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
GPMDP.media_seek
(self, position)
Send media_seek command to media player.
Send media_seek command to media player.
def media_seek(self, position): """Send media_seek command to media player.""" websocket = self.get_ws() if websocket is None: return websocket.send( json.dumps( { "namespace": "playback", "method": "setCurrentTime", "arguments": [position * 1000], } ) ) self.schedule_update_ha_state()
[ "def", "media_seek", "(", "self", ",", "position", ")", ":", "websocket", "=", "self", ".", "get_ws", "(", ")", "if", "websocket", "is", "None", ":", "return", "websocket", ".", "send", "(", "json", ".", "dumps", "(", "{", "\"namespace\"", ":", "\"playback\"", ",", "\"method\"", ":", "\"setCurrentTime\"", ",", "\"arguments\"", ":", "[", "position", "*", "1000", "]", ",", "}", ")", ")", "self", ".", "schedule_update_ha_state", "(", ")" ]
[ 341, 4 ]
[ 355, 39 ]
python
en
['en', 'en', 'en']
True
GPMDP.volume_up
(self)
Send volume_up command to media player.
Send volume_up command to media player.
def volume_up(self): """Send volume_up command to media player.""" websocket = self.get_ws() if websocket is None: return websocket.send('{"namespace": "volume", "method": "increaseVolume"}') self.schedule_update_ha_state()
[ "def", "volume_up", "(", "self", ")", ":", "websocket", "=", "self", ".", "get_ws", "(", ")", "if", "websocket", "is", "None", ":", "return", "websocket", ".", "send", "(", "'{\"namespace\": \"volume\", \"method\": \"increaseVolume\"}'", ")", "self", ".", "schedule_update_ha_state", "(", ")" ]
[ 357, 4 ]
[ 363, 39 ]
python
en
['en', 'en', 'en']
True
GPMDP.volume_down
(self)
Send volume_down command to media player.
Send volume_down command to media player.
def volume_down(self): """Send volume_down command to media player.""" websocket = self.get_ws() if websocket is None: return websocket.send('{"namespace": "volume", "method": "decreaseVolume"}') self.schedule_update_ha_state()
[ "def", "volume_down", "(", "self", ")", ":", "websocket", "=", "self", ".", "get_ws", "(", ")", "if", "websocket", "is", "None", ":", "return", "websocket", ".", "send", "(", "'{\"namespace\": \"volume\", \"method\": \"decreaseVolume\"}'", ")", "self", ".", "schedule_update_ha_state", "(", ")" ]
[ 365, 4 ]
[ 371, 39 ]
python
en
['en', 'en', 'en']
True
GPMDP.set_volume_level
(self, volume)
Set volume on media player, range(0..1).
Set volume on media player, range(0..1).
def set_volume_level(self, volume): """Set volume on media player, range(0..1).""" websocket = self.get_ws() if websocket is None: return websocket.send( json.dumps( { "namespace": "volume", "method": "setVolume", "arguments": [volume * 100], } ) ) self.schedule_update_ha_state()
[ "def", "set_volume_level", "(", "self", ",", "volume", ")", ":", "websocket", "=", "self", ".", "get_ws", "(", ")", "if", "websocket", "is", "None", ":", "return", "websocket", ".", "send", "(", "json", ".", "dumps", "(", "{", "\"namespace\"", ":", "\"volume\"", ",", "\"method\"", ":", "\"setVolume\"", ",", "\"arguments\"", ":", "[", "volume", "*", "100", "]", ",", "}", ")", ")", "self", ".", "schedule_update_ha_state", "(", ")" ]
[ 373, 4 ]
[ 387, 39 ]
python
en
['nl', 'no', 'en']
False
test_create_matcher
()
Test the create matcher method.
Test the create matcher method.
def test_create_matcher(): """Test the create matcher method.""" # Basic sentence pattern = create_matcher("Hello world") assert pattern.match("Hello world") is not None # Match a part pattern = create_matcher("Hello {name}") match = pattern.match("hello world") assert match is not None assert match.groupdict()["name"] == "world" no_match = pattern.match("Hello world, how are you?") assert no_match is None # Optional and matching part pattern = create_matcher("Turn on [the] {name}") match = pattern.match("turn on the kitchen lights") assert match is not None assert match.groupdict()["name"] == "kitchen lights" match = pattern.match("turn on kitchen lights") assert match is not None assert match.groupdict()["name"] == "kitchen lights" match = pattern.match("turn off kitchen lights") assert match is None # Two different optional parts, 1 matching part pattern = create_matcher("Turn on [the] [a] {name}") match = pattern.match("turn on the kitchen lights") assert match is not None assert match.groupdict()["name"] == "kitchen lights" match = pattern.match("turn on kitchen lights") assert match is not None assert match.groupdict()["name"] == "kitchen lights" match = pattern.match("turn on a kitchen light") assert match is not None assert match.groupdict()["name"] == "kitchen light" # Strip plural pattern = create_matcher("Turn {name}[s] on") match = pattern.match("turn kitchen lights on") assert match is not None assert match.groupdict()["name"] == "kitchen light" # Optional 2 words pattern = create_matcher("Turn [the great] {name} on") match = pattern.match("turn the great kitchen lights on") assert match is not None assert match.groupdict()["name"] == "kitchen lights" match = pattern.match("turn kitchen lights on") assert match is not None assert match.groupdict()["name"] == "kitchen lights"
[ "def", "test_create_matcher", "(", ")", ":", "# Basic sentence", "pattern", "=", "create_matcher", "(", "\"Hello world\"", ")", "assert", "pattern", ".", "match", "(", "\"Hello world\"", ")", "is", "not", "None", "# Match a part", "pattern", "=", "create_matcher", "(", "\"Hello {name}\"", ")", "match", "=", "pattern", ".", "match", "(", "\"hello world\"", ")", "assert", "match", "is", "not", "None", "assert", "match", ".", "groupdict", "(", ")", "[", "\"name\"", "]", "==", "\"world\"", "no_match", "=", "pattern", ".", "match", "(", "\"Hello world, how are you?\"", ")", "assert", "no_match", "is", "None", "# Optional and matching part", "pattern", "=", "create_matcher", "(", "\"Turn on [the] {name}\"", ")", "match", "=", "pattern", ".", "match", "(", "\"turn on the kitchen lights\"", ")", "assert", "match", "is", "not", "None", "assert", "match", ".", "groupdict", "(", ")", "[", "\"name\"", "]", "==", "\"kitchen lights\"", "match", "=", "pattern", ".", "match", "(", "\"turn on kitchen lights\"", ")", "assert", "match", "is", "not", "None", "assert", "match", ".", "groupdict", "(", ")", "[", "\"name\"", "]", "==", "\"kitchen lights\"", "match", "=", "pattern", ".", "match", "(", "\"turn off kitchen lights\"", ")", "assert", "match", "is", "None", "# Two different optional parts, 1 matching part", "pattern", "=", "create_matcher", "(", "\"Turn on [the] [a] {name}\"", ")", "match", "=", "pattern", ".", "match", "(", "\"turn on the kitchen lights\"", ")", "assert", "match", "is", "not", "None", "assert", "match", ".", "groupdict", "(", ")", "[", "\"name\"", "]", "==", "\"kitchen lights\"", "match", "=", "pattern", ".", "match", "(", "\"turn on kitchen lights\"", ")", "assert", "match", "is", "not", "None", "assert", "match", ".", "groupdict", "(", ")", "[", "\"name\"", "]", "==", "\"kitchen lights\"", "match", "=", "pattern", ".", "match", "(", "\"turn on a kitchen light\"", ")", "assert", "match", "is", "not", "None", "assert", "match", ".", "groupdict", "(", ")", "[", "\"name\"", "]", "==", "\"kitchen light\"", "# Strip plural", "pattern", "=", "create_matcher", "(", "\"Turn {name}[s] on\"", ")", "match", "=", "pattern", ".", "match", "(", "\"turn kitchen lights on\"", ")", "assert", "match", "is", "not", "None", "assert", "match", ".", "groupdict", "(", ")", "[", "\"name\"", "]", "==", "\"kitchen light\"", "# Optional 2 words", "pattern", "=", "create_matcher", "(", "\"Turn [the great] {name} on\"", ")", "match", "=", "pattern", ".", "match", "(", "\"turn the great kitchen lights on\"", ")", "assert", "match", "is", "not", "None", "assert", "match", ".", "groupdict", "(", ")", "[", "\"name\"", "]", "==", "\"kitchen lights\"", "match", "=", "pattern", ".", "match", "(", "\"turn kitchen lights on\"", ")", "assert", "match", "is", "not", "None", "assert", "match", ".", "groupdict", "(", ")", "[", "\"name\"", "]", "==", "\"kitchen lights\"" ]
[ 4, 0 ]
[ 54, 56 ]
python
en
['en', 'zh', 'en']
True
mock_dev_track
(mock_device_tracker_conf)
Mock device tracker config loading.
Mock device tracker config loading.
def mock_dev_track(mock_device_tracker_conf): """Mock device tracker config loading.""" pass
[ "def", "mock_dev_track", "(", "mock_device_tracker_conf", ")", ":", "pass" ]
[ 18, 0 ]
[ 20, 8 ]
python
en
['da', 'en', 'en']
True
locative_client
(loop, hass, hass_client)
Locative mock client.
Locative mock client.
async def locative_client(loop, hass, hass_client): """Locative mock client.""" assert await async_setup_component(hass, DOMAIN, {DOMAIN: {}}) await hass.async_block_till_done() with patch("homeassistant.components.device_tracker.legacy.update_config"): return await hass_client()
[ "async", "def", "locative_client", "(", "loop", ",", "hass", ",", "hass_client", ")", ":", "assert", "await", "async_setup_component", "(", "hass", ",", "DOMAIN", ",", "{", "DOMAIN", ":", "{", "}", "}", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "with", "patch", "(", "\"homeassistant.components.device_tracker.legacy.update_config\"", ")", ":", "return", "await", "hass_client", "(", ")" ]
[ 24, 0 ]
[ 30, 34 ]
python
en
['pl', 'en', 'pt']
False
webhook_id
(hass, locative_client)
Initialize the Geofency component and get the webhook_id.
Initialize the Geofency component and get the webhook_id.
async def webhook_id(hass, locative_client): """Initialize the Geofency component and get the webhook_id.""" await async_process_ha_core_config( hass, {"internal_url": "http://example.local:8123"}, ) result = await hass.config_entries.flow.async_init( "locative", context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM, result result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY await hass.async_block_till_done() return result["result"].data["webhook_id"]
[ "async", "def", "webhook_id", "(", "hass", ",", "locative_client", ")", ":", "await", "async_process_ha_core_config", "(", "hass", ",", "{", "\"internal_url\"", ":", "\"http://example.local:8123\"", "}", ",", ")", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "\"locative\"", ",", "context", "=", "{", "\"source\"", ":", "\"user\"", "}", ")", "assert", "result", "[", "\"type\"", "]", "==", "data_entry_flow", ".", "RESULT_TYPE_FORM", ",", "result", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_configure", "(", "result", "[", "\"flow_id\"", "]", ",", "{", "}", ")", "assert", "result", "[", "\"type\"", "]", "==", "data_entry_flow", ".", "RESULT_TYPE_CREATE_ENTRY", "await", "hass", ".", "async_block_till_done", "(", ")", "return", "result", "[", "\"result\"", "]", ".", "data", "[", "\"webhook_id\"", "]" ]
[ 34, 0 ]
[ 49, 46 ]
python
en
['en', 'en', 'en']
True
test_missing_data
(locative_client, webhook_id)
Test missing data.
Test missing data.
async def test_missing_data(locative_client, webhook_id): """Test missing data.""" url = f"/api/webhook/{webhook_id}" data = { "latitude": 1.0, "longitude": 1.1, "device": "123", "id": "Home", "trigger": "enter", } # No data req = await locative_client.post(url) assert req.status == HTTP_UNPROCESSABLE_ENTITY # No latitude copy = data.copy() del copy["latitude"] req = await locative_client.post(url, data=copy) assert req.status == HTTP_UNPROCESSABLE_ENTITY # No device copy = data.copy() del copy["device"] req = await locative_client.post(url, data=copy) assert req.status == HTTP_UNPROCESSABLE_ENTITY # No location copy = data.copy() del copy["id"] req = await locative_client.post(url, data=copy) assert req.status == HTTP_UNPROCESSABLE_ENTITY # No trigger copy = data.copy() del copy["trigger"] req = await locative_client.post(url, data=copy) assert req.status == HTTP_UNPROCESSABLE_ENTITY # Test message copy = data.copy() copy["trigger"] = "test" req = await locative_client.post(url, data=copy) assert req.status == HTTP_OK # Test message, no location copy = data.copy() copy["trigger"] = "test" del copy["id"] req = await locative_client.post(url, data=copy) assert req.status == HTTP_OK # Unknown trigger copy = data.copy() copy["trigger"] = "foobar" req = await locative_client.post(url, data=copy) assert req.status == HTTP_UNPROCESSABLE_ENTITY
[ "async", "def", "test_missing_data", "(", "locative_client", ",", "webhook_id", ")", ":", "url", "=", "f\"/api/webhook/{webhook_id}\"", "data", "=", "{", "\"latitude\"", ":", "1.0", ",", "\"longitude\"", ":", "1.1", ",", "\"device\"", ":", "\"123\"", ",", "\"id\"", ":", "\"Home\"", ",", "\"trigger\"", ":", "\"enter\"", ",", "}", "# No data", "req", "=", "await", "locative_client", ".", "post", "(", "url", ")", "assert", "req", ".", "status", "==", "HTTP_UNPROCESSABLE_ENTITY", "# No latitude", "copy", "=", "data", ".", "copy", "(", ")", "del", "copy", "[", "\"latitude\"", "]", "req", "=", "await", "locative_client", ".", "post", "(", "url", ",", "data", "=", "copy", ")", "assert", "req", ".", "status", "==", "HTTP_UNPROCESSABLE_ENTITY", "# No device", "copy", "=", "data", ".", "copy", "(", ")", "del", "copy", "[", "\"device\"", "]", "req", "=", "await", "locative_client", ".", "post", "(", "url", ",", "data", "=", "copy", ")", "assert", "req", ".", "status", "==", "HTTP_UNPROCESSABLE_ENTITY", "# No location", "copy", "=", "data", ".", "copy", "(", ")", "del", "copy", "[", "\"id\"", "]", "req", "=", "await", "locative_client", ".", "post", "(", "url", ",", "data", "=", "copy", ")", "assert", "req", ".", "status", "==", "HTTP_UNPROCESSABLE_ENTITY", "# No trigger", "copy", "=", "data", ".", "copy", "(", ")", "del", "copy", "[", "\"trigger\"", "]", "req", "=", "await", "locative_client", ".", "post", "(", "url", ",", "data", "=", "copy", ")", "assert", "req", ".", "status", "==", "HTTP_UNPROCESSABLE_ENTITY", "# Test message", "copy", "=", "data", ".", "copy", "(", ")", "copy", "[", "\"trigger\"", "]", "=", "\"test\"", "req", "=", "await", "locative_client", ".", "post", "(", "url", ",", "data", "=", "copy", ")", "assert", "req", ".", "status", "==", "HTTP_OK", "# Test message, no location", "copy", "=", "data", ".", "copy", "(", ")", "copy", "[", "\"trigger\"", "]", "=", "\"test\"", "del", "copy", "[", "\"id\"", "]", "req", "=", "await", "locative_client", ".", "post", "(", "url", ",", "data", "=", "copy", ")", "assert", "req", ".", "status", "==", "HTTP_OK", "# Unknown trigger", "copy", "=", "data", ".", "copy", "(", ")", "copy", "[", "\"trigger\"", "]", "=", "\"foobar\"", "req", "=", "await", "locative_client", ".", "post", "(", "url", ",", "data", "=", "copy", ")", "assert", "req", ".", "status", "==", "HTTP_UNPROCESSABLE_ENTITY" ]
[ 52, 0 ]
[ 109, 50 ]
python
de
['de', 'no', 'en']
False
test_enter_and_exit
(hass, locative_client, webhook_id)
Test when there is a known zone.
Test when there is a known zone.
async def test_enter_and_exit(hass, locative_client, webhook_id): """Test when there is a known zone.""" url = f"/api/webhook/{webhook_id}" data = { "latitude": 40.7855, "longitude": -111.7367, "device": "123", "id": "Home", "trigger": "enter", } # Enter the Home req = await locative_client.post(url, data=data) await hass.async_block_till_done() assert req.status == HTTP_OK state_name = hass.states.get( "{}.{}".format(DEVICE_TRACKER_DOMAIN, data["device"]) ).state assert state_name == "home" data["id"] = "HOME" data["trigger"] = "exit" # Exit Home req = await locative_client.post(url, data=data) await hass.async_block_till_done() assert req.status == HTTP_OK state_name = hass.states.get( "{}.{}".format(DEVICE_TRACKER_DOMAIN, data["device"]) ).state assert state_name == "not_home" data["id"] = "hOmE" data["trigger"] = "enter" # Enter Home again req = await locative_client.post(url, data=data) await hass.async_block_till_done() assert req.status == HTTP_OK state_name = hass.states.get( "{}.{}".format(DEVICE_TRACKER_DOMAIN, data["device"]) ).state assert state_name == "home" data["trigger"] = "exit" # Exit Home req = await locative_client.post(url, data=data) await hass.async_block_till_done() assert req.status == HTTP_OK state_name = hass.states.get( "{}.{}".format(DEVICE_TRACKER_DOMAIN, data["device"]) ).state assert state_name == "not_home" data["id"] = "work" data["trigger"] = "enter" # Enter Work req = await locative_client.post(url, data=data) await hass.async_block_till_done() assert req.status == HTTP_OK state_name = hass.states.get( "{}.{}".format(DEVICE_TRACKER_DOMAIN, data["device"]) ).state assert state_name == "work"
[ "async", "def", "test_enter_and_exit", "(", "hass", ",", "locative_client", ",", "webhook_id", ")", ":", "url", "=", "f\"/api/webhook/{webhook_id}\"", "data", "=", "{", "\"latitude\"", ":", "40.7855", ",", "\"longitude\"", ":", "-", "111.7367", ",", "\"device\"", ":", "\"123\"", ",", "\"id\"", ":", "\"Home\"", ",", "\"trigger\"", ":", "\"enter\"", ",", "}", "# Enter the Home", "req", "=", "await", "locative_client", ".", "post", "(", "url", ",", "data", "=", "data", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "req", ".", "status", "==", "HTTP_OK", "state_name", "=", "hass", ".", "states", ".", "get", "(", "\"{}.{}\"", ".", "format", "(", "DEVICE_TRACKER_DOMAIN", ",", "data", "[", "\"device\"", "]", ")", ")", ".", "state", "assert", "state_name", "==", "\"home\"", "data", "[", "\"id\"", "]", "=", "\"HOME\"", "data", "[", "\"trigger\"", "]", "=", "\"exit\"", "# Exit Home", "req", "=", "await", "locative_client", ".", "post", "(", "url", ",", "data", "=", "data", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "req", ".", "status", "==", "HTTP_OK", "state_name", "=", "hass", ".", "states", ".", "get", "(", "\"{}.{}\"", ".", "format", "(", "DEVICE_TRACKER_DOMAIN", ",", "data", "[", "\"device\"", "]", ")", ")", ".", "state", "assert", "state_name", "==", "\"not_home\"", "data", "[", "\"id\"", "]", "=", "\"hOmE\"", "data", "[", "\"trigger\"", "]", "=", "\"enter\"", "# Enter Home again", "req", "=", "await", "locative_client", ".", "post", "(", "url", ",", "data", "=", "data", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "req", ".", "status", "==", "HTTP_OK", "state_name", "=", "hass", ".", "states", ".", "get", "(", "\"{}.{}\"", ".", "format", "(", "DEVICE_TRACKER_DOMAIN", ",", "data", "[", "\"device\"", "]", ")", ")", ".", "state", "assert", "state_name", "==", "\"home\"", "data", "[", "\"trigger\"", "]", "=", "\"exit\"", "# Exit Home", "req", "=", "await", "locative_client", ".", "post", "(", "url", ",", "data", "=", "data", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "req", ".", "status", "==", "HTTP_OK", "state_name", "=", "hass", ".", "states", ".", "get", "(", "\"{}.{}\"", ".", "format", "(", "DEVICE_TRACKER_DOMAIN", ",", "data", "[", "\"device\"", "]", ")", ")", ".", "state", "assert", "state_name", "==", "\"not_home\"", "data", "[", "\"id\"", "]", "=", "\"work\"", "data", "[", "\"trigger\"", "]", "=", "\"enter\"", "# Enter Work", "req", "=", "await", "locative_client", ".", "post", "(", "url", ",", "data", "=", "data", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "req", ".", "status", "==", "HTTP_OK", "state_name", "=", "hass", ".", "states", ".", "get", "(", "\"{}.{}\"", ".", "format", "(", "DEVICE_TRACKER_DOMAIN", ",", "data", "[", "\"device\"", "]", ")", ")", ".", "state", "assert", "state_name", "==", "\"work\"" ]
[ 112, 0 ]
[ 178, 31 ]
python
en
['en', 'en', 'en']
True
test_exit_after_enter
(hass, locative_client, webhook_id)
Test when an exit message comes after an enter message.
Test when an exit message comes after an enter message.
async def test_exit_after_enter(hass, locative_client, webhook_id): """Test when an exit message comes after an enter message.""" url = f"/api/webhook/{webhook_id}" data = { "latitude": 40.7855, "longitude": -111.7367, "device": "123", "id": "Home", "trigger": "enter", } # Enter Home req = await locative_client.post(url, data=data) await hass.async_block_till_done() assert req.status == HTTP_OK state = hass.states.get("{}.{}".format(DEVICE_TRACKER_DOMAIN, data["device"])) assert state.state == "home" data["id"] = "Work" # Enter Work req = await locative_client.post(url, data=data) await hass.async_block_till_done() assert req.status == HTTP_OK state = hass.states.get("{}.{}".format(DEVICE_TRACKER_DOMAIN, data["device"])) assert state.state == "work" data["id"] = "Home" data["trigger"] = "exit" # Exit Home req = await locative_client.post(url, data=data) await hass.async_block_till_done() assert req.status == HTTP_OK state = hass.states.get("{}.{}".format(DEVICE_TRACKER_DOMAIN, data["device"])) assert state.state == "work"
[ "async", "def", "test_exit_after_enter", "(", "hass", ",", "locative_client", ",", "webhook_id", ")", ":", "url", "=", "f\"/api/webhook/{webhook_id}\"", "data", "=", "{", "\"latitude\"", ":", "40.7855", ",", "\"longitude\"", ":", "-", "111.7367", ",", "\"device\"", ":", "\"123\"", ",", "\"id\"", ":", "\"Home\"", ",", "\"trigger\"", ":", "\"enter\"", ",", "}", "# Enter Home", "req", "=", "await", "locative_client", ".", "post", "(", "url", ",", "data", "=", "data", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "req", ".", "status", "==", "HTTP_OK", "state", "=", "hass", ".", "states", ".", "get", "(", "\"{}.{}\"", ".", "format", "(", "DEVICE_TRACKER_DOMAIN", ",", "data", "[", "\"device\"", "]", ")", ")", "assert", "state", ".", "state", "==", "\"home\"", "data", "[", "\"id\"", "]", "=", "\"Work\"", "# Enter Work", "req", "=", "await", "locative_client", ".", "post", "(", "url", ",", "data", "=", "data", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "req", ".", "status", "==", "HTTP_OK", "state", "=", "hass", ".", "states", ".", "get", "(", "\"{}.{}\"", ".", "format", "(", "DEVICE_TRACKER_DOMAIN", ",", "data", "[", "\"device\"", "]", ")", ")", "assert", "state", ".", "state", "==", "\"work\"", "data", "[", "\"id\"", "]", "=", "\"Home\"", "data", "[", "\"trigger\"", "]", "=", "\"exit\"", "# Exit Home", "req", "=", "await", "locative_client", ".", "post", "(", "url", ",", "data", "=", "data", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "req", ".", "status", "==", "HTTP_OK", "state", "=", "hass", ".", "states", ".", "get", "(", "\"{}.{}\"", ".", "format", "(", "DEVICE_TRACKER_DOMAIN", ",", "data", "[", "\"device\"", "]", ")", ")", "assert", "state", ".", "state", "==", "\"work\"" ]
[ 181, 0 ]
[ 220, 32 ]
python
en
['en', 'en', 'en']
True
test_exit_first
(hass, locative_client, webhook_id)
Test when an exit message is sent first on a new device.
Test when an exit message is sent first on a new device.
async def test_exit_first(hass, locative_client, webhook_id): """Test when an exit message is sent first on a new device.""" url = f"/api/webhook/{webhook_id}" data = { "latitude": 40.7855, "longitude": -111.7367, "device": "new_device", "id": "Home", "trigger": "exit", } # Exit Home req = await locative_client.post(url, data=data) await hass.async_block_till_done() assert req.status == HTTP_OK state = hass.states.get("{}.{}".format(DEVICE_TRACKER_DOMAIN, data["device"])) assert state.state == "not_home"
[ "async", "def", "test_exit_first", "(", "hass", ",", "locative_client", ",", "webhook_id", ")", ":", "url", "=", "f\"/api/webhook/{webhook_id}\"", "data", "=", "{", "\"latitude\"", ":", "40.7855", ",", "\"longitude\"", ":", "-", "111.7367", ",", "\"device\"", ":", "\"new_device\"", ",", "\"id\"", ":", "\"Home\"", ",", "\"trigger\"", ":", "\"exit\"", ",", "}", "# Exit Home", "req", "=", "await", "locative_client", ".", "post", "(", "url", ",", "data", "=", "data", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "req", ".", "status", "==", "HTTP_OK", "state", "=", "hass", ".", "states", ".", "get", "(", "\"{}.{}\"", ".", "format", "(", "DEVICE_TRACKER_DOMAIN", ",", "data", "[", "\"device\"", "]", ")", ")", "assert", "state", ".", "state", "==", "\"not_home\"" ]
[ 223, 0 ]
[ 241, 36 ]
python
en
['en', 'en', 'en']
True
test_two_devices
(hass, locative_client, webhook_id)
Test updating two different devices.
Test updating two different devices.
async def test_two_devices(hass, locative_client, webhook_id): """Test updating two different devices.""" url = f"/api/webhook/{webhook_id}" data_device_1 = { "latitude": 40.7855, "longitude": -111.7367, "device": "device_1", "id": "Home", "trigger": "exit", } # Exit Home req = await locative_client.post(url, data=data_device_1) await hass.async_block_till_done() assert req.status == HTTP_OK state = hass.states.get( "{}.{}".format(DEVICE_TRACKER_DOMAIN, data_device_1["device"]) ) assert state.state == "not_home" # Enter Home data_device_2 = dict(data_device_1) data_device_2["device"] = "device_2" data_device_2["trigger"] = "enter" req = await locative_client.post(url, data=data_device_2) await hass.async_block_till_done() assert req.status == HTTP_OK state = hass.states.get( "{}.{}".format(DEVICE_TRACKER_DOMAIN, data_device_2["device"]) ) assert state.state == "home" state = hass.states.get( "{}.{}".format(DEVICE_TRACKER_DOMAIN, data_device_1["device"]) ) assert state.state == "not_home"
[ "async", "def", "test_two_devices", "(", "hass", ",", "locative_client", ",", "webhook_id", ")", ":", "url", "=", "f\"/api/webhook/{webhook_id}\"", "data_device_1", "=", "{", "\"latitude\"", ":", "40.7855", ",", "\"longitude\"", ":", "-", "111.7367", ",", "\"device\"", ":", "\"device_1\"", ",", "\"id\"", ":", "\"Home\"", ",", "\"trigger\"", ":", "\"exit\"", ",", "}", "# Exit Home", "req", "=", "await", "locative_client", ".", "post", "(", "url", ",", "data", "=", "data_device_1", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "req", ".", "status", "==", "HTTP_OK", "state", "=", "hass", ".", "states", ".", "get", "(", "\"{}.{}\"", ".", "format", "(", "DEVICE_TRACKER_DOMAIN", ",", "data_device_1", "[", "\"device\"", "]", ")", ")", "assert", "state", ".", "state", "==", "\"not_home\"", "# Enter Home", "data_device_2", "=", "dict", "(", "data_device_1", ")", "data_device_2", "[", "\"device\"", "]", "=", "\"device_2\"", "data_device_2", "[", "\"trigger\"", "]", "=", "\"enter\"", "req", "=", "await", "locative_client", ".", "post", "(", "url", ",", "data", "=", "data_device_2", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "req", ".", "status", "==", "HTTP_OK", "state", "=", "hass", ".", "states", ".", "get", "(", "\"{}.{}\"", ".", "format", "(", "DEVICE_TRACKER_DOMAIN", ",", "data_device_2", "[", "\"device\"", "]", ")", ")", "assert", "state", ".", "state", "==", "\"home\"", "state", "=", "hass", ".", "states", ".", "get", "(", "\"{}.{}\"", ".", "format", "(", "DEVICE_TRACKER_DOMAIN", ",", "data_device_1", "[", "\"device\"", "]", ")", ")", "assert", "state", ".", "state", "==", "\"not_home\"" ]
[ 244, 0 ]
[ 281, 36 ]
python
en
['en', 'en', 'en']
True
test_load_unload_entry
(hass, locative_client, webhook_id)
Test that the appropriate dispatch signals are added and removed.
Test that the appropriate dispatch signals are added and removed.
async def test_load_unload_entry(hass, locative_client, webhook_id): """Test that the appropriate dispatch signals are added and removed.""" url = f"/api/webhook/{webhook_id}" data = { "latitude": 40.7855, "longitude": -111.7367, "device": "new_device", "id": "Home", "trigger": "exit", } # Exit Home req = await locative_client.post(url, data=data) await hass.async_block_till_done() assert req.status == HTTP_OK state = hass.states.get("{}.{}".format(DEVICE_TRACKER_DOMAIN, data["device"])) assert state.state == "not_home" assert len(hass.data[DATA_DISPATCHER][TRACKER_UPDATE]) == 1 entry = hass.config_entries.async_entries(DOMAIN)[0] await locative.async_unload_entry(hass, entry) await hass.async_block_till_done() assert not hass.data[DATA_DISPATCHER][TRACKER_UPDATE]
[ "async", "def", "test_load_unload_entry", "(", "hass", ",", "locative_client", ",", "webhook_id", ")", ":", "url", "=", "f\"/api/webhook/{webhook_id}\"", "data", "=", "{", "\"latitude\"", ":", "40.7855", ",", "\"longitude\"", ":", "-", "111.7367", ",", "\"device\"", ":", "\"new_device\"", ",", "\"id\"", ":", "\"Home\"", ",", "\"trigger\"", ":", "\"exit\"", ",", "}", "# Exit Home", "req", "=", "await", "locative_client", ".", "post", "(", "url", ",", "data", "=", "data", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "req", ".", "status", "==", "HTTP_OK", "state", "=", "hass", ".", "states", ".", "get", "(", "\"{}.{}\"", ".", "format", "(", "DEVICE_TRACKER_DOMAIN", ",", "data", "[", "\"device\"", "]", ")", ")", "assert", "state", ".", "state", "==", "\"not_home\"", "assert", "len", "(", "hass", ".", "data", "[", "DATA_DISPATCHER", "]", "[", "TRACKER_UPDATE", "]", ")", "==", "1", "entry", "=", "hass", ".", "config_entries", ".", "async_entries", "(", "DOMAIN", ")", "[", "0", "]", "await", "locative", ".", "async_unload_entry", "(", "hass", ",", "entry", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "not", "hass", ".", "data", "[", "DATA_DISPATCHER", "]", "[", "TRACKER_UPDATE", "]" ]
[ 287, 0 ]
[ 312, 57 ]
python
en
['en', 'en', 'en']
True
scatter
(inputs, target_gpus, chunk_sizes, dim=0)
r""" Slices tensors into approximately equal chunks and distributes them across given GPUs. Duplicates references to objects that are not tensors.
r""" Slices tensors into approximately equal chunks and distributes them across given GPUs. Duplicates references to objects that are not tensors.
def scatter(inputs, target_gpus, chunk_sizes, dim=0): r""" Slices tensors into approximately equal chunks and distributes them across given GPUs. Duplicates references to objects that are not tensors. """ def scatter_map(obj): if isinstance(obj, torch.Tensor): try: return Scatter.apply(target_gpus, chunk_sizes, dim, obj) except: print('obj', obj.size()) print('dim', dim) print('chunk_sizes', chunk_sizes) quit() if isinstance(obj, tuple) and len(obj) > 0: return list(zip(*map(scatter_map, obj))) if isinstance(obj, list) and len(obj) > 0: return list(map(list, zip(*map(scatter_map, obj)))) if isinstance(obj, dict) and len(obj) > 0: return list(map(type(obj), zip(*map(scatter_map, obj.items())))) return [obj for targets in target_gpus] # After scatter_map is called, a scatter_map cell will exist. This cell # has a reference to the actual function scatter_map, which has references # to a closure that has a reference to the scatter_map cell (because the # fn is recursive). To avoid this reference cycle, we set the function to # None, clearing the cell try: return scatter_map(inputs) finally: scatter_map = None
[ "def", "scatter", "(", "inputs", ",", "target_gpus", ",", "chunk_sizes", ",", "dim", "=", "0", ")", ":", "def", "scatter_map", "(", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "torch", ".", "Tensor", ")", ":", "try", ":", "return", "Scatter", ".", "apply", "(", "target_gpus", ",", "chunk_sizes", ",", "dim", ",", "obj", ")", "except", ":", "print", "(", "'obj'", ",", "obj", ".", "size", "(", ")", ")", "print", "(", "'dim'", ",", "dim", ")", "print", "(", "'chunk_sizes'", ",", "chunk_sizes", ")", "quit", "(", ")", "if", "isinstance", "(", "obj", ",", "tuple", ")", "and", "len", "(", "obj", ")", ">", "0", ":", "return", "list", "(", "zip", "(", "*", "map", "(", "scatter_map", ",", "obj", ")", ")", ")", "if", "isinstance", "(", "obj", ",", "list", ")", "and", "len", "(", "obj", ")", ">", "0", ":", "return", "list", "(", "map", "(", "list", ",", "zip", "(", "*", "map", "(", "scatter_map", ",", "obj", ")", ")", ")", ")", "if", "isinstance", "(", "obj", ",", "dict", ")", "and", "len", "(", "obj", ")", ">", "0", ":", "return", "list", "(", "map", "(", "type", "(", "obj", ")", ",", "zip", "(", "*", "map", "(", "scatter_map", ",", "obj", ".", "items", "(", ")", ")", ")", ")", ")", "return", "[", "obj", "for", "targets", "in", "target_gpus", "]", "# After scatter_map is called, a scatter_map cell will exist. This cell", "# has a reference to the actual function scatter_map, which has references", "# to a closure that has a reference to the scatter_map cell (because the", "# fn is recursive). To avoid this reference cycle, we set the function to", "# None, clearing the cell", "try", ":", "return", "scatter_map", "(", "inputs", ")", "finally", ":", "scatter_map", "=", "None" ]
[ 6, 0 ]
[ 37, 26 ]
python
cy
['en', 'cy', 'hi']
False
scatter_kwargs
(inputs, kwargs, target_gpus, chunk_sizes, dim=0)
r"""Scatter with support for kwargs dictionary
r"""Scatter with support for kwargs dictionary
def scatter_kwargs(inputs, kwargs, target_gpus, chunk_sizes, dim=0): r"""Scatter with support for kwargs dictionary""" inputs = scatter(inputs, target_gpus, chunk_sizes, dim) if inputs else [] kwargs = scatter(kwargs, target_gpus, chunk_sizes, dim) if kwargs else [] if len(inputs) < len(kwargs): inputs.extend([() for _ in range(len(kwargs) - len(inputs))]) elif len(kwargs) < len(inputs): kwargs.extend([{} for _ in range(len(inputs) - len(kwargs))]) inputs = tuple(inputs) kwargs = tuple(kwargs) return inputs, kwargs
[ "def", "scatter_kwargs", "(", "inputs", ",", "kwargs", ",", "target_gpus", ",", "chunk_sizes", ",", "dim", "=", "0", ")", ":", "inputs", "=", "scatter", "(", "inputs", ",", "target_gpus", ",", "chunk_sizes", ",", "dim", ")", "if", "inputs", "else", "[", "]", "kwargs", "=", "scatter", "(", "kwargs", ",", "target_gpus", ",", "chunk_sizes", ",", "dim", ")", "if", "kwargs", "else", "[", "]", "if", "len", "(", "inputs", ")", "<", "len", "(", "kwargs", ")", ":", "inputs", ".", "extend", "(", "[", "(", ")", "for", "_", "in", "range", "(", "len", "(", "kwargs", ")", "-", "len", "(", "inputs", ")", ")", "]", ")", "elif", "len", "(", "kwargs", ")", "<", "len", "(", "inputs", ")", ":", "kwargs", ".", "extend", "(", "[", "{", "}", "for", "_", "in", "range", "(", "len", "(", "inputs", ")", "-", "len", "(", "kwargs", ")", ")", "]", ")", "inputs", "=", "tuple", "(", "inputs", ")", "kwargs", "=", "tuple", "(", "kwargs", ")", "return", "inputs", ",", "kwargs" ]
[ 39, 0 ]
[ 49, 25 ]
python
en
['en', 'en', 'sw']
True
_name_validator
(config)
Validate the name.
Validate the name.
def _name_validator(config): """Validate the name.""" config = copy.deepcopy(config) for address, device_config in config[CONF_DEVICES].items(): if CONF_NAME not in device_config: device_config[CONF_NAME] = util.slugify(address) return config
[ "def", "_name_validator", "(", "config", ")", ":", "config", "=", "copy", ".", "deepcopy", "(", "config", ")", "for", "address", ",", "device_config", "in", "config", "[", "CONF_DEVICES", "]", ".", "items", "(", ")", ":", "if", "CONF_NAME", "not", "in", "device_config", ":", "device_config", "[", "CONF_NAME", "]", "=", "util", ".", "slugify", "(", "address", ")", "return", "config" ]
[ 27, 0 ]
[ 34, 17 ]
python
en
['en', 'en', 'en']
True
retry
(method)
Retry bluetooth commands.
Retry bluetooth commands.
def retry(method): """Retry bluetooth commands.""" @wraps(method) def wrapper_retry(device, *args, **kwargs): """Try send command and retry on error.""" initial = time.monotonic() while True: if time.monotonic() - initial >= 10: return None try: return method(device, *args, **kwargs) except (decora.decoraException, AttributeError, BTLEException): _LOGGER.warning( "Decora connect error for device %s. Reconnecting...", device.name, ) # pylint: disable=protected-access device._switch.connect() return wrapper_retry
[ "def", "retry", "(", "method", ")", ":", "@", "wraps", "(", "method", ")", "def", "wrapper_retry", "(", "device", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"Try send command and retry on error.\"\"\"", "initial", "=", "time", ".", "monotonic", "(", ")", "while", "True", ":", "if", "time", ".", "monotonic", "(", ")", "-", "initial", ">=", "10", ":", "return", "None", "try", ":", "return", "method", "(", "device", ",", "*", "args", ",", "*", "*", "kwargs", ")", "except", "(", "decora", ".", "decoraException", ",", "AttributeError", ",", "BTLEException", ")", ":", "_LOGGER", ".", "warning", "(", "\"Decora connect error for device %s. Reconnecting...\"", ",", "device", ".", "name", ",", ")", "# pylint: disable=protected-access", "device", ".", "_switch", ".", "connect", "(", ")", "return", "wrapper_retry" ]
[ 51, 0 ]
[ 72, 24 ]
python
en
['en', 'pt', 'en']
True
setup_platform
(hass, config, add_entities, discovery_info=None)
Set up an Decora switch.
Set up an Decora switch.
def setup_platform(hass, config, add_entities, discovery_info=None): """Set up an Decora switch.""" lights = [] for address, device_config in config[CONF_DEVICES].items(): device = {} device["name"] = device_config[CONF_NAME] device["key"] = device_config[CONF_API_KEY] device["address"] = address light = DecoraLight(device) lights.append(light) add_entities(lights)
[ "def", "setup_platform", "(", "hass", ",", "config", ",", "add_entities", ",", "discovery_info", "=", "None", ")", ":", "lights", "=", "[", "]", "for", "address", ",", "device_config", "in", "config", "[", "CONF_DEVICES", "]", ".", "items", "(", ")", ":", "device", "=", "{", "}", "device", "[", "\"name\"", "]", "=", "device_config", "[", "CONF_NAME", "]", "device", "[", "\"key\"", "]", "=", "device_config", "[", "CONF_API_KEY", "]", "device", "[", "\"address\"", "]", "=", "address", "light", "=", "DecoraLight", "(", "device", ")", "lights", ".", "append", "(", "light", ")", "add_entities", "(", "lights", ")" ]
[ 75, 0 ]
[ 86, 24 ]
python
en
['en', 'lb', 'en']
True
DecoraLight.__init__
(self, device)
Initialize the light.
Initialize the light.
def __init__(self, device): """Initialize the light.""" self._name = device["name"] self._address = device["address"] self._key = device["key"] self._switch = decora.decora(self._address, self._key) self._brightness = 0 self._state = False
[ "def", "__init__", "(", "self", ",", "device", ")", ":", "self", ".", "_name", "=", "device", "[", "\"name\"", "]", "self", ".", "_address", "=", "device", "[", "\"address\"", "]", "self", ".", "_key", "=", "device", "[", "\"key\"", "]", "self", ".", "_switch", "=", "decora", ".", "decora", "(", "self", ".", "_address", ",", "self", ".", "_key", ")", "self", ".", "_brightness", "=", "0", "self", ".", "_state", "=", "False" ]
[ 92, 4 ]
[ 100, 27 ]
python
en
['en', 'en', 'en']
True
DecoraLight.unique_id
(self)
Return the ID of this light.
Return the ID of this light.
def unique_id(self): """Return the ID of this light.""" return self._address
[ "def", "unique_id", "(", "self", ")", ":", "return", "self", ".", "_address" ]
[ 103, 4 ]
[ 105, 28 ]
python
en
['en', 'en', 'en']
True
DecoraLight.name
(self)
Return the name of the device if any.
Return the name of the device if any.
def name(self): """Return the name of the device if any.""" return self._name
[ "def", "name", "(", "self", ")", ":", "return", "self", ".", "_name" ]
[ 108, 4 ]
[ 110, 25 ]
python
en
['en', 'en', 'en']
True
DecoraLight.is_on
(self)
Return true if device is on.
Return true if device is on.
def is_on(self): """Return true if device is on.""" return self._state
[ "def", "is_on", "(", "self", ")", ":", "return", "self", ".", "_state" ]
[ 113, 4 ]
[ 115, 26 ]
python
en
['en', 'fy', 'en']
True
DecoraLight.brightness
(self)
Return the brightness of this light between 0..255.
Return the brightness of this light between 0..255.
def brightness(self): """Return the brightness of this light between 0..255.""" return self._brightness
[ "def", "brightness", "(", "self", ")", ":", "return", "self", ".", "_brightness" ]
[ 118, 4 ]
[ 120, 31 ]
python
en
['en', 'en', 'en']
True
DecoraLight.supported_features
(self)
Flag supported features.
Flag supported features.
def supported_features(self): """Flag supported features.""" return SUPPORT_DECORA_LED
[ "def", "supported_features", "(", "self", ")", ":", "return", "SUPPORT_DECORA_LED" ]
[ 123, 4 ]
[ 125, 33 ]
python
en
['da', 'en', 'en']
True
DecoraLight.assumed_state
(self)
We can read the actual state.
We can read the actual state.
def assumed_state(self): """We can read the actual state.""" return False
[ "def", "assumed_state", "(", "self", ")", ":", "return", "False" ]
[ 128, 4 ]
[ 130, 20 ]
python
en
['en', 'en', 'en']
True
DecoraLight.set_state
(self, brightness)
Set the state of this lamp to the provided brightness.
Set the state of this lamp to the provided brightness.
def set_state(self, brightness): """Set the state of this lamp to the provided brightness.""" self._switch.set_brightness(int(brightness / 2.55)) self._brightness = brightness
[ "def", "set_state", "(", "self", ",", "brightness", ")", ":", "self", ".", "_switch", ".", "set_brightness", "(", "int", "(", "brightness", "/", "2.55", ")", ")", "self", ".", "_brightness", "=", "brightness" ]
[ 133, 4 ]
[ 136, 37 ]
python
en
['en', 'en', 'en']
True
DecoraLight.turn_on
(self, **kwargs)
Turn the specified or all lights on.
Turn the specified or all lights on.
def turn_on(self, **kwargs): """Turn the specified or all lights on.""" brightness = kwargs.get(ATTR_BRIGHTNESS) self._switch.on() self._state = True if brightness is not None: self.set_state(brightness)
[ "def", "turn_on", "(", "self", ",", "*", "*", "kwargs", ")", ":", "brightness", "=", "kwargs", ".", "get", "(", "ATTR_BRIGHTNESS", ")", "self", ".", "_switch", ".", "on", "(", ")", "self", ".", "_state", "=", "True", "if", "brightness", "is", "not", "None", ":", "self", ".", "set_state", "(", "brightness", ")" ]
[ 139, 4 ]
[ 146, 38 ]
python
en
['en', 'en', 'en']
True
DecoraLight.turn_off
(self, **kwargs)
Turn the specified or all lights off.
Turn the specified or all lights off.
def turn_off(self, **kwargs): """Turn the specified or all lights off.""" self._switch.off() self._state = False
[ "def", "turn_off", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_switch", ".", "off", "(", ")", "self", ".", "_state", "=", "False" ]
[ 149, 4 ]
[ 152, 27 ]
python
en
['en', 'en', 'en']
True
DecoraLight.update
(self)
Synchronise internal state with the actual light state.
Synchronise internal state with the actual light state.
def update(self): """Synchronise internal state with the actual light state.""" self._brightness = self._switch.get_brightness() * 2.55 self._state = self._switch.get_on()
[ "def", "update", "(", "self", ")", ":", "self", ".", "_brightness", "=", "self", ".", "_switch", ".", "get_brightness", "(", ")", "*", "2.55", "self", ".", "_state", "=", "self", ".", "_switch", ".", "get_on", "(", ")" ]
[ 155, 4 ]
[ 158, 43 ]
python
en
['en', 'en', 'en']
True
test_api_adjust_brightness
(hass, result, adjust)
Test api adjust brightness process.
Test api adjust brightness process.
async def test_api_adjust_brightness(hass, result, adjust): """Test api adjust brightness process.""" request = get_new_request( "Alexa.BrightnessController", "AdjustBrightness", "light#test" ) # add payload request["directive"]["payload"]["brightnessDelta"] = adjust # setup test devices hass.states.async_set( "light.test", "off", {"friendly_name": "Test light", "brightness": "77"} ) call_light = async_mock_service(hass, "light", "turn_on") msg = await smart_home.async_handle_message(hass, DEFAULT_CONFIG, request) await hass.async_block_till_done() assert "event" in msg msg = msg["event"] assert len(call_light) == 1 assert call_light[0].data["entity_id"] == "light.test" assert call_light[0].data["brightness_pct"] == result assert msg["header"]["name"] == "Response"
[ "async", "def", "test_api_adjust_brightness", "(", "hass", ",", "result", ",", "adjust", ")", ":", "request", "=", "get_new_request", "(", "\"Alexa.BrightnessController\"", ",", "\"AdjustBrightness\"", ",", "\"light#test\"", ")", "# add payload", "request", "[", "\"directive\"", "]", "[", "\"payload\"", "]", "[", "\"brightnessDelta\"", "]", "=", "adjust", "# setup test devices", "hass", ".", "states", ".", "async_set", "(", "\"light.test\"", ",", "\"off\"", ",", "{", "\"friendly_name\"", ":", "\"Test light\"", ",", "\"brightness\"", ":", "\"77\"", "}", ")", "call_light", "=", "async_mock_service", "(", "hass", ",", "\"light\"", ",", "\"turn_on\"", ")", "msg", "=", "await", "smart_home", ".", "async_handle_message", "(", "hass", ",", "DEFAULT_CONFIG", ",", "request", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "\"event\"", "in", "msg", "msg", "=", "msg", "[", "\"event\"", "]", "assert", "len", "(", "call_light", ")", "==", "1", "assert", "call_light", "[", "0", "]", ".", "data", "[", "\"entity_id\"", "]", "==", "\"light.test\"", "assert", "call_light", "[", "0", "]", ".", "data", "[", "\"brightness_pct\"", "]", "==", "result", "assert", "msg", "[", "\"header\"", "]", "[", "\"name\"", "]", "==", "\"Response\"" ]
[ 40, 0 ]
[ 65, 46 ]
python
en
['en', 'bs', 'en']
True
test_api_set_color_rgb
(hass)
Test api set color process.
Test api set color process.
async def test_api_set_color_rgb(hass): """Test api set color process.""" request = get_new_request("Alexa.ColorController", "SetColor", "light#test") # add payload request["directive"]["payload"]["color"] = { "hue": "120", "saturation": "0.612", "brightness": "0.342", } # setup test devices hass.states.async_set( "light.test", "off", {"friendly_name": "Test light", "supported_features": 16} ) call_light = async_mock_service(hass, "light", "turn_on") msg = await smart_home.async_handle_message(hass, DEFAULT_CONFIG, request) await hass.async_block_till_done() assert "event" in msg msg = msg["event"] assert len(call_light) == 1 assert call_light[0].data["entity_id"] == "light.test" assert call_light[0].data["rgb_color"] == (33, 87, 33) assert msg["header"]["name"] == "Response"
[ "async", "def", "test_api_set_color_rgb", "(", "hass", ")", ":", "request", "=", "get_new_request", "(", "\"Alexa.ColorController\"", ",", "\"SetColor\"", ",", "\"light#test\"", ")", "# add payload", "request", "[", "\"directive\"", "]", "[", "\"payload\"", "]", "[", "\"color\"", "]", "=", "{", "\"hue\"", ":", "\"120\"", ",", "\"saturation\"", ":", "\"0.612\"", ",", "\"brightness\"", ":", "\"0.342\"", ",", "}", "# setup test devices", "hass", ".", "states", ".", "async_set", "(", "\"light.test\"", ",", "\"off\"", ",", "{", "\"friendly_name\"", ":", "\"Test light\"", ",", "\"supported_features\"", ":", "16", "}", ")", "call_light", "=", "async_mock_service", "(", "hass", ",", "\"light\"", ",", "\"turn_on\"", ")", "msg", "=", "await", "smart_home", ".", "async_handle_message", "(", "hass", ",", "DEFAULT_CONFIG", ",", "request", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "\"event\"", "in", "msg", "msg", "=", "msg", "[", "\"event\"", "]", "assert", "len", "(", "call_light", ")", "==", "1", "assert", "call_light", "[", "0", "]", ".", "data", "[", "\"entity_id\"", "]", "==", "\"light.test\"", "assert", "call_light", "[", "0", "]", ".", "data", "[", "\"rgb_color\"", "]", "==", "(", "33", ",", "87", ",", "33", ")", "assert", "msg", "[", "\"header\"", "]", "[", "\"name\"", "]", "==", "\"Response\"" ]
[ 68, 0 ]
[ 95, 46 ]
python
en
['ro', 'fr', 'en']
False
test_api_set_color_temperature
(hass)
Test api set color temperature process.
Test api set color temperature process.
async def test_api_set_color_temperature(hass): """Test api set color temperature process.""" request = get_new_request( "Alexa.ColorTemperatureController", "SetColorTemperature", "light#test" ) # add payload request["directive"]["payload"]["colorTemperatureInKelvin"] = "7500" # setup test devices hass.states.async_set("light.test", "off", {"friendly_name": "Test light"}) call_light = async_mock_service(hass, "light", "turn_on") msg = await smart_home.async_handle_message(hass, DEFAULT_CONFIG, request) await hass.async_block_till_done() assert "event" in msg msg = msg["event"] assert len(call_light) == 1 assert call_light[0].data["entity_id"] == "light.test" assert call_light[0].data["kelvin"] == 7500 assert msg["header"]["name"] == "Response"
[ "async", "def", "test_api_set_color_temperature", "(", "hass", ")", ":", "request", "=", "get_new_request", "(", "\"Alexa.ColorTemperatureController\"", ",", "\"SetColorTemperature\"", ",", "\"light#test\"", ")", "# add payload", "request", "[", "\"directive\"", "]", "[", "\"payload\"", "]", "[", "\"colorTemperatureInKelvin\"", "]", "=", "\"7500\"", "# setup test devices", "hass", ".", "states", ".", "async_set", "(", "\"light.test\"", ",", "\"off\"", ",", "{", "\"friendly_name\"", ":", "\"Test light\"", "}", ")", "call_light", "=", "async_mock_service", "(", "hass", ",", "\"light\"", ",", "\"turn_on\"", ")", "msg", "=", "await", "smart_home", ".", "async_handle_message", "(", "hass", ",", "DEFAULT_CONFIG", ",", "request", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "\"event\"", "in", "msg", "msg", "=", "msg", "[", "\"event\"", "]", "assert", "len", "(", "call_light", ")", "==", "1", "assert", "call_light", "[", "0", "]", ".", "data", "[", "\"entity_id\"", "]", "==", "\"light.test\"", "assert", "call_light", "[", "0", "]", ".", "data", "[", "\"kelvin\"", "]", "==", "7500", "assert", "msg", "[", "\"header\"", "]", "[", "\"name\"", "]", "==", "\"Response\"" ]
[ 98, 0 ]
[ 121, 46 ]
python
ca
['ro', 'ca', 'en']
False
test_api_decrease_color_temp
(hass, result, initial)
Test api decrease color temp process.
Test api decrease color temp process.
async def test_api_decrease_color_temp(hass, result, initial): """Test api decrease color temp process.""" request = get_new_request( "Alexa.ColorTemperatureController", "DecreaseColorTemperature", "light#test" ) # setup test devices hass.states.async_set( "light.test", "off", {"friendly_name": "Test light", "color_temp": initial, "max_mireds": 500}, ) call_light = async_mock_service(hass, "light", "turn_on") msg = await smart_home.async_handle_message(hass, DEFAULT_CONFIG, request) await hass.async_block_till_done() assert "event" in msg msg = msg["event"] assert len(call_light) == 1 assert call_light[0].data["entity_id"] == "light.test" assert call_light[0].data["color_temp"] == result assert msg["header"]["name"] == "Response"
[ "async", "def", "test_api_decrease_color_temp", "(", "hass", ",", "result", ",", "initial", ")", ":", "request", "=", "get_new_request", "(", "\"Alexa.ColorTemperatureController\"", ",", "\"DecreaseColorTemperature\"", ",", "\"light#test\"", ")", "# setup test devices", "hass", ".", "states", ".", "async_set", "(", "\"light.test\"", ",", "\"off\"", ",", "{", "\"friendly_name\"", ":", "\"Test light\"", ",", "\"color_temp\"", ":", "initial", ",", "\"max_mireds\"", ":", "500", "}", ",", ")", "call_light", "=", "async_mock_service", "(", "hass", ",", "\"light\"", ",", "\"turn_on\"", ")", "msg", "=", "await", "smart_home", ".", "async_handle_message", "(", "hass", ",", "DEFAULT_CONFIG", ",", "request", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "\"event\"", "in", "msg", "msg", "=", "msg", "[", "\"event\"", "]", "assert", "len", "(", "call_light", ")", "==", "1", "assert", "call_light", "[", "0", "]", ".", "data", "[", "\"entity_id\"", "]", "==", "\"light.test\"", "assert", "call_light", "[", "0", "]", ".", "data", "[", "\"color_temp\"", "]", "==", "result", "assert", "msg", "[", "\"header\"", "]", "[", "\"name\"", "]", "==", "\"Response\"" ]
[ 125, 0 ]
[ 149, 46 ]
python
ro
['ro', 'ro', 'en']
True
test_api_increase_color_temp
(hass, result, initial)
Test api increase color temp process.
Test api increase color temp process.
async def test_api_increase_color_temp(hass, result, initial): """Test api increase color temp process.""" request = get_new_request( "Alexa.ColorTemperatureController", "IncreaseColorTemperature", "light#test" ) # setup test devices hass.states.async_set( "light.test", "off", {"friendly_name": "Test light", "color_temp": initial, "min_mireds": 142}, ) call_light = async_mock_service(hass, "light", "turn_on") msg = await smart_home.async_handle_message(hass, DEFAULT_CONFIG, request) await hass.async_block_till_done() assert "event" in msg msg = msg["event"] assert len(call_light) == 1 assert call_light[0].data["entity_id"] == "light.test" assert call_light[0].data["color_temp"] == result assert msg["header"]["name"] == "Response"
[ "async", "def", "test_api_increase_color_temp", "(", "hass", ",", "result", ",", "initial", ")", ":", "request", "=", "get_new_request", "(", "\"Alexa.ColorTemperatureController\"", ",", "\"IncreaseColorTemperature\"", ",", "\"light#test\"", ")", "# setup test devices", "hass", ".", "states", ".", "async_set", "(", "\"light.test\"", ",", "\"off\"", ",", "{", "\"friendly_name\"", ":", "\"Test light\"", ",", "\"color_temp\"", ":", "initial", ",", "\"min_mireds\"", ":", "142", "}", ",", ")", "call_light", "=", "async_mock_service", "(", "hass", ",", "\"light\"", ",", "\"turn_on\"", ")", "msg", "=", "await", "smart_home", ".", "async_handle_message", "(", "hass", ",", "DEFAULT_CONFIG", ",", "request", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "\"event\"", "in", "msg", "msg", "=", "msg", "[", "\"event\"", "]", "assert", "len", "(", "call_light", ")", "==", "1", "assert", "call_light", "[", "0", "]", ".", "data", "[", "\"entity_id\"", "]", "==", "\"light.test\"", "assert", "call_light", "[", "0", "]", ".", "data", "[", "\"color_temp\"", "]", "==", "result", "assert", "msg", "[", "\"header\"", "]", "[", "\"name\"", "]", "==", "\"Response\"" ]
[ 153, 0 ]
[ 177, 46 ]
python
en
['en', 'sm', 'en']
True
test_api_select_input
(hass, domain, payload, source_list, idx)
Test api set input process.
Test api set input process.
async def test_api_select_input(hass, domain, payload, source_list, idx): """Test api set input process.""" hass.states.async_set( "media_player.test", "off", { "friendly_name": "Test media player", "source": "unknown", "source_list": source_list, }, ) # test where no source matches if idx is None: await assert_request_fails( "Alexa.InputController", "SelectInput", "media_player#test", "media_player.select_source", hass, payload={"input": payload}, ) return call, _ = await assert_request_calls_service( "Alexa.InputController", "SelectInput", "media_player#test", "media_player.select_source", hass, payload={"input": payload}, ) assert call.data["source"] == source_list[idx]
[ "async", "def", "test_api_select_input", "(", "hass", ",", "domain", ",", "payload", ",", "source_list", ",", "idx", ")", ":", "hass", ".", "states", ".", "async_set", "(", "\"media_player.test\"", ",", "\"off\"", ",", "{", "\"friendly_name\"", ":", "\"Test media player\"", ",", "\"source\"", ":", "\"unknown\"", ",", "\"source_list\"", ":", "source_list", ",", "}", ",", ")", "# test where no source matches", "if", "idx", "is", "None", ":", "await", "assert_request_fails", "(", "\"Alexa.InputController\"", ",", "\"SelectInput\"", ",", "\"media_player#test\"", ",", "\"media_player.select_source\"", ",", "hass", ",", "payload", "=", "{", "\"input\"", ":", "payload", "}", ",", ")", "return", "call", ",", "_", "=", "await", "assert_request_calls_service", "(", "\"Alexa.InputController\"", ",", "\"SelectInput\"", ",", "\"media_player#test\"", ",", "\"media_player.select_source\"", ",", "hass", ",", "payload", "=", "{", "\"input\"", ":", "payload", "}", ",", ")", "assert", "call", ".", "data", "[", "\"source\"", "]", "==", "source_list", "[", "idx", "]" ]
[ 189, 0 ]
[ 221, 50 ]
python
da
['da', 'su', 'en']
False
test_report_lock_state
(hass)
Test LockController implements lockState property.
Test LockController implements lockState property.
async def test_report_lock_state(hass): """Test LockController implements lockState property.""" hass.states.async_set("lock.locked", STATE_LOCKED, {}) hass.states.async_set("lock.unlocked", STATE_UNLOCKED, {}) hass.states.async_set("lock.unknown", STATE_UNKNOWN, {}) properties = await reported_properties(hass, "lock.locked") properties.assert_equal("Alexa.LockController", "lockState", "LOCKED") properties = await reported_properties(hass, "lock.unlocked") properties.assert_equal("Alexa.LockController", "lockState", "UNLOCKED") properties = await reported_properties(hass, "lock.unknown") properties.assert_equal("Alexa.LockController", "lockState", "JAMMED")
[ "async", "def", "test_report_lock_state", "(", "hass", ")", ":", "hass", ".", "states", ".", "async_set", "(", "\"lock.locked\"", ",", "STATE_LOCKED", ",", "{", "}", ")", "hass", ".", "states", ".", "async_set", "(", "\"lock.unlocked\"", ",", "STATE_UNLOCKED", ",", "{", "}", ")", "hass", ".", "states", ".", "async_set", "(", "\"lock.unknown\"", ",", "STATE_UNKNOWN", ",", "{", "}", ")", "properties", "=", "await", "reported_properties", "(", "hass", ",", "\"lock.locked\"", ")", "properties", ".", "assert_equal", "(", "\"Alexa.LockController\"", ",", "\"lockState\"", ",", "\"LOCKED\"", ")", "properties", "=", "await", "reported_properties", "(", "hass", ",", "\"lock.unlocked\"", ")", "properties", ".", "assert_equal", "(", "\"Alexa.LockController\"", ",", "\"lockState\"", ",", "\"UNLOCKED\"", ")", "properties", "=", "await", "reported_properties", "(", "hass", ",", "\"lock.unknown\"", ")", "properties", ".", "assert_equal", "(", "\"Alexa.LockController\"", ",", "\"lockState\"", ",", "\"JAMMED\"", ")" ]
[ 224, 0 ]
[ 237, 74 ]
python
en
['da', 'en', 'en']
True
test_report_dimmable_light_state
(hass)
Test BrightnessController reports brightness correctly.
Test BrightnessController reports brightness correctly.
async def test_report_dimmable_light_state(hass): """Test BrightnessController reports brightness correctly.""" hass.states.async_set( "light.test_on", "on", {"friendly_name": "Test light On", "brightness": 128, "supported_features": 1}, ) hass.states.async_set( "light.test_off", "off", {"friendly_name": "Test light Off", "supported_features": 1}, ) properties = await reported_properties(hass, "light.test_on") properties.assert_equal("Alexa.BrightnessController", "brightness", 50) properties = await reported_properties(hass, "light.test_off") properties.assert_equal("Alexa.BrightnessController", "brightness", 0)
[ "async", "def", "test_report_dimmable_light_state", "(", "hass", ")", ":", "hass", ".", "states", ".", "async_set", "(", "\"light.test_on\"", ",", "\"on\"", ",", "{", "\"friendly_name\"", ":", "\"Test light On\"", ",", "\"brightness\"", ":", "128", ",", "\"supported_features\"", ":", "1", "}", ",", ")", "hass", ".", "states", ".", "async_set", "(", "\"light.test_off\"", ",", "\"off\"", ",", "{", "\"friendly_name\"", ":", "\"Test light Off\"", ",", "\"supported_features\"", ":", "1", "}", ",", ")", "properties", "=", "await", "reported_properties", "(", "hass", ",", "\"light.test_on\"", ")", "properties", ".", "assert_equal", "(", "\"Alexa.BrightnessController\"", ",", "\"brightness\"", ",", "50", ")", "properties", "=", "await", "reported_properties", "(", "hass", ",", "\"light.test_off\"", ")", "properties", ".", "assert_equal", "(", "\"Alexa.BrightnessController\"", ",", "\"brightness\"", ",", "0", ")" ]
[ 240, 0 ]
[ 257, 74 ]
python
en
['en', 'zu', 'en']
True
test_report_colored_light_state
(hass)
Test ColorController reports color correctly.
Test ColorController reports color correctly.
async def test_report_colored_light_state(hass): """Test ColorController reports color correctly.""" hass.states.async_set( "light.test_on", "on", { "friendly_name": "Test light On", "hs_color": (180, 75), "brightness": 128, "supported_features": 17, }, ) hass.states.async_set( "light.test_off", "off", {"friendly_name": "Test light Off", "supported_features": 17}, ) properties = await reported_properties(hass, "light.test_on") properties.assert_equal( "Alexa.ColorController", "color", {"hue": 180, "saturation": 0.75, "brightness": 128 / 255.0}, ) properties = await reported_properties(hass, "light.test_off") properties.assert_equal( "Alexa.ColorController", "color", {"hue": 0, "saturation": 0, "brightness": 0} )
[ "async", "def", "test_report_colored_light_state", "(", "hass", ")", ":", "hass", ".", "states", ".", "async_set", "(", "\"light.test_on\"", ",", "\"on\"", ",", "{", "\"friendly_name\"", ":", "\"Test light On\"", ",", "\"hs_color\"", ":", "(", "180", ",", "75", ")", ",", "\"brightness\"", ":", "128", ",", "\"supported_features\"", ":", "17", ",", "}", ",", ")", "hass", ".", "states", ".", "async_set", "(", "\"light.test_off\"", ",", "\"off\"", ",", "{", "\"friendly_name\"", ":", "\"Test light Off\"", ",", "\"supported_features\"", ":", "17", "}", ",", ")", "properties", "=", "await", "reported_properties", "(", "hass", ",", "\"light.test_on\"", ")", "properties", ".", "assert_equal", "(", "\"Alexa.ColorController\"", ",", "\"color\"", ",", "{", "\"hue\"", ":", "180", ",", "\"saturation\"", ":", "0.75", ",", "\"brightness\"", ":", "128", "/", "255.0", "}", ",", ")", "properties", "=", "await", "reported_properties", "(", "hass", ",", "\"light.test_off\"", ")", "properties", ".", "assert_equal", "(", "\"Alexa.ColorController\"", ",", "\"color\"", ",", "{", "\"hue\"", ":", "0", ",", "\"saturation\"", ":", "0", ",", "\"brightness\"", ":", "0", "}", ")" ]
[ 260, 0 ]
[ 288, 5 ]
python
en
['en', 'en', 'en']
True
test_report_colored_temp_light_state
(hass)
Test ColorTemperatureController reports color temp correctly.
Test ColorTemperatureController reports color temp correctly.
async def test_report_colored_temp_light_state(hass): """Test ColorTemperatureController reports color temp correctly.""" hass.states.async_set( "light.test_on", "on", {"friendly_name": "Test light On", "color_temp": 240, "supported_features": 2}, ) hass.states.async_set( "light.test_off", "off", {"friendly_name": "Test light Off", "supported_features": 2}, ) properties = await reported_properties(hass, "light.test_on") properties.assert_equal( "Alexa.ColorTemperatureController", "colorTemperatureInKelvin", 4166 ) properties = await reported_properties(hass, "light.test_off") properties.assert_not_has_property( "Alexa.ColorTemperatureController", "colorTemperatureInKelvin" )
[ "async", "def", "test_report_colored_temp_light_state", "(", "hass", ")", ":", "hass", ".", "states", ".", "async_set", "(", "\"light.test_on\"", ",", "\"on\"", ",", "{", "\"friendly_name\"", ":", "\"Test light On\"", ",", "\"color_temp\"", ":", "240", ",", "\"supported_features\"", ":", "2", "}", ",", ")", "hass", ".", "states", ".", "async_set", "(", "\"light.test_off\"", ",", "\"off\"", ",", "{", "\"friendly_name\"", ":", "\"Test light Off\"", ",", "\"supported_features\"", ":", "2", "}", ",", ")", "properties", "=", "await", "reported_properties", "(", "hass", ",", "\"light.test_on\"", ")", "properties", ".", "assert_equal", "(", "\"Alexa.ColorTemperatureController\"", ",", "\"colorTemperatureInKelvin\"", ",", "4166", ")", "properties", "=", "await", "reported_properties", "(", "hass", ",", "\"light.test_off\"", ")", "properties", ".", "assert_not_has_property", "(", "\"Alexa.ColorTemperatureController\"", ",", "\"colorTemperatureInKelvin\"", ")" ]
[ 291, 0 ]
[ 312, 5 ]
python
en
['en', 'en', 'en']
True
test_report_fan_speed_state
(hass)
Test PercentageController, PowerLevelController, RangeController reports fan speed correctly.
Test PercentageController, PowerLevelController, RangeController reports fan speed correctly.
async def test_report_fan_speed_state(hass): """Test PercentageController, PowerLevelController, RangeController reports fan speed correctly.""" hass.states.async_set( "fan.off", "off", { "friendly_name": "Off fan", "speed": "off", "supported_features": 1, "speed_list": ["off", "low", "medium", "high"], }, ) hass.states.async_set( "fan.low_speed", "on", { "friendly_name": "Low speed fan", "speed": "low", "supported_features": 1, "speed_list": ["off", "low", "medium", "high"], }, ) hass.states.async_set( "fan.medium_speed", "on", { "friendly_name": "Medium speed fan", "speed": "medium", "supported_features": 1, "speed_list": ["off", "low", "medium", "high"], }, ) hass.states.async_set( "fan.high_speed", "on", { "friendly_name": "High speed fan", "speed": "high", "supported_features": 1, "speed_list": ["off", "low", "medium", "high"], }, ) properties = await reported_properties(hass, "fan.off") properties.assert_equal("Alexa.PercentageController", "percentage", 0) properties.assert_equal("Alexa.PowerLevelController", "powerLevel", 0) properties.assert_equal("Alexa.RangeController", "rangeValue", 0) properties = await reported_properties(hass, "fan.low_speed") properties.assert_equal("Alexa.PercentageController", "percentage", 33) properties.assert_equal("Alexa.PowerLevelController", "powerLevel", 33) properties.assert_equal("Alexa.RangeController", "rangeValue", 1) properties = await reported_properties(hass, "fan.medium_speed") properties.assert_equal("Alexa.PercentageController", "percentage", 66) properties.assert_equal("Alexa.PowerLevelController", "powerLevel", 66) properties.assert_equal("Alexa.RangeController", "rangeValue", 2) properties = await reported_properties(hass, "fan.high_speed") properties.assert_equal("Alexa.PercentageController", "percentage", 100) properties.assert_equal("Alexa.PowerLevelController", "powerLevel", 100) properties.assert_equal("Alexa.RangeController", "rangeValue", 3)
[ "async", "def", "test_report_fan_speed_state", "(", "hass", ")", ":", "hass", ".", "states", ".", "async_set", "(", "\"fan.off\"", ",", "\"off\"", ",", "{", "\"friendly_name\"", ":", "\"Off fan\"", ",", "\"speed\"", ":", "\"off\"", ",", "\"supported_features\"", ":", "1", ",", "\"speed_list\"", ":", "[", "\"off\"", ",", "\"low\"", ",", "\"medium\"", ",", "\"high\"", "]", ",", "}", ",", ")", "hass", ".", "states", ".", "async_set", "(", "\"fan.low_speed\"", ",", "\"on\"", ",", "{", "\"friendly_name\"", ":", "\"Low speed fan\"", ",", "\"speed\"", ":", "\"low\"", ",", "\"supported_features\"", ":", "1", ",", "\"speed_list\"", ":", "[", "\"off\"", ",", "\"low\"", ",", "\"medium\"", ",", "\"high\"", "]", ",", "}", ",", ")", "hass", ".", "states", ".", "async_set", "(", "\"fan.medium_speed\"", ",", "\"on\"", ",", "{", "\"friendly_name\"", ":", "\"Medium speed fan\"", ",", "\"speed\"", ":", "\"medium\"", ",", "\"supported_features\"", ":", "1", ",", "\"speed_list\"", ":", "[", "\"off\"", ",", "\"low\"", ",", "\"medium\"", ",", "\"high\"", "]", ",", "}", ",", ")", "hass", ".", "states", ".", "async_set", "(", "\"fan.high_speed\"", ",", "\"on\"", ",", "{", "\"friendly_name\"", ":", "\"High speed fan\"", ",", "\"speed\"", ":", "\"high\"", ",", "\"supported_features\"", ":", "1", ",", "\"speed_list\"", ":", "[", "\"off\"", ",", "\"low\"", ",", "\"medium\"", ",", "\"high\"", "]", ",", "}", ",", ")", "properties", "=", "await", "reported_properties", "(", "hass", ",", "\"fan.off\"", ")", "properties", ".", "assert_equal", "(", "\"Alexa.PercentageController\"", ",", "\"percentage\"", ",", "0", ")", "properties", ".", "assert_equal", "(", "\"Alexa.PowerLevelController\"", ",", "\"powerLevel\"", ",", "0", ")", "properties", ".", "assert_equal", "(", "\"Alexa.RangeController\"", ",", "\"rangeValue\"", ",", "0", ")", "properties", "=", "await", "reported_properties", "(", "hass", ",", "\"fan.low_speed\"", ")", "properties", ".", "assert_equal", "(", "\"Alexa.PercentageController\"", ",", "\"percentage\"", ",", "33", ")", "properties", ".", "assert_equal", "(", "\"Alexa.PowerLevelController\"", ",", "\"powerLevel\"", ",", "33", ")", "properties", ".", "assert_equal", "(", "\"Alexa.RangeController\"", ",", "\"rangeValue\"", ",", "1", ")", "properties", "=", "await", "reported_properties", "(", "hass", ",", "\"fan.medium_speed\"", ")", "properties", ".", "assert_equal", "(", "\"Alexa.PercentageController\"", ",", "\"percentage\"", ",", "66", ")", "properties", ".", "assert_equal", "(", "\"Alexa.PowerLevelController\"", ",", "\"powerLevel\"", ",", "66", ")", "properties", ".", "assert_equal", "(", "\"Alexa.RangeController\"", ",", "\"rangeValue\"", ",", "2", ")", "properties", "=", "await", "reported_properties", "(", "hass", ",", "\"fan.high_speed\"", ")", "properties", ".", "assert_equal", "(", "\"Alexa.PercentageController\"", ",", "\"percentage\"", ",", "100", ")", "properties", ".", "assert_equal", "(", "\"Alexa.PowerLevelController\"", ",", "\"powerLevel\"", ",", "100", ")", "properties", ".", "assert_equal", "(", "\"Alexa.RangeController\"", ",", "\"rangeValue\"", ",", "3", ")" ]
[ 315, 0 ]
[ 376, 69 ]
python
en
['en', 'en', 'en']
True
test_report_fan_oscillating
(hass)
Test ToggleController reports fan oscillating correctly.
Test ToggleController reports fan oscillating correctly.
async def test_report_fan_oscillating(hass): """Test ToggleController reports fan oscillating correctly.""" hass.states.async_set( "fan.oscillating_off", "off", {"friendly_name": "fan oscillating off", "supported_features": 2}, ) hass.states.async_set( "fan.oscillating_on", "on", { "friendly_name": "Fan oscillating on", "oscillating": True, "supported_features": 2, }, ) properties = await reported_properties(hass, "fan.oscillating_off") properties.assert_equal("Alexa.ToggleController", "toggleState", "OFF") properties = await reported_properties(hass, "fan.oscillating_on") properties.assert_equal("Alexa.ToggleController", "toggleState", "ON")
[ "async", "def", "test_report_fan_oscillating", "(", "hass", ")", ":", "hass", ".", "states", ".", "async_set", "(", "\"fan.oscillating_off\"", ",", "\"off\"", ",", "{", "\"friendly_name\"", ":", "\"fan oscillating off\"", ",", "\"supported_features\"", ":", "2", "}", ",", ")", "hass", ".", "states", ".", "async_set", "(", "\"fan.oscillating_on\"", ",", "\"on\"", ",", "{", "\"friendly_name\"", ":", "\"Fan oscillating on\"", ",", "\"oscillating\"", ":", "True", ",", "\"supported_features\"", ":", "2", ",", "}", ",", ")", "properties", "=", "await", "reported_properties", "(", "hass", ",", "\"fan.oscillating_off\"", ")", "properties", ".", "assert_equal", "(", "\"Alexa.ToggleController\"", ",", "\"toggleState\"", ",", "\"OFF\"", ")", "properties", "=", "await", "reported_properties", "(", "hass", ",", "\"fan.oscillating_on\"", ")", "properties", ".", "assert_equal", "(", "\"Alexa.ToggleController\"", ",", "\"toggleState\"", ",", "\"ON\"", ")" ]
[ 379, 0 ]
[ 400, 74 ]
python
en
['en', 'en', 'en']
True
test_report_fan_direction
(hass)
Test ModeController reports fan direction correctly.
Test ModeController reports fan direction correctly.
async def test_report_fan_direction(hass): """Test ModeController reports fan direction correctly.""" hass.states.async_set( "fan.off", "off", {"friendly_name": "Off fan", "supported_features": 4} ) hass.states.async_set( "fan.reverse", "on", { "friendly_name": "Fan Reverse", "direction": "reverse", "supported_features": 4, }, ) hass.states.async_set( "fan.forward", "on", { "friendly_name": "Fan Forward", "direction": "forward", "supported_features": 4, }, ) properties = await reported_properties(hass, "fan.off") properties.assert_not_has_property("Alexa.ModeController", "mode") properties = await reported_properties(hass, "fan.reverse") properties.assert_equal("Alexa.ModeController", "mode", "direction.reverse") properties = await reported_properties(hass, "fan.forward") properties.assert_equal("Alexa.ModeController", "mode", "direction.forward")
[ "async", "def", "test_report_fan_direction", "(", "hass", ")", ":", "hass", ".", "states", ".", "async_set", "(", "\"fan.off\"", ",", "\"off\"", ",", "{", "\"friendly_name\"", ":", "\"Off fan\"", ",", "\"supported_features\"", ":", "4", "}", ")", "hass", ".", "states", ".", "async_set", "(", "\"fan.reverse\"", ",", "\"on\"", ",", "{", "\"friendly_name\"", ":", "\"Fan Reverse\"", ",", "\"direction\"", ":", "\"reverse\"", ",", "\"supported_features\"", ":", "4", ",", "}", ",", ")", "hass", ".", "states", ".", "async_set", "(", "\"fan.forward\"", ",", "\"on\"", ",", "{", "\"friendly_name\"", ":", "\"Fan Forward\"", ",", "\"direction\"", ":", "\"forward\"", ",", "\"supported_features\"", ":", "4", ",", "}", ",", ")", "properties", "=", "await", "reported_properties", "(", "hass", ",", "\"fan.off\"", ")", "properties", ".", "assert_not_has_property", "(", "\"Alexa.ModeController\"", ",", "\"mode\"", ")", "properties", "=", "await", "reported_properties", "(", "hass", ",", "\"fan.reverse\"", ")", "properties", ".", "assert_equal", "(", "\"Alexa.ModeController\"", ",", "\"mode\"", ",", "\"direction.reverse\"", ")", "properties", "=", "await", "reported_properties", "(", "hass", ",", "\"fan.forward\"", ")", "properties", ".", "assert_equal", "(", "\"Alexa.ModeController\"", ",", "\"mode\"", ",", "\"direction.forward\"", ")" ]
[ 403, 0 ]
[ 434, 80 ]
python
en
['id', 'en', 'en']
True
test_report_cover_range_value
(hass)
Test RangeController reports cover position correctly.
Test RangeController reports cover position correctly.
async def test_report_cover_range_value(hass): """Test RangeController reports cover position correctly.""" hass.states.async_set( "cover.fully_open", "open", { "friendly_name": "Fully open cover", "current_position": 100, "supported_features": 15, }, ) hass.states.async_set( "cover.half_open", "open", { "friendly_name": "Half open cover", "current_position": 50, "supported_features": 15, }, ) hass.states.async_set( "cover.closed", "closed", { "friendly_name": "Closed cover", "current_position": 0, "supported_features": 15, }, ) properties = await reported_properties(hass, "cover.fully_open") properties.assert_equal("Alexa.RangeController", "rangeValue", 100) properties = await reported_properties(hass, "cover.half_open") properties.assert_equal("Alexa.RangeController", "rangeValue", 50) properties = await reported_properties(hass, "cover.closed") properties.assert_equal("Alexa.RangeController", "rangeValue", 0)
[ "async", "def", "test_report_cover_range_value", "(", "hass", ")", ":", "hass", ".", "states", ".", "async_set", "(", "\"cover.fully_open\"", ",", "\"open\"", ",", "{", "\"friendly_name\"", ":", "\"Fully open cover\"", ",", "\"current_position\"", ":", "100", ",", "\"supported_features\"", ":", "15", ",", "}", ",", ")", "hass", ".", "states", ".", "async_set", "(", "\"cover.half_open\"", ",", "\"open\"", ",", "{", "\"friendly_name\"", ":", "\"Half open cover\"", ",", "\"current_position\"", ":", "50", ",", "\"supported_features\"", ":", "15", ",", "}", ",", ")", "hass", ".", "states", ".", "async_set", "(", "\"cover.closed\"", ",", "\"closed\"", ",", "{", "\"friendly_name\"", ":", "\"Closed cover\"", ",", "\"current_position\"", ":", "0", ",", "\"supported_features\"", ":", "15", ",", "}", ",", ")", "properties", "=", "await", "reported_properties", "(", "hass", ",", "\"cover.fully_open\"", ")", "properties", ".", "assert_equal", "(", "\"Alexa.RangeController\"", ",", "\"rangeValue\"", ",", "100", ")", "properties", "=", "await", "reported_properties", "(", "hass", ",", "\"cover.half_open\"", ")", "properties", ".", "assert_equal", "(", "\"Alexa.RangeController\"", ",", "\"rangeValue\"", ",", "50", ")", "properties", "=", "await", "reported_properties", "(", "hass", ",", "\"cover.closed\"", ")", "properties", ".", "assert_equal", "(", "\"Alexa.RangeController\"", ",", "\"rangeValue\"", ",", "0", ")" ]
[ 437, 0 ]
[ 474, 69 ]
python
en
['en', 'en', 'en']
True
test_report_climate_state
(hass)
Test ThermostatController reports state correctly.
Test ThermostatController reports state correctly.
async def test_report_climate_state(hass): """Test ThermostatController reports state correctly.""" for auto_modes in (climate.HVAC_MODE_AUTO, climate.HVAC_MODE_HEAT_COOL): hass.states.async_set( "climate.downstairs", auto_modes, { "friendly_name": "Climate Downstairs", "supported_features": 91, climate.ATTR_CURRENT_TEMPERATURE: 34, ATTR_UNIT_OF_MEASUREMENT: TEMP_CELSIUS, }, ) properties = await reported_properties(hass, "climate.downstairs") properties.assert_equal("Alexa.ThermostatController", "thermostatMode", "AUTO") properties.assert_equal( "Alexa.TemperatureSensor", "temperature", {"value": 34.0, "scale": "CELSIUS"}, ) for off_modes in (climate.HVAC_MODE_OFF, climate.HVAC_MODE_FAN_ONLY): hass.states.async_set( "climate.downstairs", off_modes, { "friendly_name": "Climate Downstairs", "supported_features": 91, climate.ATTR_CURRENT_TEMPERATURE: 34, ATTR_UNIT_OF_MEASUREMENT: TEMP_CELSIUS, }, ) properties = await reported_properties(hass, "climate.downstairs") properties.assert_equal("Alexa.ThermostatController", "thermostatMode", "OFF") properties.assert_equal( "Alexa.TemperatureSensor", "temperature", {"value": 34.0, "scale": "CELSIUS"}, ) # assert dry is reported as CUSTOM hass.states.async_set( "climate.downstairs", "dry", { "friendly_name": "Climate Downstairs", "supported_features": 91, climate.ATTR_CURRENT_TEMPERATURE: 34, ATTR_UNIT_OF_MEASUREMENT: TEMP_CELSIUS, }, ) properties = await reported_properties(hass, "climate.downstairs") properties.assert_equal("Alexa.ThermostatController", "thermostatMode", "CUSTOM") properties.assert_equal( "Alexa.TemperatureSensor", "temperature", {"value": 34.0, "scale": "CELSIUS"} ) hass.states.async_set( "climate.heat", "heat", { "friendly_name": "Climate Heat", "supported_features": 91, climate.ATTR_CURRENT_TEMPERATURE: 34, ATTR_UNIT_OF_MEASUREMENT: TEMP_CELSIUS, }, ) properties = await reported_properties(hass, "climate.heat") properties.assert_equal("Alexa.ThermostatController", "thermostatMode", "HEAT") properties.assert_equal( "Alexa.TemperatureSensor", "temperature", {"value": 34.0, "scale": "CELSIUS"} ) hass.states.async_set( "climate.cool", "cool", { "friendly_name": "Climate Cool", "supported_features": 91, climate.ATTR_CURRENT_TEMPERATURE: 34, ATTR_UNIT_OF_MEASUREMENT: TEMP_CELSIUS, }, ) properties = await reported_properties(hass, "climate.cool") properties.assert_equal("Alexa.ThermostatController", "thermostatMode", "COOL") properties.assert_equal( "Alexa.TemperatureSensor", "temperature", {"value": 34.0, "scale": "CELSIUS"} ) hass.states.async_set( "climate.unavailable", "unavailable", {"friendly_name": "Climate Unavailable", "supported_features": 91}, ) properties = await reported_properties(hass, "climate.unavailable") properties.assert_not_has_property("Alexa.ThermostatController", "thermostatMode") hass.states.async_set( "climate.unsupported", "blablabla", { "friendly_name": "Climate Unsupported", "supported_features": 91, climate.ATTR_CURRENT_TEMPERATURE: 34, ATTR_UNIT_OF_MEASUREMENT: TEMP_CELSIUS, }, ) with pytest.raises(UnsupportedProperty): properties = await reported_properties(hass, "climate.unsupported") properties.assert_not_has_property( "Alexa.ThermostatController", "thermostatMode" ) properties.assert_equal( "Alexa.TemperatureSensor", "temperature", {"value": 34.0, "scale": "CELSIUS"}, )
[ "async", "def", "test_report_climate_state", "(", "hass", ")", ":", "for", "auto_modes", "in", "(", "climate", ".", "HVAC_MODE_AUTO", ",", "climate", ".", "HVAC_MODE_HEAT_COOL", ")", ":", "hass", ".", "states", ".", "async_set", "(", "\"climate.downstairs\"", ",", "auto_modes", ",", "{", "\"friendly_name\"", ":", "\"Climate Downstairs\"", ",", "\"supported_features\"", ":", "91", ",", "climate", ".", "ATTR_CURRENT_TEMPERATURE", ":", "34", ",", "ATTR_UNIT_OF_MEASUREMENT", ":", "TEMP_CELSIUS", ",", "}", ",", ")", "properties", "=", "await", "reported_properties", "(", "hass", ",", "\"climate.downstairs\"", ")", "properties", ".", "assert_equal", "(", "\"Alexa.ThermostatController\"", ",", "\"thermostatMode\"", ",", "\"AUTO\"", ")", "properties", ".", "assert_equal", "(", "\"Alexa.TemperatureSensor\"", ",", "\"temperature\"", ",", "{", "\"value\"", ":", "34.0", ",", "\"scale\"", ":", "\"CELSIUS\"", "}", ",", ")", "for", "off_modes", "in", "(", "climate", ".", "HVAC_MODE_OFF", ",", "climate", ".", "HVAC_MODE_FAN_ONLY", ")", ":", "hass", ".", "states", ".", "async_set", "(", "\"climate.downstairs\"", ",", "off_modes", ",", "{", "\"friendly_name\"", ":", "\"Climate Downstairs\"", ",", "\"supported_features\"", ":", "91", ",", "climate", ".", "ATTR_CURRENT_TEMPERATURE", ":", "34", ",", "ATTR_UNIT_OF_MEASUREMENT", ":", "TEMP_CELSIUS", ",", "}", ",", ")", "properties", "=", "await", "reported_properties", "(", "hass", ",", "\"climate.downstairs\"", ")", "properties", ".", "assert_equal", "(", "\"Alexa.ThermostatController\"", ",", "\"thermostatMode\"", ",", "\"OFF\"", ")", "properties", ".", "assert_equal", "(", "\"Alexa.TemperatureSensor\"", ",", "\"temperature\"", ",", "{", "\"value\"", ":", "34.0", ",", "\"scale\"", ":", "\"CELSIUS\"", "}", ",", ")", "# assert dry is reported as CUSTOM", "hass", ".", "states", ".", "async_set", "(", "\"climate.downstairs\"", ",", "\"dry\"", ",", "{", "\"friendly_name\"", ":", "\"Climate Downstairs\"", ",", "\"supported_features\"", ":", "91", ",", "climate", ".", "ATTR_CURRENT_TEMPERATURE", ":", "34", ",", "ATTR_UNIT_OF_MEASUREMENT", ":", "TEMP_CELSIUS", ",", "}", ",", ")", "properties", "=", "await", "reported_properties", "(", "hass", ",", "\"climate.downstairs\"", ")", "properties", ".", "assert_equal", "(", "\"Alexa.ThermostatController\"", ",", "\"thermostatMode\"", ",", "\"CUSTOM\"", ")", "properties", ".", "assert_equal", "(", "\"Alexa.TemperatureSensor\"", ",", "\"temperature\"", ",", "{", "\"value\"", ":", "34.0", ",", "\"scale\"", ":", "\"CELSIUS\"", "}", ")", "hass", ".", "states", ".", "async_set", "(", "\"climate.heat\"", ",", "\"heat\"", ",", "{", "\"friendly_name\"", ":", "\"Climate Heat\"", ",", "\"supported_features\"", ":", "91", ",", "climate", ".", "ATTR_CURRENT_TEMPERATURE", ":", "34", ",", "ATTR_UNIT_OF_MEASUREMENT", ":", "TEMP_CELSIUS", ",", "}", ",", ")", "properties", "=", "await", "reported_properties", "(", "hass", ",", "\"climate.heat\"", ")", "properties", ".", "assert_equal", "(", "\"Alexa.ThermostatController\"", ",", "\"thermostatMode\"", ",", "\"HEAT\"", ")", "properties", ".", "assert_equal", "(", "\"Alexa.TemperatureSensor\"", ",", "\"temperature\"", ",", "{", "\"value\"", ":", "34.0", ",", "\"scale\"", ":", "\"CELSIUS\"", "}", ")", "hass", ".", "states", ".", "async_set", "(", "\"climate.cool\"", ",", "\"cool\"", ",", "{", "\"friendly_name\"", ":", "\"Climate Cool\"", ",", "\"supported_features\"", ":", "91", ",", "climate", ".", "ATTR_CURRENT_TEMPERATURE", ":", "34", ",", "ATTR_UNIT_OF_MEASUREMENT", ":", "TEMP_CELSIUS", ",", "}", ",", ")", "properties", "=", "await", "reported_properties", "(", "hass", ",", "\"climate.cool\"", ")", "properties", ".", "assert_equal", "(", "\"Alexa.ThermostatController\"", ",", "\"thermostatMode\"", ",", "\"COOL\"", ")", "properties", ".", "assert_equal", "(", "\"Alexa.TemperatureSensor\"", ",", "\"temperature\"", ",", "{", "\"value\"", ":", "34.0", ",", "\"scale\"", ":", "\"CELSIUS\"", "}", ")", "hass", ".", "states", ".", "async_set", "(", "\"climate.unavailable\"", ",", "\"unavailable\"", ",", "{", "\"friendly_name\"", ":", "\"Climate Unavailable\"", ",", "\"supported_features\"", ":", "91", "}", ",", ")", "properties", "=", "await", "reported_properties", "(", "hass", ",", "\"climate.unavailable\"", ")", "properties", ".", "assert_not_has_property", "(", "\"Alexa.ThermostatController\"", ",", "\"thermostatMode\"", ")", "hass", ".", "states", ".", "async_set", "(", "\"climate.unsupported\"", ",", "\"blablabla\"", ",", "{", "\"friendly_name\"", ":", "\"Climate Unsupported\"", ",", "\"supported_features\"", ":", "91", ",", "climate", ".", "ATTR_CURRENT_TEMPERATURE", ":", "34", ",", "ATTR_UNIT_OF_MEASUREMENT", ":", "TEMP_CELSIUS", ",", "}", ",", ")", "with", "pytest", ".", "raises", "(", "UnsupportedProperty", ")", ":", "properties", "=", "await", "reported_properties", "(", "hass", ",", "\"climate.unsupported\"", ")", "properties", ".", "assert_not_has_property", "(", "\"Alexa.ThermostatController\"", ",", "\"thermostatMode\"", ")", "properties", ".", "assert_equal", "(", "\"Alexa.TemperatureSensor\"", ",", "\"temperature\"", ",", "{", "\"value\"", ":", "34.0", ",", "\"scale\"", ":", "\"CELSIUS\"", "}", ",", ")" ]
[ 477, 0 ]
[ 593, 9 ]
python
en
['en', 'en', 'en']
True
test_temperature_sensor_sensor
(hass)
Test TemperatureSensor reports sensor temperature correctly.
Test TemperatureSensor reports sensor temperature correctly.
async def test_temperature_sensor_sensor(hass): """Test TemperatureSensor reports sensor temperature correctly.""" for bad_value in (STATE_UNKNOWN, STATE_UNAVAILABLE, "not-number"): hass.states.async_set( "sensor.temp_living_room", bad_value, {ATTR_UNIT_OF_MEASUREMENT: TEMP_CELSIUS}, ) properties = await reported_properties(hass, "sensor.temp_living_room") properties.assert_not_has_property("Alexa.TemperatureSensor", "temperature") hass.states.async_set( "sensor.temp_living_room", "34", {ATTR_UNIT_OF_MEASUREMENT: TEMP_CELSIUS} ) properties = await reported_properties(hass, "sensor.temp_living_room") properties.assert_equal( "Alexa.TemperatureSensor", "temperature", {"value": 34.0, "scale": "CELSIUS"} )
[ "async", "def", "test_temperature_sensor_sensor", "(", "hass", ")", ":", "for", "bad_value", "in", "(", "STATE_UNKNOWN", ",", "STATE_UNAVAILABLE", ",", "\"not-number\"", ")", ":", "hass", ".", "states", ".", "async_set", "(", "\"sensor.temp_living_room\"", ",", "bad_value", ",", "{", "ATTR_UNIT_OF_MEASUREMENT", ":", "TEMP_CELSIUS", "}", ",", ")", "properties", "=", "await", "reported_properties", "(", "hass", ",", "\"sensor.temp_living_room\"", ")", "properties", ".", "assert_not_has_property", "(", "\"Alexa.TemperatureSensor\"", ",", "\"temperature\"", ")", "hass", ".", "states", ".", "async_set", "(", "\"sensor.temp_living_room\"", ",", "\"34\"", ",", "{", "ATTR_UNIT_OF_MEASUREMENT", ":", "TEMP_CELSIUS", "}", ")", "properties", "=", "await", "reported_properties", "(", "hass", ",", "\"sensor.temp_living_room\"", ")", "properties", ".", "assert_equal", "(", "\"Alexa.TemperatureSensor\"", ",", "\"temperature\"", ",", "{", "\"value\"", ":", "34.0", ",", "\"scale\"", ":", "\"CELSIUS\"", "}", ")" ]
[ 596, 0 ]
[ 614, 5 ]
python
en
['en', 'ca', 'en']
True
test_temperature_sensor_climate
(hass)
Test TemperatureSensor reports climate temperature correctly.
Test TemperatureSensor reports climate temperature correctly.
async def test_temperature_sensor_climate(hass): """Test TemperatureSensor reports climate temperature correctly.""" for bad_value in (STATE_UNKNOWN, STATE_UNAVAILABLE, "not-number"): hass.states.async_set( "climate.downstairs", climate.HVAC_MODE_HEAT, {climate.ATTR_CURRENT_TEMPERATURE: bad_value}, ) properties = await reported_properties(hass, "climate.downstairs") properties.assert_not_has_property("Alexa.TemperatureSensor", "temperature") hass.states.async_set( "climate.downstairs", climate.HVAC_MODE_HEAT, {climate.ATTR_CURRENT_TEMPERATURE: 34}, ) properties = await reported_properties(hass, "climate.downstairs") properties.assert_equal( "Alexa.TemperatureSensor", "temperature", {"value": 34.0, "scale": "CELSIUS"} )
[ "async", "def", "test_temperature_sensor_climate", "(", "hass", ")", ":", "for", "bad_value", "in", "(", "STATE_UNKNOWN", ",", "STATE_UNAVAILABLE", ",", "\"not-number\"", ")", ":", "hass", ".", "states", ".", "async_set", "(", "\"climate.downstairs\"", ",", "climate", ".", "HVAC_MODE_HEAT", ",", "{", "climate", ".", "ATTR_CURRENT_TEMPERATURE", ":", "bad_value", "}", ",", ")", "properties", "=", "await", "reported_properties", "(", "hass", ",", "\"climate.downstairs\"", ")", "properties", ".", "assert_not_has_property", "(", "\"Alexa.TemperatureSensor\"", ",", "\"temperature\"", ")", "hass", ".", "states", ".", "async_set", "(", "\"climate.downstairs\"", ",", "climate", ".", "HVAC_MODE_HEAT", ",", "{", "climate", ".", "ATTR_CURRENT_TEMPERATURE", ":", "34", "}", ",", ")", "properties", "=", "await", "reported_properties", "(", "hass", ",", "\"climate.downstairs\"", ")", "properties", ".", "assert_equal", "(", "\"Alexa.TemperatureSensor\"", ",", "\"temperature\"", ",", "{", "\"value\"", ":", "34.0", ",", "\"scale\"", ":", "\"CELSIUS\"", "}", ")" ]
[ 617, 0 ]
[ 637, 5 ]
python
en
['en', 'en', 'en']
True
test_report_alarm_control_panel_state
(hass)
Test SecurityPanelController implements armState property.
Test SecurityPanelController implements armState property.
async def test_report_alarm_control_panel_state(hass): """Test SecurityPanelController implements armState property.""" hass.states.async_set("alarm_control_panel.armed_away", STATE_ALARM_ARMED_AWAY, {}) hass.states.async_set( "alarm_control_panel.armed_custom_bypass", STATE_ALARM_ARMED_CUSTOM_BYPASS, {} ) hass.states.async_set("alarm_control_panel.armed_home", STATE_ALARM_ARMED_HOME, {}) hass.states.async_set( "alarm_control_panel.armed_night", STATE_ALARM_ARMED_NIGHT, {} ) hass.states.async_set("alarm_control_panel.disarmed", STATE_ALARM_DISARMED, {}) properties = await reported_properties(hass, "alarm_control_panel.armed_away") properties.assert_equal("Alexa.SecurityPanelController", "armState", "ARMED_AWAY") properties = await reported_properties( hass, "alarm_control_panel.armed_custom_bypass" ) properties.assert_equal("Alexa.SecurityPanelController", "armState", "ARMED_STAY") properties = await reported_properties(hass, "alarm_control_panel.armed_home") properties.assert_equal("Alexa.SecurityPanelController", "armState", "ARMED_STAY") properties = await reported_properties(hass, "alarm_control_panel.armed_night") properties.assert_equal("Alexa.SecurityPanelController", "armState", "ARMED_NIGHT") properties = await reported_properties(hass, "alarm_control_panel.disarmed") properties.assert_equal("Alexa.SecurityPanelController", "armState", "DISARMED")
[ "async", "def", "test_report_alarm_control_panel_state", "(", "hass", ")", ":", "hass", ".", "states", ".", "async_set", "(", "\"alarm_control_panel.armed_away\"", ",", "STATE_ALARM_ARMED_AWAY", ",", "{", "}", ")", "hass", ".", "states", ".", "async_set", "(", "\"alarm_control_panel.armed_custom_bypass\"", ",", "STATE_ALARM_ARMED_CUSTOM_BYPASS", ",", "{", "}", ")", "hass", ".", "states", ".", "async_set", "(", "\"alarm_control_panel.armed_home\"", ",", "STATE_ALARM_ARMED_HOME", ",", "{", "}", ")", "hass", ".", "states", ".", "async_set", "(", "\"alarm_control_panel.armed_night\"", ",", "STATE_ALARM_ARMED_NIGHT", ",", "{", "}", ")", "hass", ".", "states", ".", "async_set", "(", "\"alarm_control_panel.disarmed\"", ",", "STATE_ALARM_DISARMED", ",", "{", "}", ")", "properties", "=", "await", "reported_properties", "(", "hass", ",", "\"alarm_control_panel.armed_away\"", ")", "properties", ".", "assert_equal", "(", "\"Alexa.SecurityPanelController\"", ",", "\"armState\"", ",", "\"ARMED_AWAY\"", ")", "properties", "=", "await", "reported_properties", "(", "hass", ",", "\"alarm_control_panel.armed_custom_bypass\"", ")", "properties", ".", "assert_equal", "(", "\"Alexa.SecurityPanelController\"", ",", "\"armState\"", ",", "\"ARMED_STAY\"", ")", "properties", "=", "await", "reported_properties", "(", "hass", ",", "\"alarm_control_panel.armed_home\"", ")", "properties", ".", "assert_equal", "(", "\"Alexa.SecurityPanelController\"", ",", "\"armState\"", ",", "\"ARMED_STAY\"", ")", "properties", "=", "await", "reported_properties", "(", "hass", ",", "\"alarm_control_panel.armed_night\"", ")", "properties", ".", "assert_equal", "(", "\"Alexa.SecurityPanelController\"", ",", "\"armState\"", ",", "\"ARMED_NIGHT\"", ")", "properties", "=", "await", "reported_properties", "(", "hass", ",", "\"alarm_control_panel.disarmed\"", ")", "properties", ".", "assert_equal", "(", "\"Alexa.SecurityPanelController\"", ",", "\"armState\"", ",", "\"DISARMED\"", ")" ]
[ 640, 0 ]
[ 667, 84 ]
python
en
['en', 'en', 'en']
True
test_report_playback_state
(hass)
Test PlaybackStateReporter implements playbackState property.
Test PlaybackStateReporter implements playbackState property.
async def test_report_playback_state(hass): """Test PlaybackStateReporter implements playbackState property.""" hass.states.async_set( "media_player.test", "off", { "friendly_name": "Test media player", "supported_features": SUPPORT_PAUSE | SUPPORT_PLAY | SUPPORT_STOP, "volume_level": 0.75, }, ) properties = await reported_properties(hass, "media_player.test") properties.assert_equal( "Alexa.PlaybackStateReporter", "playbackState", {"state": "STOPPED"} )
[ "async", "def", "test_report_playback_state", "(", "hass", ")", ":", "hass", ".", "states", ".", "async_set", "(", "\"media_player.test\"", ",", "\"off\"", ",", "{", "\"friendly_name\"", ":", "\"Test media player\"", ",", "\"supported_features\"", ":", "SUPPORT_PAUSE", "|", "SUPPORT_PLAY", "|", "SUPPORT_STOP", ",", "\"volume_level\"", ":", "0.75", ",", "}", ",", ")", "properties", "=", "await", "reported_properties", "(", "hass", ",", "\"media_player.test\"", ")", "properties", ".", "assert_equal", "(", "\"Alexa.PlaybackStateReporter\"", ",", "\"playbackState\"", ",", "{", "\"state\"", ":", "\"STOPPED\"", "}", ")" ]
[ 670, 0 ]
[ 686, 5 ]
python
en
['en', 'en', 'en']
True
test_report_speaker_volume
(hass)
Test Speaker reports volume correctly.
Test Speaker reports volume correctly.
async def test_report_speaker_volume(hass): """Test Speaker reports volume correctly.""" hass.states.async_set( "media_player.test_speaker", "on", { "friendly_name": "Test media player speaker", "supported_features": SUPPORT_VOLUME_MUTE | SUPPORT_VOLUME_SET, "volume_level": None, "device_class": "speaker", }, ) properties = await reported_properties(hass, "media_player.test_speaker") properties.assert_not_has_property("Alexa.Speaker", "volume") for good_value in range(101): hass.states.async_set( "media_player.test_speaker", "on", { "friendly_name": "Test media player speaker", "supported_features": SUPPORT_VOLUME_MUTE | SUPPORT_VOLUME_SET, "volume_level": good_value / 100, "device_class": "speaker", }, ) properties = await reported_properties(hass, "media_player.test_speaker") properties.assert_equal("Alexa.Speaker", "volume", good_value)
[ "async", "def", "test_report_speaker_volume", "(", "hass", ")", ":", "hass", ".", "states", ".", "async_set", "(", "\"media_player.test_speaker\"", ",", "\"on\"", ",", "{", "\"friendly_name\"", ":", "\"Test media player speaker\"", ",", "\"supported_features\"", ":", "SUPPORT_VOLUME_MUTE", "|", "SUPPORT_VOLUME_SET", ",", "\"volume_level\"", ":", "None", ",", "\"device_class\"", ":", "\"speaker\"", ",", "}", ",", ")", "properties", "=", "await", "reported_properties", "(", "hass", ",", "\"media_player.test_speaker\"", ")", "properties", ".", "assert_not_has_property", "(", "\"Alexa.Speaker\"", ",", "\"volume\"", ")", "for", "good_value", "in", "range", "(", "101", ")", ":", "hass", ".", "states", ".", "async_set", "(", "\"media_player.test_speaker\"", ",", "\"on\"", ",", "{", "\"friendly_name\"", ":", "\"Test media player speaker\"", ",", "\"supported_features\"", ":", "SUPPORT_VOLUME_MUTE", "|", "SUPPORT_VOLUME_SET", ",", "\"volume_level\"", ":", "good_value", "/", "100", ",", "\"device_class\"", ":", "\"speaker\"", ",", "}", ",", ")", "properties", "=", "await", "reported_properties", "(", "hass", ",", "\"media_player.test_speaker\"", ")", "properties", ".", "assert_equal", "(", "\"Alexa.Speaker\"", ",", "\"volume\"", ",", "good_value", ")" ]
[ 689, 0 ]
[ 716, 70 ]
python
en
['en', 'en', 'en']
True
test_report_image_processing
(hass)
Test EventDetectionSensor implements humanPresenceDetectionState property.
Test EventDetectionSensor implements humanPresenceDetectionState property.
async def test_report_image_processing(hass): """Test EventDetectionSensor implements humanPresenceDetectionState property.""" hass.states.async_set( "image_processing.test_face", 0, { "friendly_name": "Test face", "device_class": "face", "faces": [], "total_faces": 0, }, ) properties = await reported_properties(hass, "image_processing#test_face") properties.assert_equal( "Alexa.EventDetectionSensor", "humanPresenceDetectionState", {"value": "NOT_DETECTED"}, ) hass.states.async_set( "image_processing.test_classifier", 3, { "friendly_name": "Test classifier", "device_class": "face", "faces": [ {"confidence": 98.34, "name": "Hans", "age": 16.0, "gender": "male"}, {"name": "Helena", "age": 28.0, "gender": "female"}, {"confidence": 62.53, "name": "Luna"}, ], "total_faces": 3, }, ) properties = await reported_properties(hass, "image_processing#test_classifier") properties.assert_equal( "Alexa.EventDetectionSensor", "humanPresenceDetectionState", {"value": "DETECTED"}, )
[ "async", "def", "test_report_image_processing", "(", "hass", ")", ":", "hass", ".", "states", ".", "async_set", "(", "\"image_processing.test_face\"", ",", "0", ",", "{", "\"friendly_name\"", ":", "\"Test face\"", ",", "\"device_class\"", ":", "\"face\"", ",", "\"faces\"", ":", "[", "]", ",", "\"total_faces\"", ":", "0", ",", "}", ",", ")", "properties", "=", "await", "reported_properties", "(", "hass", ",", "\"image_processing#test_face\"", ")", "properties", ".", "assert_equal", "(", "\"Alexa.EventDetectionSensor\"", ",", "\"humanPresenceDetectionState\"", ",", "{", "\"value\"", ":", "\"NOT_DETECTED\"", "}", ",", ")", "hass", ".", "states", ".", "async_set", "(", "\"image_processing.test_classifier\"", ",", "3", ",", "{", "\"friendly_name\"", ":", "\"Test classifier\"", ",", "\"device_class\"", ":", "\"face\"", ",", "\"faces\"", ":", "[", "{", "\"confidence\"", ":", "98.34", ",", "\"name\"", ":", "\"Hans\"", ",", "\"age\"", ":", "16.0", ",", "\"gender\"", ":", "\"male\"", "}", ",", "{", "\"name\"", ":", "\"Helena\"", ",", "\"age\"", ":", "28.0", ",", "\"gender\"", ":", "\"female\"", "}", ",", "{", "\"confidence\"", ":", "62.53", ",", "\"name\"", ":", "\"Luna\"", "}", ",", "]", ",", "\"total_faces\"", ":", "3", ",", "}", ",", ")", "properties", "=", "await", "reported_properties", "(", "hass", ",", "\"image_processing#test_classifier\"", ")", "properties", ".", "assert_equal", "(", "\"Alexa.EventDetectionSensor\"", ",", "\"humanPresenceDetectionState\"", ",", "{", "\"value\"", ":", "\"DETECTED\"", "}", ",", ")" ]
[ 719, 0 ]
[ 758, 5 ]
python
en
['en', 'en', 'en']
True
test_get_property_blowup
(hass, caplog)
Test we handle a property blowing up.
Test we handle a property blowing up.
async def test_get_property_blowup(hass, caplog): """Test we handle a property blowing up.""" hass.states.async_set( "climate.downstairs", climate.HVAC_MODE_AUTO, { "friendly_name": "Climate Downstairs", "supported_features": 91, climate.ATTR_CURRENT_TEMPERATURE: 34, ATTR_UNIT_OF_MEASUREMENT: TEMP_CELSIUS, }, ) with patch( "homeassistant.components.alexa.capabilities.float", side_effect=Exception("Boom Fail"), ): properties = await reported_properties(hass, "climate.downstairs") properties.assert_not_has_property("Alexa.ThermostatController", "temperature") assert "Boom Fail" in caplog.text
[ "async", "def", "test_get_property_blowup", "(", "hass", ",", "caplog", ")", ":", "hass", ".", "states", ".", "async_set", "(", "\"climate.downstairs\"", ",", "climate", ".", "HVAC_MODE_AUTO", ",", "{", "\"friendly_name\"", ":", "\"Climate Downstairs\"", ",", "\"supported_features\"", ":", "91", ",", "climate", ".", "ATTR_CURRENT_TEMPERATURE", ":", "34", ",", "ATTR_UNIT_OF_MEASUREMENT", ":", "TEMP_CELSIUS", ",", "}", ",", ")", "with", "patch", "(", "\"homeassistant.components.alexa.capabilities.float\"", ",", "side_effect", "=", "Exception", "(", "\"Boom Fail\"", ")", ",", ")", ":", "properties", "=", "await", "reported_properties", "(", "hass", ",", "\"climate.downstairs\"", ")", "properties", ".", "assert_not_has_property", "(", "\"Alexa.ThermostatController\"", ",", "\"temperature\"", ")", "assert", "\"Boom Fail\"", "in", "caplog", ".", "text" ]
[ 761, 0 ]
[ 780, 37 ]
python
en
['en', 'en', 'en']
True
async_setup
(hass, config)
Set up the Slide platform.
Set up the Slide platform.
async def async_setup(hass, config): """Set up the Slide platform.""" async def update_slides(now=None): """Update slide information.""" result = await hass.data[DOMAIN][API].slides_overview() if result is None: _LOGGER.error("Slide API does not work or returned an error") return if result: _LOGGER.debug("Slide API returned %d slide(s)", len(result)) else: _LOGGER.warning("Slide API returned 0 slides") for slide in result: if "device_id" not in slide: _LOGGER.error( "Found invalid Slide entry, device_id is missing. Entry=%s", slide ) continue uid = slide["device_id"].replace("slide_", "") slidenew = hass.data[DOMAIN][SLIDES].setdefault(uid, {}) slidenew["mac"] = uid slidenew["id"] = slide["id"] slidenew["name"] = slide["device_name"] slidenew["state"] = None oldpos = slidenew.get("pos") slidenew["pos"] = None slidenew["online"] = False slidenew["invert"] = config[DOMAIN][CONF_INVERT_POSITION] if "device_info" not in slide: _LOGGER.error( "Slide %s (%s) has no device_info Entry=%s", slide["id"], slidenew["mac"], slide, ) continue # Check if we have pos (OK) or code (NOK) if "pos" in slide["device_info"]: slidenew["online"] = True slidenew["pos"] = slide["device_info"]["pos"] slidenew["pos"] = max(0, min(1, slidenew["pos"])) if oldpos is None or oldpos == slidenew["pos"]: slidenew["state"] = ( STATE_CLOSED if slidenew["pos"] > (1 - DEFAULT_OFFSET) else STATE_OPEN ) elif oldpos < slidenew["pos"]: slidenew["state"] = ( STATE_CLOSED if slidenew["pos"] >= (1 - DEFAULT_OFFSET) else STATE_CLOSING ) else: slidenew["state"] = ( STATE_OPEN if slidenew["pos"] <= DEFAULT_OFFSET else STATE_OPENING ) elif "code" in slide["device_info"]: _LOGGER.warning( "Slide %s (%s) is offline with code=%s", slide["id"], slidenew["mac"], slide["device_info"]["code"], ) else: _LOGGER.error( "Slide %s (%s) has invalid device_info %s", slide["id"], slidenew["mac"], slide["device_info"], ) _LOGGER.debug("Updated entry=%s", slidenew) async def retry_setup(now): """Retry setup if a connection/timeout happens on Slide API.""" await async_setup(hass, config) hass.data[DOMAIN] = {} hass.data[DOMAIN][SLIDES] = {} username = config[DOMAIN][CONF_USERNAME] password = config[DOMAIN][CONF_PASSWORD] scaninterval = config[DOMAIN][CONF_SCAN_INTERVAL] hass.data[DOMAIN][API] = GoSlideCloud(username, password) try: result = await hass.data[DOMAIN][API].login() except (goslideapi.ClientConnectionError, goslideapi.ClientTimeoutError) as err: _LOGGER.error( "Error connecting to Slide Cloud: %s, going to retry in %s second(s)", err, DEFAULT_RETRY, ) async_call_later(hass, DEFAULT_RETRY, retry_setup) return True if not result: _LOGGER.error("Slide API returned unknown error during authentication") return False _LOGGER.debug("Slide API successfully authenticated") await update_slides() hass.async_create_task(async_load_platform(hass, COMPONENT, DOMAIN, {}, config)) async_track_time_interval(hass, update_slides, scaninterval) return True
[ "async", "def", "async_setup", "(", "hass", ",", "config", ")", ":", "async", "def", "update_slides", "(", "now", "=", "None", ")", ":", "\"\"\"Update slide information.\"\"\"", "result", "=", "await", "hass", ".", "data", "[", "DOMAIN", "]", "[", "API", "]", ".", "slides_overview", "(", ")", "if", "result", "is", "None", ":", "_LOGGER", ".", "error", "(", "\"Slide API does not work or returned an error\"", ")", "return", "if", "result", ":", "_LOGGER", ".", "debug", "(", "\"Slide API returned %d slide(s)\"", ",", "len", "(", "result", ")", ")", "else", ":", "_LOGGER", ".", "warning", "(", "\"Slide API returned 0 slides\"", ")", "for", "slide", "in", "result", ":", "if", "\"device_id\"", "not", "in", "slide", ":", "_LOGGER", ".", "error", "(", "\"Found invalid Slide entry, device_id is missing. Entry=%s\"", ",", "slide", ")", "continue", "uid", "=", "slide", "[", "\"device_id\"", "]", ".", "replace", "(", "\"slide_\"", ",", "\"\"", ")", "slidenew", "=", "hass", ".", "data", "[", "DOMAIN", "]", "[", "SLIDES", "]", ".", "setdefault", "(", "uid", ",", "{", "}", ")", "slidenew", "[", "\"mac\"", "]", "=", "uid", "slidenew", "[", "\"id\"", "]", "=", "slide", "[", "\"id\"", "]", "slidenew", "[", "\"name\"", "]", "=", "slide", "[", "\"device_name\"", "]", "slidenew", "[", "\"state\"", "]", "=", "None", "oldpos", "=", "slidenew", ".", "get", "(", "\"pos\"", ")", "slidenew", "[", "\"pos\"", "]", "=", "None", "slidenew", "[", "\"online\"", "]", "=", "False", "slidenew", "[", "\"invert\"", "]", "=", "config", "[", "DOMAIN", "]", "[", "CONF_INVERT_POSITION", "]", "if", "\"device_info\"", "not", "in", "slide", ":", "_LOGGER", ".", "error", "(", "\"Slide %s (%s) has no device_info Entry=%s\"", ",", "slide", "[", "\"id\"", "]", ",", "slidenew", "[", "\"mac\"", "]", ",", "slide", ",", ")", "continue", "# Check if we have pos (OK) or code (NOK)", "if", "\"pos\"", "in", "slide", "[", "\"device_info\"", "]", ":", "slidenew", "[", "\"online\"", "]", "=", "True", "slidenew", "[", "\"pos\"", "]", "=", "slide", "[", "\"device_info\"", "]", "[", "\"pos\"", "]", "slidenew", "[", "\"pos\"", "]", "=", "max", "(", "0", ",", "min", "(", "1", ",", "slidenew", "[", "\"pos\"", "]", ")", ")", "if", "oldpos", "is", "None", "or", "oldpos", "==", "slidenew", "[", "\"pos\"", "]", ":", "slidenew", "[", "\"state\"", "]", "=", "(", "STATE_CLOSED", "if", "slidenew", "[", "\"pos\"", "]", ">", "(", "1", "-", "DEFAULT_OFFSET", ")", "else", "STATE_OPEN", ")", "elif", "oldpos", "<", "slidenew", "[", "\"pos\"", "]", ":", "slidenew", "[", "\"state\"", "]", "=", "(", "STATE_CLOSED", "if", "slidenew", "[", "\"pos\"", "]", ">=", "(", "1", "-", "DEFAULT_OFFSET", ")", "else", "STATE_CLOSING", ")", "else", ":", "slidenew", "[", "\"state\"", "]", "=", "(", "STATE_OPEN", "if", "slidenew", "[", "\"pos\"", "]", "<=", "DEFAULT_OFFSET", "else", "STATE_OPENING", ")", "elif", "\"code\"", "in", "slide", "[", "\"device_info\"", "]", ":", "_LOGGER", ".", "warning", "(", "\"Slide %s (%s) is offline with code=%s\"", ",", "slide", "[", "\"id\"", "]", ",", "slidenew", "[", "\"mac\"", "]", ",", "slide", "[", "\"device_info\"", "]", "[", "\"code\"", "]", ",", ")", "else", ":", "_LOGGER", ".", "error", "(", "\"Slide %s (%s) has invalid device_info %s\"", ",", "slide", "[", "\"id\"", "]", ",", "slidenew", "[", "\"mac\"", "]", ",", "slide", "[", "\"device_info\"", "]", ",", ")", "_LOGGER", ".", "debug", "(", "\"Updated entry=%s\"", ",", "slidenew", ")", "async", "def", "retry_setup", "(", "now", ")", ":", "\"\"\"Retry setup if a connection/timeout happens on Slide API.\"\"\"", "await", "async_setup", "(", "hass", ",", "config", ")", "hass", ".", "data", "[", "DOMAIN", "]", "=", "{", "}", "hass", ".", "data", "[", "DOMAIN", "]", "[", "SLIDES", "]", "=", "{", "}", "username", "=", "config", "[", "DOMAIN", "]", "[", "CONF_USERNAME", "]", "password", "=", "config", "[", "DOMAIN", "]", "[", "CONF_PASSWORD", "]", "scaninterval", "=", "config", "[", "DOMAIN", "]", "[", "CONF_SCAN_INTERVAL", "]", "hass", ".", "data", "[", "DOMAIN", "]", "[", "API", "]", "=", "GoSlideCloud", "(", "username", ",", "password", ")", "try", ":", "result", "=", "await", "hass", ".", "data", "[", "DOMAIN", "]", "[", "API", "]", ".", "login", "(", ")", "except", "(", "goslideapi", ".", "ClientConnectionError", ",", "goslideapi", ".", "ClientTimeoutError", ")", "as", "err", ":", "_LOGGER", ".", "error", "(", "\"Error connecting to Slide Cloud: %s, going to retry in %s second(s)\"", ",", "err", ",", "DEFAULT_RETRY", ",", ")", "async_call_later", "(", "hass", ",", "DEFAULT_RETRY", ",", "retry_setup", ")", "return", "True", "if", "not", "result", ":", "_LOGGER", ".", "error", "(", "\"Slide API returned unknown error during authentication\"", ")", "return", "False", "_LOGGER", ".", "debug", "(", "\"Slide API successfully authenticated\"", ")", "await", "update_slides", "(", ")", "hass", ".", "async_create_task", "(", "async_load_platform", "(", "hass", ",", "COMPONENT", ",", "DOMAIN", ",", "{", "}", ",", "config", ")", ")", "async_track_time_interval", "(", "hass", ",", "update_slides", ",", "scaninterval", ")", "return", "True" ]
[ 52, 0 ]
[ 172, 15 ]
python
en
['en', 'da', 'en']
True
FunnelTokenizerFast.create_token_type_ids_from_sequences
( self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None )
Create a mask from the two sequences passed to be used in a sequence-pair classification task. A Funnel Transformer sequence pair mask has the following format: :: 2 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 | first sequence | second sequence | If :obj:`token_ids_1` is :obj:`None`, this method only returns the first portion of the mask (0s). Args: token_ids_0 (:obj:`List[int]`): List of IDs. token_ids_1 (:obj:`List[int]`, `optional`): Optional second list of IDs for sequence pairs. Returns: :obj:`List[int]`: List of `token type IDs <../glossary.html#token-type-ids>`_ according to the given sequence(s).
Create a mask from the two sequences passed to be used in a sequence-pair classification task. A Funnel Transformer sequence pair mask has the following format:
def create_token_type_ids_from_sequences( self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None ) -> List[int]: """ Create a mask from the two sequences passed to be used in a sequence-pair classification task. A Funnel Transformer sequence pair mask has the following format: :: 2 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 | first sequence | second sequence | If :obj:`token_ids_1` is :obj:`None`, this method only returns the first portion of the mask (0s). Args: token_ids_0 (:obj:`List[int]`): List of IDs. token_ids_1 (:obj:`List[int]`, `optional`): Optional second list of IDs for sequence pairs. Returns: :obj:`List[int]`: List of `token type IDs <../glossary.html#token-type-ids>`_ according to the given sequence(s). """ sep = [self.sep_token_id] cls = [self.cls_token_id] if token_ids_1 is None: return len(cls) * [self.cls_token_type_id] + len(token_ids_0 + sep) * [0] return len(cls) * [self.cls_token_type_id] + len(token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1]
[ "def", "create_token_type_ids_from_sequences", "(", "self", ",", "token_ids_0", ":", "List", "[", "int", "]", ",", "token_ids_1", ":", "Optional", "[", "List", "[", "int", "]", "]", "=", "None", ")", "->", "List", "[", "int", "]", ":", "sep", "=", "[", "self", ".", "sep_token_id", "]", "cls", "=", "[", "self", ".", "cls_token_id", "]", "if", "token_ids_1", "is", "None", ":", "return", "len", "(", "cls", ")", "*", "[", "self", ".", "cls_token_type_id", "]", "+", "len", "(", "token_ids_0", "+", "sep", ")", "*", "[", "0", "]", "return", "len", "(", "cls", ")", "*", "[", "self", ".", "cls_token_type_id", "]", "+", "len", "(", "token_ids_0", "+", "sep", ")", "*", "[", "0", "]", "+", "len", "(", "token_ids_1", "+", "sep", ")", "*", "[", "1", "]" ]
[ 124, 4 ]
[ 152, 112 ]
python
en
['en', 'error', 'th']
False
test_form
(hass: HomeAssistantType)
Test we get the form.
Test we get the form.
async def test_form(hass: HomeAssistantType): """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"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {} with patch(PATCH_CONFIGURATION) as mock_config_class, patch( PATCH_CONNECTION ) as mock_connection_class, patch( PATCH_ASYNC_SETUP, return_value=True ) as mock_setup, patch( PATCH_ASYNC_SETUP_ENTRY, return_value=True, ) as mock_setup_entry: isy_conn = mock_connection_class.return_value isy_conn.get_config.return_value = None mock_config_class.return_value = MOCK_VALIDATED_RESPONSE result2 = await hass.config_entries.flow.async_configure( result["flow_id"], MOCK_USER_INPUT, ) await hass.async_block_till_done() assert result2["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result2["title"] == f"{MOCK_DEVICE_NAME} ({MOCK_HOSTNAME})" assert result2["result"].unique_id == MOCK_UUID assert result2["data"] == MOCK_USER_INPUT assert len(mock_setup.mock_calls) == 1 assert len(mock_setup_entry.mock_calls) == 1
[ "async", "def", "test_form", "(", "hass", ":", "HomeAssistantType", ")", ":", "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\"", "]", "==", "data_entry_flow", ".", "RESULT_TYPE_FORM", "assert", "result", "[", "\"errors\"", "]", "==", "{", "}", "with", "patch", "(", "PATCH_CONFIGURATION", ")", "as", "mock_config_class", ",", "patch", "(", "PATCH_CONNECTION", ")", "as", "mock_connection_class", ",", "patch", "(", "PATCH_ASYNC_SETUP", ",", "return_value", "=", "True", ")", "as", "mock_setup", ",", "patch", "(", "PATCH_ASYNC_SETUP_ENTRY", ",", "return_value", "=", "True", ",", ")", "as", "mock_setup_entry", ":", "isy_conn", "=", "mock_connection_class", ".", "return_value", "isy_conn", ".", "get_config", ".", "return_value", "=", "None", "mock_config_class", ".", "return_value", "=", "MOCK_VALIDATED_RESPONSE", "result2", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_configure", "(", "result", "[", "\"flow_id\"", "]", ",", "MOCK_USER_INPUT", ",", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "result2", "[", "\"type\"", "]", "==", "data_entry_flow", ".", "RESULT_TYPE_CREATE_ENTRY", "assert", "result2", "[", "\"title\"", "]", "==", "f\"{MOCK_DEVICE_NAME} ({MOCK_HOSTNAME})\"", "assert", "result2", "[", "\"result\"", "]", ".", "unique_id", "==", "MOCK_UUID", "assert", "result2", "[", "\"data\"", "]", "==", "MOCK_USER_INPUT", "assert", "len", "(", "mock_setup", ".", "mock_calls", ")", "==", "1", "assert", "len", "(", "mock_setup_entry", ".", "mock_calls", ")", "==", "1" ]
[ 71, 0 ]
[ 101, 48 ]
python
en
['en', 'en', 'en']
True
test_form_invalid_host
(hass: HomeAssistantType)
Test we handle invalid host.
Test we handle invalid host.
async def test_form_invalid_host(hass: HomeAssistantType): """Test we handle invalid host.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) result2 = await hass.config_entries.flow.async_configure( result["flow_id"], { "host": MOCK_HOSTNAME, # Test with missing protocol (http://) "username": MOCK_USERNAME, "password": MOCK_PASSWORD, "tls": MOCK_TLS_VERSION, }, ) assert result2["type"] == data_entry_flow.RESULT_TYPE_FORM assert result2["errors"] == {"base": "invalid_host"}
[ "async", "def", "test_form_invalid_host", "(", "hass", ":", "HomeAssistantType", ")", ":", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "context", "=", "{", "\"source\"", ":", "config_entries", ".", "SOURCE_USER", "}", ")", "result2", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_configure", "(", "result", "[", "\"flow_id\"", "]", ",", "{", "\"host\"", ":", "MOCK_HOSTNAME", ",", "# Test with missing protocol (http://)", "\"username\"", ":", "MOCK_USERNAME", ",", "\"password\"", ":", "MOCK_PASSWORD", ",", "\"tls\"", ":", "MOCK_TLS_VERSION", ",", "}", ",", ")", "assert", "result2", "[", "\"type\"", "]", "==", "data_entry_flow", ".", "RESULT_TYPE_FORM", "assert", "result2", "[", "\"errors\"", "]", "==", "{", "\"base\"", ":", "\"invalid_host\"", "}" ]
[ 104, 0 ]
[ 121, 56 ]
python
en
['en', 'et', 'en']
True
test_form_invalid_auth
(hass: HomeAssistantType)
Test we handle invalid auth.
Test we handle invalid auth.
async def test_form_invalid_auth(hass: HomeAssistantType): """Test we handle invalid auth.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) with patch(PATCH_CONFIGURATION), patch( PATCH_CONNECTION, side_effect=ValueError("PyISY could not connect to the ISY."), ): result2 = await hass.config_entries.flow.async_configure( result["flow_id"], MOCK_USER_INPUT, ) assert result2["type"] == data_entry_flow.RESULT_TYPE_FORM assert result2["errors"] == {"base": "invalid_auth"}
[ "async", "def", "test_form_invalid_auth", "(", "hass", ":", "HomeAssistantType", ")", ":", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "context", "=", "{", "\"source\"", ":", "config_entries", ".", "SOURCE_USER", "}", ")", "with", "patch", "(", "PATCH_CONFIGURATION", ")", ",", "patch", "(", "PATCH_CONNECTION", ",", "side_effect", "=", "ValueError", "(", "\"PyISY could not connect to the ISY.\"", ")", ",", ")", ":", "result2", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_configure", "(", "result", "[", "\"flow_id\"", "]", ",", "MOCK_USER_INPUT", ",", ")", "assert", "result2", "[", "\"type\"", "]", "==", "data_entry_flow", ".", "RESULT_TYPE_FORM", "assert", "result2", "[", "\"errors\"", "]", "==", "{", "\"base\"", ":", "\"invalid_auth\"", "}" ]
[ 124, 0 ]
[ 139, 56 ]
python
en
['en', 'en', 'en']
True
test_form_cannot_connect
(hass: HomeAssistantType)
Test we handle cannot connect error.
Test we handle cannot connect error.
async def test_form_cannot_connect(hass: HomeAssistantType): """Test we handle cannot connect error.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) with patch(PATCH_CONFIGURATION), patch( PATCH_CONNECTION, side_effect=CannotConnect, ): result2 = await hass.config_entries.flow.async_configure( result["flow_id"], MOCK_USER_INPUT, ) assert result2["type"] == data_entry_flow.RESULT_TYPE_FORM assert result2["errors"] == {"base": "cannot_connect"}
[ "async", "def", "test_form_cannot_connect", "(", "hass", ":", "HomeAssistantType", ")", ":", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "context", "=", "{", "\"source\"", ":", "config_entries", ".", "SOURCE_USER", "}", ")", "with", "patch", "(", "PATCH_CONFIGURATION", ")", ",", "patch", "(", "PATCH_CONNECTION", ",", "side_effect", "=", "CannotConnect", ",", ")", ":", "result2", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_configure", "(", "result", "[", "\"flow_id\"", "]", ",", "MOCK_USER_INPUT", ",", ")", "assert", "result2", "[", "\"type\"", "]", "==", "data_entry_flow", ".", "RESULT_TYPE_FORM", "assert", "result2", "[", "\"errors\"", "]", "==", "{", "\"base\"", ":", "\"cannot_connect\"", "}" ]
[ 142, 0 ]
[ 157, 58 ]
python
en
['en', 'en', 'en']
True
test_form_existing_config_entry
(hass: HomeAssistantType)
Test if config entry already exists.
Test if config entry already exists.
async def test_form_existing_config_entry(hass: HomeAssistantType): """Test if config entry already exists.""" MockConfigEntry(domain=DOMAIN, unique_id=MOCK_UUID).add_to_hass(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"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {} with patch(PATCH_CONFIGURATION) as mock_config_class, patch( PATCH_CONNECTION ) as mock_connection_class: isy_conn = mock_connection_class.return_value isy_conn.get_config.return_value = None mock_config_class.return_value = MOCK_VALIDATED_RESPONSE result2 = await hass.config_entries.flow.async_configure( result["flow_id"], MOCK_USER_INPUT, ) assert result2["type"] == data_entry_flow.RESULT_TYPE_ABORT
[ "async", "def", "test_form_existing_config_entry", "(", "hass", ":", "HomeAssistantType", ")", ":", "MockConfigEntry", "(", "domain", "=", "DOMAIN", ",", "unique_id", "=", "MOCK_UUID", ")", ".", "add_to_hass", "(", "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\"", "]", "==", "data_entry_flow", ".", "RESULT_TYPE_FORM", "assert", "result", "[", "\"errors\"", "]", "==", "{", "}", "with", "patch", "(", "PATCH_CONFIGURATION", ")", "as", "mock_config_class", ",", "patch", "(", "PATCH_CONNECTION", ")", "as", "mock_connection_class", ":", "isy_conn", "=", "mock_connection_class", ".", "return_value", "isy_conn", ".", "get_config", ".", "return_value", "=", "None", "mock_config_class", ".", "return_value", "=", "MOCK_VALIDATED_RESPONSE", "result2", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_configure", "(", "result", "[", "\"flow_id\"", "]", ",", "MOCK_USER_INPUT", ",", ")", "assert", "result2", "[", "\"type\"", "]", "==", "data_entry_flow", ".", "RESULT_TYPE_ABORT" ]
[ 160, 0 ]
[ 180, 63 ]
python
en
['en', 'en', 'en']
True
test_import_flow_some_fields
(hass: HomeAssistantType)
Test import config flow with just the basic fields.
Test import config flow with just the basic fields.
async def test_import_flow_some_fields(hass: HomeAssistantType) -> None: """Test import config flow with just the basic fields.""" with patch(PATCH_CONFIGURATION) as mock_config_class, patch( PATCH_CONNECTION ) as mock_connection_class, patch(PATCH_ASYNC_SETUP, return_value=True), patch( PATCH_ASYNC_SETUP_ENTRY, return_value=True, ): isy_conn = mock_connection_class.return_value isy_conn.get_config.return_value = None mock_config_class.return_value = MOCK_VALIDATED_RESPONSE result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data=MOCK_IMPORT_BASIC_CONFIG, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["data"][CONF_HOST] == f"http://{MOCK_HOSTNAME}" assert result["data"][CONF_USERNAME] == MOCK_USERNAME assert result["data"][CONF_PASSWORD] == MOCK_PASSWORD
[ "async", "def", "test_import_flow_some_fields", "(", "hass", ":", "HomeAssistantType", ")", "->", "None", ":", "with", "patch", "(", "PATCH_CONFIGURATION", ")", "as", "mock_config_class", ",", "patch", "(", "PATCH_CONNECTION", ")", "as", "mock_connection_class", ",", "patch", "(", "PATCH_ASYNC_SETUP", ",", "return_value", "=", "True", ")", ",", "patch", "(", "PATCH_ASYNC_SETUP_ENTRY", ",", "return_value", "=", "True", ",", ")", ":", "isy_conn", "=", "mock_connection_class", ".", "return_value", "isy_conn", ".", "get_config", ".", "return_value", "=", "None", "mock_config_class", ".", "return_value", "=", "MOCK_VALIDATED_RESPONSE", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "context", "=", "{", "\"source\"", ":", "SOURCE_IMPORT", "}", ",", "data", "=", "MOCK_IMPORT_BASIC_CONFIG", ",", ")", "assert", "result", "[", "\"type\"", "]", "==", "data_entry_flow", ".", "RESULT_TYPE_CREATE_ENTRY", "assert", "result", "[", "\"data\"", "]", "[", "CONF_HOST", "]", "==", "f\"http://{MOCK_HOSTNAME}\"", "assert", "result", "[", "\"data\"", "]", "[", "CONF_USERNAME", "]", "==", "MOCK_USERNAME", "assert", "result", "[", "\"data\"", "]", "[", "CONF_PASSWORD", "]", "==", "MOCK_PASSWORD" ]
[ 183, 0 ]
[ 203, 57 ]
python
en
['en', 'en', 'en']
True
test_import_flow_with_https
(hass: HomeAssistantType)
Test import config with https.
Test import config with https.
async def test_import_flow_with_https(hass: HomeAssistantType) -> None: """Test import config with https.""" with patch(PATCH_CONFIGURATION) as mock_config_class, patch( PATCH_CONNECTION ) as mock_connection_class, patch(PATCH_ASYNC_SETUP, return_value=True), patch( PATCH_ASYNC_SETUP_ENTRY, return_value=True, ): isy_conn = mock_connection_class.return_value isy_conn.get_config.return_value = None mock_config_class.return_value = MOCK_VALIDATED_RESPONSE result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data=MOCK_IMPORT_WITH_SSL, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["data"][CONF_HOST] == f"https://{MOCK_HOSTNAME}" assert result["data"][CONF_USERNAME] == MOCK_USERNAME assert result["data"][CONF_PASSWORD] == MOCK_PASSWORD
[ "async", "def", "test_import_flow_with_https", "(", "hass", ":", "HomeAssistantType", ")", "->", "None", ":", "with", "patch", "(", "PATCH_CONFIGURATION", ")", "as", "mock_config_class", ",", "patch", "(", "PATCH_CONNECTION", ")", "as", "mock_connection_class", ",", "patch", "(", "PATCH_ASYNC_SETUP", ",", "return_value", "=", "True", ")", ",", "patch", "(", "PATCH_ASYNC_SETUP_ENTRY", ",", "return_value", "=", "True", ",", ")", ":", "isy_conn", "=", "mock_connection_class", ".", "return_value", "isy_conn", ".", "get_config", ".", "return_value", "=", "None", "mock_config_class", ".", "return_value", "=", "MOCK_VALIDATED_RESPONSE", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "context", "=", "{", "\"source\"", ":", "SOURCE_IMPORT", "}", ",", "data", "=", "MOCK_IMPORT_WITH_SSL", ",", ")", "assert", "result", "[", "\"type\"", "]", "==", "data_entry_flow", ".", "RESULT_TYPE_CREATE_ENTRY", "assert", "result", "[", "\"data\"", "]", "[", "CONF_HOST", "]", "==", "f\"https://{MOCK_HOSTNAME}\"", "assert", "result", "[", "\"data\"", "]", "[", "CONF_USERNAME", "]", "==", "MOCK_USERNAME", "assert", "result", "[", "\"data\"", "]", "[", "CONF_PASSWORD", "]", "==", "MOCK_PASSWORD" ]
[ 206, 0 ]
[ 227, 57 ]
python
en
['en', 'en', 'en']
True
test_import_flow_all_fields
(hass: HomeAssistantType)
Test import config flow with all fields.
Test import config flow with all fields.
async def test_import_flow_all_fields(hass: HomeAssistantType) -> None: """Test import config flow with all fields.""" with patch(PATCH_CONFIGURATION) as mock_config_class, patch( PATCH_CONNECTION ) as mock_connection_class, patch(PATCH_ASYNC_SETUP, return_value=True), patch( PATCH_ASYNC_SETUP_ENTRY, return_value=True, ): isy_conn = mock_connection_class.return_value isy_conn.get_config.return_value = None mock_config_class.return_value = MOCK_VALIDATED_RESPONSE result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data=MOCK_IMPORT_FULL_CONFIG, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["data"][CONF_HOST] == f"http://{MOCK_HOSTNAME}" assert result["data"][CONF_USERNAME] == MOCK_USERNAME assert result["data"][CONF_PASSWORD] == MOCK_PASSWORD assert result["data"][CONF_IGNORE_STRING] == MOCK_IGNORE_STRING assert result["data"][CONF_RESTORE_LIGHT_STATE] == MOCK_RESTORE_LIGHT_STATE assert result["data"][CONF_SENSOR_STRING] == MOCK_SENSOR_STRING assert result["data"][CONF_VAR_SENSOR_STRING] == MOCK_VARIABLE_SENSOR_STRING assert result["data"][CONF_TLS_VER] == MOCK_TLS_VERSION
[ "async", "def", "test_import_flow_all_fields", "(", "hass", ":", "HomeAssistantType", ")", "->", "None", ":", "with", "patch", "(", "PATCH_CONFIGURATION", ")", "as", "mock_config_class", ",", "patch", "(", "PATCH_CONNECTION", ")", "as", "mock_connection_class", ",", "patch", "(", "PATCH_ASYNC_SETUP", ",", "return_value", "=", "True", ")", ",", "patch", "(", "PATCH_ASYNC_SETUP_ENTRY", ",", "return_value", "=", "True", ",", ")", ":", "isy_conn", "=", "mock_connection_class", ".", "return_value", "isy_conn", ".", "get_config", ".", "return_value", "=", "None", "mock_config_class", ".", "return_value", "=", "MOCK_VALIDATED_RESPONSE", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "context", "=", "{", "\"source\"", ":", "SOURCE_IMPORT", "}", ",", "data", "=", "MOCK_IMPORT_FULL_CONFIG", ",", ")", "assert", "result", "[", "\"type\"", "]", "==", "data_entry_flow", ".", "RESULT_TYPE_CREATE_ENTRY", "assert", "result", "[", "\"data\"", "]", "[", "CONF_HOST", "]", "==", "f\"http://{MOCK_HOSTNAME}\"", "assert", "result", "[", "\"data\"", "]", "[", "CONF_USERNAME", "]", "==", "MOCK_USERNAME", "assert", "result", "[", "\"data\"", "]", "[", "CONF_PASSWORD", "]", "==", "MOCK_PASSWORD", "assert", "result", "[", "\"data\"", "]", "[", "CONF_IGNORE_STRING", "]", "==", "MOCK_IGNORE_STRING", "assert", "result", "[", "\"data\"", "]", "[", "CONF_RESTORE_LIGHT_STATE", "]", "==", "MOCK_RESTORE_LIGHT_STATE", "assert", "result", "[", "\"data\"", "]", "[", "CONF_SENSOR_STRING", "]", "==", "MOCK_SENSOR_STRING", "assert", "result", "[", "\"data\"", "]", "[", "CONF_VAR_SENSOR_STRING", "]", "==", "MOCK_VARIABLE_SENSOR_STRING", "assert", "result", "[", "\"data\"", "]", "[", "CONF_TLS_VER", "]", "==", "MOCK_TLS_VERSION" ]
[ 230, 0 ]
[ 255, 59 ]
python
en
['en', 'en', 'en']
True
test_form_ssdp_already_configured
(hass: HomeAssistantType)
Test ssdp abort when the serial number is already configured.
Test ssdp abort when the serial number is already configured.
async def test_form_ssdp_already_configured(hass: HomeAssistantType) -> None: """Test ssdp abort when the serial number is already configured.""" await setup.async_setup_component(hass, "persistent_notification", {}) MockConfigEntry( domain=DOMAIN, data={CONF_HOST: f"http://{MOCK_HOSTNAME}{ISY_URL_POSTFIX}"}, unique_id=MOCK_UUID, ).add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_SSDP}, data={ ssdp.ATTR_SSDP_LOCATION: f"http://{MOCK_HOSTNAME}{ISY_URL_POSTFIX}", ssdp.ATTR_UPNP_FRIENDLY_NAME: "myisy", ssdp.ATTR_UPNP_UDN: f"{UDN_UUID_PREFIX}{MOCK_UUID}", }, ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT
[ "async", "def", "test_form_ssdp_already_configured", "(", "hass", ":", "HomeAssistantType", ")", "->", "None", ":", "await", "setup", ".", "async_setup_component", "(", "hass", ",", "\"persistent_notification\"", ",", "{", "}", ")", "MockConfigEntry", "(", "domain", "=", "DOMAIN", ",", "data", "=", "{", "CONF_HOST", ":", "f\"http://{MOCK_HOSTNAME}{ISY_URL_POSTFIX}\"", "}", ",", "unique_id", "=", "MOCK_UUID", ",", ")", ".", "add_to_hass", "(", "hass", ")", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "context", "=", "{", "\"source\"", ":", "SOURCE_SSDP", "}", ",", "data", "=", "{", "ssdp", ".", "ATTR_SSDP_LOCATION", ":", "f\"http://{MOCK_HOSTNAME}{ISY_URL_POSTFIX}\"", ",", "ssdp", ".", "ATTR_UPNP_FRIENDLY_NAME", ":", "\"myisy\"", ",", "ssdp", ".", "ATTR_UPNP_UDN", ":", "f\"{UDN_UUID_PREFIX}{MOCK_UUID}\"", ",", "}", ",", ")", "assert", "result", "[", "\"type\"", "]", "==", "data_entry_flow", ".", "RESULT_TYPE_ABORT" ]
[ 258, 0 ]
[ 277, 62 ]
python
en
['en', 'en', 'en']
True
test_form_ssdp
(hass: HomeAssistantType)
Test we can setup from ssdp.
Test we can setup from ssdp.
async def test_form_ssdp(hass: HomeAssistantType): """Test we can setup from ssdp.""" await setup.async_setup_component(hass, "persistent_notification", {}) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_SSDP}, data={ ssdp.ATTR_SSDP_LOCATION: f"http://{MOCK_HOSTNAME}{ISY_URL_POSTFIX}", ssdp.ATTR_UPNP_FRIENDLY_NAME: "myisy", ssdp.ATTR_UPNP_UDN: f"{UDN_UUID_PREFIX}{MOCK_UUID}", }, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" assert result["errors"] == {} with patch(PATCH_CONFIGURATION) as mock_config_class, patch( PATCH_CONNECTION ) as mock_connection_class, patch( PATCH_ASYNC_SETUP, return_value=True ) as mock_setup, patch( PATCH_ASYNC_SETUP_ENTRY, return_value=True, ) as mock_setup_entry: isy_conn = mock_connection_class.return_value isy_conn.get_config.return_value = None mock_config_class.return_value = MOCK_VALIDATED_RESPONSE result2 = await hass.config_entries.flow.async_configure( result["flow_id"], MOCK_USER_INPUT, ) await hass.async_block_till_done() assert result2["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result2["title"] == f"{MOCK_DEVICE_NAME} ({MOCK_HOSTNAME})" assert result2["result"].unique_id == MOCK_UUID assert result2["data"] == MOCK_USER_INPUT assert len(mock_setup.mock_calls) == 1 assert len(mock_setup_entry.mock_calls) == 1
[ "async", "def", "test_form_ssdp", "(", "hass", ":", "HomeAssistantType", ")", ":", "await", "setup", ".", "async_setup_component", "(", "hass", ",", "\"persistent_notification\"", ",", "{", "}", ")", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "context", "=", "{", "\"source\"", ":", "SOURCE_SSDP", "}", ",", "data", "=", "{", "ssdp", ".", "ATTR_SSDP_LOCATION", ":", "f\"http://{MOCK_HOSTNAME}{ISY_URL_POSTFIX}\"", ",", "ssdp", ".", "ATTR_UPNP_FRIENDLY_NAME", ":", "\"myisy\"", ",", "ssdp", ".", "ATTR_UPNP_UDN", ":", "f\"{UDN_UUID_PREFIX}{MOCK_UUID}\"", ",", "}", ",", ")", "assert", "result", "[", "\"type\"", "]", "==", "data_entry_flow", ".", "RESULT_TYPE_FORM", "assert", "result", "[", "\"step_id\"", "]", "==", "\"user\"", "assert", "result", "[", "\"errors\"", "]", "==", "{", "}", "with", "patch", "(", "PATCH_CONFIGURATION", ")", "as", "mock_config_class", ",", "patch", "(", "PATCH_CONNECTION", ")", "as", "mock_connection_class", ",", "patch", "(", "PATCH_ASYNC_SETUP", ",", "return_value", "=", "True", ")", "as", "mock_setup", ",", "patch", "(", "PATCH_ASYNC_SETUP_ENTRY", ",", "return_value", "=", "True", ",", ")", "as", "mock_setup_entry", ":", "isy_conn", "=", "mock_connection_class", ".", "return_value", "isy_conn", ".", "get_config", ".", "return_value", "=", "None", "mock_config_class", ".", "return_value", "=", "MOCK_VALIDATED_RESPONSE", "result2", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_configure", "(", "result", "[", "\"flow_id\"", "]", ",", "MOCK_USER_INPUT", ",", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "result2", "[", "\"type\"", "]", "==", "data_entry_flow", ".", "RESULT_TYPE_CREATE_ENTRY", "assert", "result2", "[", "\"title\"", "]", "==", "f\"{MOCK_DEVICE_NAME} ({MOCK_HOSTNAME})\"", "assert", "result2", "[", "\"result\"", "]", ".", "unique_id", "==", "MOCK_UUID", "assert", "result2", "[", "\"data\"", "]", "==", "MOCK_USER_INPUT", "assert", "len", "(", "mock_setup", ".", "mock_calls", ")", "==", "1", "assert", "len", "(", "mock_setup_entry", ".", "mock_calls", ")", "==", "1" ]
[ 280, 0 ]
[ 319, 48 ]
python
en
['en', 'en', 'en']
True
devices_with_push
(hass)
Return a dictionary of push enabled targets.
Return a dictionary of push enabled targets.
def devices_with_push(hass): """Return a dictionary of push enabled targets.""" targets = {} for device_name, device in hass.data[DOMAIN][ATTR_DEVICES].items(): if device.get(ATTR_PUSH_ID) is not None: targets[device_name] = device.get(ATTR_PUSH_ID) return targets
[ "def", "devices_with_push", "(", "hass", ")", ":", "targets", "=", "{", "}", "for", "device_name", ",", "device", "in", "hass", ".", "data", "[", "DOMAIN", "]", "[", "ATTR_DEVICES", "]", ".", "items", "(", ")", ":", "if", "device", ".", "get", "(", "ATTR_PUSH_ID", ")", "is", "not", "None", ":", "targets", "[", "device_name", "]", "=", "device", ".", "get", "(", "ATTR_PUSH_ID", ")", "return", "targets" ]
[ 212, 0 ]
[ 218, 18 ]
python
en
['en', 'en', 'en']
True
enabled_push_ids
(hass)
Return a list of push enabled target push IDs.
Return a list of push enabled target push IDs.
def enabled_push_ids(hass): """Return a list of push enabled target push IDs.""" push_ids = [] for device in hass.data[DOMAIN][ATTR_DEVICES].values(): if device.get(ATTR_PUSH_ID) is not None: push_ids.append(device.get(ATTR_PUSH_ID)) return push_ids
[ "def", "enabled_push_ids", "(", "hass", ")", ":", "push_ids", "=", "[", "]", "for", "device", "in", "hass", ".", "data", "[", "DOMAIN", "]", "[", "ATTR_DEVICES", "]", ".", "values", "(", ")", ":", "if", "device", ".", "get", "(", "ATTR_PUSH_ID", ")", "is", "not", "None", ":", "push_ids", ".", "append", "(", "device", ".", "get", "(", "ATTR_PUSH_ID", ")", ")", "return", "push_ids" ]
[ 221, 0 ]
[ 227, 19 ]
python
en
['en', 'en', 'en']
True
devices
(hass)
Return a dictionary of all identified devices.
Return a dictionary of all identified devices.
def devices(hass): """Return a dictionary of all identified devices.""" return hass.data[DOMAIN][ATTR_DEVICES]
[ "def", "devices", "(", "hass", ")", ":", "return", "hass", ".", "data", "[", "DOMAIN", "]", "[", "ATTR_DEVICES", "]" ]
[ 230, 0 ]
[ 232, 42 ]
python
en
['en', 'en', 'en']
True
device_name_for_push_id
(hass, push_id)
Return the device name for the push ID.
Return the device name for the push ID.
def device_name_for_push_id(hass, push_id): """Return the device name for the push ID.""" for device_name, device in hass.data[DOMAIN][ATTR_DEVICES].items(): if device.get(ATTR_PUSH_ID) is push_id: return device_name return None
[ "def", "device_name_for_push_id", "(", "hass", ",", "push_id", ")", ":", "for", "device_name", ",", "device", "in", "hass", ".", "data", "[", "DOMAIN", "]", "[", "ATTR_DEVICES", "]", ".", "items", "(", ")", ":", "if", "device", ".", "get", "(", "ATTR_PUSH_ID", ")", "is", "push_id", ":", "return", "device_name", "return", "None" ]
[ 235, 0 ]
[ 240, 15 ]
python
en
['en', 'en', 'en']
True
async_setup
(hass, config)
Set up the iOS component.
Set up the iOS component.
async def async_setup(hass, config): """Set up the iOS component.""" conf = config.get(DOMAIN) ios_config = await hass.async_add_executor_job( load_json, hass.config.path(CONFIGURATION_FILE) ) if ios_config == {}: ios_config[ATTR_DEVICES] = {} ios_config[CONF_USER] = conf or {} if CONF_PUSH not in ios_config[CONF_USER]: ios_config[CONF_USER][CONF_PUSH] = {} hass.data[DOMAIN] = ios_config # No entry support for notify component yet discovery.load_platform(hass, "notify", DOMAIN, {}, config) if conf is not None: hass.async_create_task( hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_IMPORT} ) ) return True
[ "async", "def", "async_setup", "(", "hass", ",", "config", ")", ":", "conf", "=", "config", ".", "get", "(", "DOMAIN", ")", "ios_config", "=", "await", "hass", ".", "async_add_executor_job", "(", "load_json", ",", "hass", ".", "config", ".", "path", "(", "CONFIGURATION_FILE", ")", ")", "if", "ios_config", "==", "{", "}", ":", "ios_config", "[", "ATTR_DEVICES", "]", "=", "{", "}", "ios_config", "[", "CONF_USER", "]", "=", "conf", "or", "{", "}", "if", "CONF_PUSH", "not", "in", "ios_config", "[", "CONF_USER", "]", ":", "ios_config", "[", "CONF_USER", "]", "[", "CONF_PUSH", "]", "=", "{", "}", "hass", ".", "data", "[", "DOMAIN", "]", "=", "ios_config", "# No entry support for notify component yet", "discovery", ".", "load_platform", "(", "hass", ",", "\"notify\"", ",", "DOMAIN", ",", "{", "}", ",", "config", ")", "if", "conf", "is", "not", "None", ":", "hass", ".", "async_create_task", "(", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "context", "=", "{", "\"source\"", ":", "config_entries", ".", "SOURCE_IMPORT", "}", ")", ")", "return", "True" ]
[ 243, 0 ]
[ 271, 15 ]
python
en
['en', 'en', 'en']
True
async_setup_entry
(hass, entry)
Set up an iOS entry.
Set up an iOS entry.
async def async_setup_entry(hass, entry): """Set up an iOS entry.""" hass.async_create_task( hass.config_entries.async_forward_entry_setup(entry, "sensor") ) hass.http.register_view(iOSIdentifyDeviceView(hass.config.path(CONFIGURATION_FILE))) hass.http.register_view(iOSPushConfigView(hass.data[DOMAIN][CONF_USER][CONF_PUSH])) hass.http.register_view(iOSConfigView(hass.data[DOMAIN][CONF_USER])) return True
[ "async", "def", "async_setup_entry", "(", "hass", ",", "entry", ")", ":", "hass", ".", "async_create_task", "(", "hass", ".", "config_entries", ".", "async_forward_entry_setup", "(", "entry", ",", "\"sensor\"", ")", ")", "hass", ".", "http", ".", "register_view", "(", "iOSIdentifyDeviceView", "(", "hass", ".", "config", ".", "path", "(", "CONFIGURATION_FILE", ")", ")", ")", "hass", ".", "http", ".", "register_view", "(", "iOSPushConfigView", "(", "hass", ".", "data", "[", "DOMAIN", "]", "[", "CONF_USER", "]", "[", "CONF_PUSH", "]", ")", ")", "hass", ".", "http", ".", "register_view", "(", "iOSConfigView", "(", "hass", ".", "data", "[", "DOMAIN", "]", "[", "CONF_USER", "]", ")", ")", "return", "True" ]
[ 274, 0 ]
[ 284, 15 ]
python
en
['en', 'ga', 'en']
True
iOSPushConfigView.__init__
(self, push_config)
Init the view.
Init the view.
def __init__(self, push_config): """Init the view.""" self.push_config = push_config
[ "def", "__init__", "(", "self", ",", "push_config", ")", ":", "self", ".", "push_config", "=", "push_config" ]
[ 294, 4 ]
[ 296, 38 ]
python
en
['en', 'en', 'en']
True
iOSPushConfigView.get
(self, request)
Handle the GET request for the push configuration.
Handle the GET request for the push configuration.
def get(self, request): """Handle the GET request for the push configuration.""" return self.json(self.push_config)
[ "def", "get", "(", "self", ",", "request", ")", ":", "return", "self", ".", "json", "(", "self", ".", "push_config", ")" ]
[ 299, 4 ]
[ 301, 42 ]
python
en
['en', 'en', 'en']
True
iOSConfigView.__init__
(self, config)
Init the view.
Init the view.
def __init__(self, config): """Init the view.""" self.config = config
[ "def", "__init__", "(", "self", ",", "config", ")", ":", "self", ".", "config", "=", "config" ]
[ 310, 4 ]
[ 312, 28 ]
python
en
['en', 'en', 'en']
True
iOSConfigView.get
(self, request)
Handle the GET request for the user-defined configuration.
Handle the GET request for the user-defined configuration.
def get(self, request): """Handle the GET request for the user-defined configuration.""" return self.json(self.config)
[ "def", "get", "(", "self", ",", "request", ")", ":", "return", "self", ".", "json", "(", "self", ".", "config", ")" ]
[ 315, 4 ]
[ 317, 37 ]
python
en
['en', 'en', 'en']
True
iOSIdentifyDeviceView.__init__
(self, config_path)
Initialize the view.
Initialize the view.
def __init__(self, config_path): """Initialize the view.""" self._config_path = config_path
[ "def", "__init__", "(", "self", ",", "config_path", ")", ":", "self", ".", "_config_path", "=", "config_path" ]
[ 326, 4 ]
[ 328, 39 ]
python
en
['en', 'en', 'en']
True
iOSIdentifyDeviceView.post
(self, request)
Handle the POST request for device identification.
Handle the POST request for device identification.
async def post(self, request): """Handle the POST request for device identification.""" try: data = await request.json() except ValueError: return self.json_message("Invalid JSON", HTTP_BAD_REQUEST) hass = request.app["hass"] # Commented for now while iOS app is getting frequent updates # try: # data = IDENTIFY_SCHEMA(req_data) # except vol.Invalid as ex: # return self.json_message( # vol.humanize.humanize_error(request.json, ex), # HTTP_BAD_REQUEST) data[ATTR_LAST_SEEN_AT] = datetime.datetime.now().isoformat() device_id = data[ATTR_DEVICE_ID] hass.data[DOMAIN][ATTR_DEVICES][device_id] = data async_dispatcher_send(hass, f"{DOMAIN}.{device_id}", data) try: save_json(self._config_path, hass.data[DOMAIN]) except HomeAssistantError: return self.json_message("Error saving device.", HTTP_INTERNAL_SERVER_ERROR) return self.json({"status": "registered"})
[ "async", "def", "post", "(", "self", ",", "request", ")", ":", "try", ":", "data", "=", "await", "request", ".", "json", "(", ")", "except", "ValueError", ":", "return", "self", ".", "json_message", "(", "\"Invalid JSON\"", ",", "HTTP_BAD_REQUEST", ")", "hass", "=", "request", ".", "app", "[", "\"hass\"", "]", "# Commented for now while iOS app is getting frequent updates", "# try:", "# data = IDENTIFY_SCHEMA(req_data)", "# except vol.Invalid as ex:", "# return self.json_message(", "# vol.humanize.humanize_error(request.json, ex),", "# HTTP_BAD_REQUEST)", "data", "[", "ATTR_LAST_SEEN_AT", "]", "=", "datetime", ".", "datetime", ".", "now", "(", ")", ".", "isoformat", "(", ")", "device_id", "=", "data", "[", "ATTR_DEVICE_ID", "]", "hass", ".", "data", "[", "DOMAIN", "]", "[", "ATTR_DEVICES", "]", "[", "device_id", "]", "=", "data", "async_dispatcher_send", "(", "hass", ",", "f\"{DOMAIN}.{device_id}\"", ",", "data", ")", "try", ":", "save_json", "(", "self", ".", "_config_path", ",", "hass", ".", "data", "[", "DOMAIN", "]", ")", "except", "HomeAssistantError", ":", "return", "self", ".", "json_message", "(", "\"Error saving device.\"", ",", "HTTP_INTERNAL_SERVER_ERROR", ")", "return", "self", ".", "json", "(", "{", "\"status\"", ":", "\"registered\"", "}", ")" ]
[ 330, 4 ]
[ 360, 50 ]
python
en
['en', 'en', 'en']
True
async_setup_entry
(hass, config_entry, async_add_entities)
Set up the Flo sensors from config entry.
Set up the Flo sensors from config entry.
async def async_setup_entry(hass, config_entry, async_add_entities): """Set up the Flo sensors from config entry.""" devices: List[FloDeviceDataUpdateCoordinator] = hass.data[FLO_DOMAIN][ config_entry.entry_id ]["devices"] entities = [] entities.extend([FloDailyUsageSensor(device) for device in devices]) entities.extend([FloSystemModeSensor(device) for device in devices]) entities.extend([FloCurrentFlowRateSensor(device) for device in devices]) entities.extend([FloTemperatureSensor(device) for device in devices]) entities.extend([FloPressureSensor(device) for device in devices]) async_add_entities(entities)
[ "async", "def", "async_setup_entry", "(", "hass", ",", "config_entry", ",", "async_add_entities", ")", ":", "devices", ":", "List", "[", "FloDeviceDataUpdateCoordinator", "]", "=", "hass", ".", "data", "[", "FLO_DOMAIN", "]", "[", "config_entry", ".", "entry_id", "]", "[", "\"devices\"", "]", "entities", "=", "[", "]", "entities", ".", "extend", "(", "[", "FloDailyUsageSensor", "(", "device", ")", "for", "device", "in", "devices", "]", ")", "entities", ".", "extend", "(", "[", "FloSystemModeSensor", "(", "device", ")", "for", "device", "in", "devices", "]", ")", "entities", ".", "extend", "(", "[", "FloCurrentFlowRateSensor", "(", "device", ")", "for", "device", "in", "devices", "]", ")", "entities", ".", "extend", "(", "[", "FloTemperatureSensor", "(", "device", ")", "for", "device", "in", "devices", "]", ")", "entities", ".", "extend", "(", "[", "FloPressureSensor", "(", "device", ")", "for", "device", "in", "devices", "]", ")", "async_add_entities", "(", "entities", ")" ]
[ 26, 0 ]
[ 37, 32 ]
python
en
['en', 'en', 'en']
True
FloDailyUsageSensor.__init__
(self, device)
Initialize the daily water usage sensor.
Initialize the daily water usage sensor.
def __init__(self, device): """Initialize the daily water usage sensor.""" super().__init__("daily_consumption", NAME_DAILY_USAGE, device) self._state: float = None
[ "def", "__init__", "(", "self", ",", "device", ")", ":", "super", "(", ")", ".", "__init__", "(", "\"daily_consumption\"", ",", "NAME_DAILY_USAGE", ",", "device", ")", "self", ".", "_state", ":", "float", "=", "None" ]
[ 43, 4 ]
[ 46, 33 ]
python
en
['en', 'en', 'en']
True
FloDailyUsageSensor.icon
(self)
Return the daily usage icon.
Return the daily usage icon.
def icon(self) -> str: """Return the daily usage icon.""" return WATER_ICON
[ "def", "icon", "(", "self", ")", "->", "str", ":", "return", "WATER_ICON" ]
[ 49, 4 ]
[ 51, 25 ]
python
en
['en', 'en', 'en']
True
FloDailyUsageSensor.state
(self)
Return the current daily usage.
Return the current daily usage.
def state(self) -> Optional[float]: """Return the current daily usage.""" if self._device.consumption_today is None: return None return round(self._device.consumption_today, 1)
[ "def", "state", "(", "self", ")", "->", "Optional", "[", "float", "]", ":", "if", "self", ".", "_device", ".", "consumption_today", "is", "None", ":", "return", "None", "return", "round", "(", "self", ".", "_device", ".", "consumption_today", ",", "1", ")" ]
[ 54, 4 ]
[ 58, 55 ]
python
en
['en', 'en', 'en']
True
FloDailyUsageSensor.unit_of_measurement
(self)
Return gallons as the unit measurement for water.
Return gallons as the unit measurement for water.
def unit_of_measurement(self) -> str: """Return gallons as the unit measurement for water.""" return VOLUME_GALLONS
[ "def", "unit_of_measurement", "(", "self", ")", "->", "str", ":", "return", "VOLUME_GALLONS" ]
[ 61, 4 ]
[ 63, 29 ]
python
en
['en', 'en', 'en']
True
FloSystemModeSensor.__init__
(self, device)
Initialize the system mode sensor.
Initialize the system mode sensor.
def __init__(self, device): """Initialize the system mode sensor.""" super().__init__("current_system_mode", NAME_CURRENT_SYSTEM_MODE, device) self._state: str = None
[ "def", "__init__", "(", "self", ",", "device", ")", ":", "super", "(", ")", ".", "__init__", "(", "\"current_system_mode\"", ",", "NAME_CURRENT_SYSTEM_MODE", ",", "device", ")", "self", ".", "_state", ":", "str", "=", "None" ]
[ 69, 4 ]
[ 72, 31 ]
python
en
['en', 'pt', 'en']
True
FloSystemModeSensor.state
(self)
Return the current system mode.
Return the current system mode.
def state(self) -> Optional[str]: """Return the current system mode.""" if not self._device.current_system_mode: return None return self._device.current_system_mode
[ "def", "state", "(", "self", ")", "->", "Optional", "[", "str", "]", ":", "if", "not", "self", ".", "_device", ".", "current_system_mode", ":", "return", "None", "return", "self", ".", "_device", ".", "current_system_mode" ]
[ 75, 4 ]
[ 79, 47 ]
python
en
['en', 'en', 'en']
True
FloCurrentFlowRateSensor.__init__
(self, device)
Initialize the flow rate sensor.
Initialize the flow rate sensor.
def __init__(self, device): """Initialize the flow rate sensor.""" super().__init__("current_flow_rate", NAME_FLOW_RATE, device) self._state: float = None
[ "def", "__init__", "(", "self", ",", "device", ")", ":", "super", "(", ")", ".", "__init__", "(", "\"current_flow_rate\"", ",", "NAME_FLOW_RATE", ",", "device", ")", "self", ".", "_state", ":", "float", "=", "None" ]
[ 85, 4 ]
[ 88, 33 ]
python
en
['en', 'en', 'en']
True
FloCurrentFlowRateSensor.icon
(self)
Return the daily usage icon.
Return the daily usage icon.
def icon(self) -> str: """Return the daily usage icon.""" return GAUGE_ICON
[ "def", "icon", "(", "self", ")", "->", "str", ":", "return", "GAUGE_ICON" ]
[ 91, 4 ]
[ 93, 25 ]
python
en
['en', 'en', 'en']
True
FloCurrentFlowRateSensor.state
(self)
Return the current flow rate.
Return the current flow rate.
def state(self) -> Optional[float]: """Return the current flow rate.""" if self._device.current_flow_rate is None: return None return round(self._device.current_flow_rate, 1)
[ "def", "state", "(", "self", ")", "->", "Optional", "[", "float", "]", ":", "if", "self", ".", "_device", ".", "current_flow_rate", "is", "None", ":", "return", "None", "return", "round", "(", "self", ".", "_device", ".", "current_flow_rate", ",", "1", ")" ]
[ 96, 4 ]
[ 100, 55 ]
python
en
['en', 'en', 'en']
True
FloCurrentFlowRateSensor.unit_of_measurement
(self)
Return the unit measurement.
Return the unit measurement.
def unit_of_measurement(self) -> str: """Return the unit measurement.""" return "gpm"
[ "def", "unit_of_measurement", "(", "self", ")", "->", "str", ":", "return", "\"gpm\"" ]
[ 103, 4 ]
[ 105, 20 ]
python
en
['en', 'fr', 'en']
True
FloTemperatureSensor.__init__
(self, device)
Initialize the temperature sensor.
Initialize the temperature sensor.
def __init__(self, device): """Initialize the temperature sensor.""" super().__init__("temperature", NAME_TEMPERATURE, device) self._state: float = None
[ "def", "__init__", "(", "self", ",", "device", ")", ":", "super", "(", ")", ".", "__init__", "(", "\"temperature\"", ",", "NAME_TEMPERATURE", ",", "device", ")", "self", ".", "_state", ":", "float", "=", "None" ]
[ 111, 4 ]
[ 114, 33 ]
python
en
['en', 'la', 'en']
True
FloTemperatureSensor.state
(self)
Return the current temperature.
Return the current temperature.
def state(self) -> Optional[float]: """Return the current temperature.""" if self._device.temperature is None: return None return round(fahrenheit_to_celsius(self._device.temperature), 1)
[ "def", "state", "(", "self", ")", "->", "Optional", "[", "float", "]", ":", "if", "self", ".", "_device", ".", "temperature", "is", "None", ":", "return", "None", "return", "round", "(", "fahrenheit_to_celsius", "(", "self", ".", "_device", ".", "temperature", ")", ",", "1", ")" ]
[ 117, 4 ]
[ 121, 72 ]
python
en
['en', 'la', 'en']
True
FloTemperatureSensor.unit_of_measurement
(self)
Return gallons as the unit measurement for water.
Return gallons as the unit measurement for water.
def unit_of_measurement(self) -> str: """Return gallons as the unit measurement for water.""" return TEMP_CELSIUS
[ "def", "unit_of_measurement", "(", "self", ")", "->", "str", ":", "return", "TEMP_CELSIUS" ]
[ 124, 4 ]
[ 126, 27 ]
python
en
['en', 'en', 'en']
True
FloTemperatureSensor.device_class
(self)
Return the device class for this sensor.
Return the device class for this sensor.
def device_class(self) -> Optional[str]: """Return the device class for this sensor.""" return DEVICE_CLASS_TEMPERATURE
[ "def", "device_class", "(", "self", ")", "->", "Optional", "[", "str", "]", ":", "return", "DEVICE_CLASS_TEMPERATURE" ]
[ 129, 4 ]
[ 131, 39 ]
python
en
['en', 'en', 'en']
True
FloPressureSensor.__init__
(self, device)
Initialize the pressure sensor.
Initialize the pressure sensor.
def __init__(self, device): """Initialize the pressure sensor.""" super().__init__("water_pressure", NAME_WATER_PRESSURE, device) self._state: float = None
[ "def", "__init__", "(", "self", ",", "device", ")", ":", "super", "(", ")", ".", "__init__", "(", "\"water_pressure\"", ",", "NAME_WATER_PRESSURE", ",", "device", ")", "self", ".", "_state", ":", "float", "=", "None" ]
[ 137, 4 ]
[ 140, 33 ]
python
en
['en', 'co', 'en']
True
FloPressureSensor.state
(self)
Return the current water pressure.
Return the current water pressure.
def state(self) -> Optional[float]: """Return the current water pressure.""" if self._device.current_psi is None: return None return round(self._device.current_psi, 1)
[ "def", "state", "(", "self", ")", "->", "Optional", "[", "float", "]", ":", "if", "self", ".", "_device", ".", "current_psi", "is", "None", ":", "return", "None", "return", "round", "(", "self", ".", "_device", ".", "current_psi", ",", "1", ")" ]
[ 143, 4 ]
[ 147, 49 ]
python
en
['en', 'en', 'en']
True
FloPressureSensor.unit_of_measurement
(self)
Return gallons as the unit measurement for water.
Return gallons as the unit measurement for water.
def unit_of_measurement(self) -> str: """Return gallons as the unit measurement for water.""" return PRESSURE_PSI
[ "def", "unit_of_measurement", "(", "self", ")", "->", "str", ":", "return", "PRESSURE_PSI" ]
[ 150, 4 ]
[ 152, 27 ]
python
en
['en', 'en', 'en']
True
FloPressureSensor.device_class
(self)
Return the device class for this sensor.
Return the device class for this sensor.
def device_class(self) -> Optional[str]: """Return the device class for this sensor.""" return DEVICE_CLASS_PRESSURE
[ "def", "device_class", "(", "self", ")", "->", "Optional", "[", "str", "]", ":", "return", "DEVICE_CLASS_PRESSURE" ]
[ 155, 4 ]
[ 157, 36 ]
python
en
['en', 'en', 'en']
True
test_service_show_view
(hass, mock_zeroconf)
Test we don't set app id in prod.
Test we don't set app id in prod.
async def test_service_show_view(hass, mock_zeroconf): """Test we don't set app id in prod.""" await async_process_ha_core_config( hass, {"external_url": "https://example.com"}, ) await home_assistant_cast.async_setup_ha_cast(hass, MockConfigEntry()) calls = async_mock_signal(hass, home_assistant_cast.SIGNAL_HASS_CAST_SHOW_VIEW) await hass.services.async_call( "cast", "show_lovelace_view", {"entity_id": "media_player.kitchen", "view_path": "mock_path"}, blocking=True, ) assert len(calls) == 1 controller, entity_id, view_path, url_path = calls[0] assert controller.hass_url == "https://example.com" assert controller.client_id is None # Verify user did not accidentally submit their dev app id assert controller.supporting_app_id == "B12CE3CA" assert entity_id == "media_player.kitchen" assert view_path == "mock_path" assert url_path is None
[ "async", "def", "test_service_show_view", "(", "hass", ",", "mock_zeroconf", ")", ":", "await", "async_process_ha_core_config", "(", "hass", ",", "{", "\"external_url\"", ":", "\"https://example.com\"", "}", ",", ")", "await", "home_assistant_cast", ".", "async_setup_ha_cast", "(", "hass", ",", "MockConfigEntry", "(", ")", ")", "calls", "=", "async_mock_signal", "(", "hass", ",", "home_assistant_cast", ".", "SIGNAL_HASS_CAST_SHOW_VIEW", ")", "await", "hass", ".", "services", ".", "async_call", "(", "\"cast\"", ",", "\"show_lovelace_view\"", ",", "{", "\"entity_id\"", ":", "\"media_player.kitchen\"", ",", "\"view_path\"", ":", "\"mock_path\"", "}", ",", "blocking", "=", "True", ",", ")", "assert", "len", "(", "calls", ")", "==", "1", "controller", ",", "entity_id", ",", "view_path", ",", "url_path", "=", "calls", "[", "0", "]", "assert", "controller", ".", "hass_url", "==", "\"https://example.com\"", "assert", "controller", ".", "client_id", "is", "None", "# Verify user did not accidentally submit their dev app id", "assert", "controller", ".", "supporting_app_id", "==", "\"B12CE3CA\"", "assert", "entity_id", "==", "\"media_player.kitchen\"", "assert", "view_path", "==", "\"mock_path\"", "assert", "url_path", "is", "None" ]
[ 9, 0 ]
[ 33, 27 ]
python
en
['en', 'en', 'en']
True
test_service_show_view_dashboard
(hass, mock_zeroconf)
Test casting a specific dashboard.
Test casting a specific dashboard.
async def test_service_show_view_dashboard(hass, mock_zeroconf): """Test casting a specific dashboard.""" await async_process_ha_core_config( hass, {"external_url": "https://example.com"}, ) await home_assistant_cast.async_setup_ha_cast(hass, MockConfigEntry()) calls = async_mock_signal(hass, home_assistant_cast.SIGNAL_HASS_CAST_SHOW_VIEW) await hass.services.async_call( "cast", "show_lovelace_view", { "entity_id": "media_player.kitchen", "view_path": "mock_path", "dashboard_path": "mock-dashboard", }, blocking=True, ) assert len(calls) == 1 _controller, entity_id, view_path, url_path = calls[0] assert entity_id == "media_player.kitchen" assert view_path == "mock_path" assert url_path == "mock-dashboard"
[ "async", "def", "test_service_show_view_dashboard", "(", "hass", ",", "mock_zeroconf", ")", ":", "await", "async_process_ha_core_config", "(", "hass", ",", "{", "\"external_url\"", ":", "\"https://example.com\"", "}", ",", ")", "await", "home_assistant_cast", ".", "async_setup_ha_cast", "(", "hass", ",", "MockConfigEntry", "(", ")", ")", "calls", "=", "async_mock_signal", "(", "hass", ",", "home_assistant_cast", ".", "SIGNAL_HASS_CAST_SHOW_VIEW", ")", "await", "hass", ".", "services", ".", "async_call", "(", "\"cast\"", ",", "\"show_lovelace_view\"", ",", "{", "\"entity_id\"", ":", "\"media_player.kitchen\"", ",", "\"view_path\"", ":", "\"mock_path\"", ",", "\"dashboard_path\"", ":", "\"mock-dashboard\"", ",", "}", ",", "blocking", "=", "True", ",", ")", "assert", "len", "(", "calls", ")", "==", "1", "_controller", ",", "entity_id", ",", "view_path", ",", "url_path", "=", "calls", "[", "0", "]", "assert", "entity_id", "==", "\"media_player.kitchen\"", "assert", "view_path", "==", "\"mock_path\"", "assert", "url_path", "==", "\"mock-dashboard\"" ]
[ 36, 0 ]
[ 60, 39 ]
python
en
['en', 'en', 'en']
True
test_use_cloud_url
(hass, mock_zeroconf)
Test that we fall back to cloud url.
Test that we fall back to cloud url.
async def test_use_cloud_url(hass, mock_zeroconf): """Test that we fall back to cloud url.""" await async_process_ha_core_config( hass, {"internal_url": "http://example.local:8123"}, ) hass.config.components.add("cloud") await home_assistant_cast.async_setup_ha_cast(hass, MockConfigEntry()) calls = async_mock_signal(hass, home_assistant_cast.SIGNAL_HASS_CAST_SHOW_VIEW) with patch( "homeassistant.components.cloud.async_remote_ui_url", return_value="https://something.nabu.casa", ): await hass.services.async_call( "cast", "show_lovelace_view", {"entity_id": "media_player.kitchen", "view_path": "mock_path"}, blocking=True, ) assert len(calls) == 1 controller = calls[0][0] assert controller.hass_url == "https://something.nabu.casa"
[ "async", "def", "test_use_cloud_url", "(", "hass", ",", "mock_zeroconf", ")", ":", "await", "async_process_ha_core_config", "(", "hass", ",", "{", "\"internal_url\"", ":", "\"http://example.local:8123\"", "}", ",", ")", "hass", ".", "config", ".", "components", ".", "add", "(", "\"cloud\"", ")", "await", "home_assistant_cast", ".", "async_setup_ha_cast", "(", "hass", ",", "MockConfigEntry", "(", ")", ")", "calls", "=", "async_mock_signal", "(", "hass", ",", "home_assistant_cast", ".", "SIGNAL_HASS_CAST_SHOW_VIEW", ")", "with", "patch", "(", "\"homeassistant.components.cloud.async_remote_ui_url\"", ",", "return_value", "=", "\"https://something.nabu.casa\"", ",", ")", ":", "await", "hass", ".", "services", ".", "async_call", "(", "\"cast\"", ",", "\"show_lovelace_view\"", ",", "{", "\"entity_id\"", ":", "\"media_player.kitchen\"", ",", "\"view_path\"", ":", "\"mock_path\"", "}", ",", "blocking", "=", "True", ",", ")", "assert", "len", "(", "calls", ")", "==", "1", "controller", "=", "calls", "[", "0", "]", "[", "0", "]", "assert", "controller", ".", "hass_url", "==", "\"https://something.nabu.casa\"" ]
[ 63, 0 ]
[ 87, 63 ]
python
en
['en', 'en', 'en']
True
_validate_input
(data)
Validate the user input allows us to connect.
Validate the user input allows us to connect.
async def _validate_input(data): """Validate the user input allows us to connect.""" url = data[CONF_URL] api_key = data.get(CONF_API_KEY) try: api = NightscoutAPI(url, api_secret=api_key) status = await api.get_server_status() if status.settings.get("authDefaultRoles") == "status-only": await api.get_sgvs() except ClientResponseError as error: raise InputValidationError("invalid_auth") from error except (ClientError, AsyncIOTimeoutError, OSError) as error: raise InputValidationError("cannot_connect") from error # Return info to be stored in the config entry. return {"title": status.name}
[ "async", "def", "_validate_input", "(", "data", ")", ":", "url", "=", "data", "[", "CONF_URL", "]", "api_key", "=", "data", ".", "get", "(", "CONF_API_KEY", ")", "try", ":", "api", "=", "NightscoutAPI", "(", "url", ",", "api_secret", "=", "api_key", ")", "status", "=", "await", "api", ".", "get_server_status", "(", ")", "if", "status", ".", "settings", ".", "get", "(", "\"authDefaultRoles\"", ")", "==", "\"status-only\"", ":", "await", "api", ".", "get_sgvs", "(", ")", "except", "ClientResponseError", "as", "error", ":", "raise", "InputValidationError", "(", "\"invalid_auth\"", ")", "from", "error", "except", "(", "ClientError", ",", "AsyncIOTimeoutError", ",", "OSError", ")", "as", "error", ":", "raise", "InputValidationError", "(", "\"cannot_connect\"", ")", "from", "error", "# Return info to be stored in the config entry.", "return", "{", "\"title\"", ":", "status", ".", "name", "}" ]
[ 19, 0 ]
[ 34, 33 ]
python
en
['en', 'en', 'en']
True
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: unique_id = hash_from_url(user_input[CONF_URL]) await self.async_set_unique_id(unique_id) self._abort_if_unique_id_configured() try: info = await _validate_input(user_input) except InputValidationError as error: errors["base"] = error.base except Exception: # pylint: disable=broad-except _LOGGER.exception("Unexpected exception") errors["base"] = "unknown" else: return self.async_create_entry(title=info["title"], data=user_input) return self.async_show_form( step_id="user", data_schema=DATA_SCHEMA, errors=errors )
[ "async", "def", "async_step_user", "(", "self", ",", "user_input", "=", "None", ")", ":", "errors", "=", "{", "}", "if", "user_input", "is", "not", "None", ":", "unique_id", "=", "hash_from_url", "(", "user_input", "[", "CONF_URL", "]", ")", "await", "self", ".", "async_set_unique_id", "(", "unique_id", ")", "self", ".", "_abort_if_unique_id_configured", "(", ")", "try", ":", "info", "=", "await", "_validate_input", "(", "user_input", ")", "except", "InputValidationError", "as", "error", ":", "errors", "[", "\"base\"", "]", "=", "error", ".", "base", "except", "Exception", ":", "# pylint: disable=broad-except", "_LOGGER", ".", "exception", "(", "\"Unexpected exception\"", ")", "errors", "[", "\"base\"", "]", "=", "\"unknown\"", "else", ":", "return", "self", ".", "async_create_entry", "(", "title", "=", "info", "[", "\"title\"", "]", ",", "data", "=", "user_input", ")", "return", "self", ".", "async_show_form", "(", "step_id", "=", "\"user\"", ",", "data_schema", "=", "DATA_SCHEMA", ",", "errors", "=", "errors", ")" ]
[ 43, 4 ]
[ 63, 9 ]
python
en
['en', 'en', 'en']
True