Search is not available for this dataset
identifier
stringlengths
1
155
parameters
stringlengths
2
6.09k
docstring
stringlengths
11
63.4k
docstring_summary
stringlengths
0
63.4k
function
stringlengths
29
99.8k
function_tokens
sequence
start_point
sequence
end_point
sequence
language
stringclasses
1 value
docstring_language
stringlengths
2
7
docstring_language_predictions
stringlengths
18
23
is_langid_reliable
stringclasses
2 values
test_device_remove_non_tasmota_device
( hass, device_reg, hass_ws_client, mqtt_mock, setup_tasmota )
Test removing a non Tasmota device through device registry.
Test removing a non Tasmota device through device registry.
async def test_device_remove_non_tasmota_device( hass, device_reg, hass_ws_client, mqtt_mock, setup_tasmota ): """Test removing a non Tasmota device through device registry.""" config_entry = MockConfigEntry(domain="test") config_entry.add_to_hass(hass) mac = "12:34:56:AB:CD:EF" device_entry = device_reg.async_get_or_create( config_entry_id=config_entry.entry_id, connections={("mac", mac)}, ) assert device_entry is not None device_reg.async_remove_device(device_entry.id) await hass.async_block_till_done() # Verify device entry is removed device_entry = device_reg.async_get_device(set(), {("mac", mac)}) assert device_entry is None # Verify no Tasmota discovery message was sent mqtt_mock.async_publish.assert_not_called()
[ "async", "def", "test_device_remove_non_tasmota_device", "(", "hass", ",", "device_reg", ",", "hass_ws_client", ",", "mqtt_mock", ",", "setup_tasmota", ")", ":", "config_entry", "=", "MockConfigEntry", "(", "domain", "=", "\"test\"", ")", "config_entry", ".", "add_to_hass", "(", "hass", ")", "mac", "=", "\"12:34:56:AB:CD:EF\"", "device_entry", "=", "device_reg", ".", "async_get_or_create", "(", "config_entry_id", "=", "config_entry", ".", "entry_id", ",", "connections", "=", "{", "(", "\"mac\"", ",", "mac", ")", "}", ",", ")", "assert", "device_entry", "is", "not", "None", "device_reg", ".", "async_remove_device", "(", "device_entry", ".", "id", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "# Verify device entry is removed", "device_entry", "=", "device_reg", ".", "async_get_device", "(", "set", "(", ")", ",", "{", "(", "\"mac\"", ",", "mac", ")", "}", ")", "assert", "device_entry", "is", "None", "# Verify no Tasmota discovery message was sent", "mqtt_mock", ".", "async_publish", ".", "assert_not_called", "(", ")" ]
[ 44, 0 ]
[ 66, 47 ]
python
en
['en', 'en', 'en']
True
test_device_remove_stale_tasmota_device
( hass, device_reg, hass_ws_client, mqtt_mock, setup_tasmota )
Test removing a stale (undiscovered) Tasmota device through device registry.
Test removing a stale (undiscovered) Tasmota device through device registry.
async def test_device_remove_stale_tasmota_device( hass, device_reg, hass_ws_client, mqtt_mock, setup_tasmota ): """Test removing a stale (undiscovered) Tasmota device through device registry.""" config_entry = hass.config_entries.async_entries("tasmota")[0] mac = "12:34:56:AB:CD:EF" device_entry = device_reg.async_get_or_create( config_entry_id=config_entry.entry_id, connections={("mac", mac)}, ) assert device_entry is not None device_reg.async_remove_device(device_entry.id) await hass.async_block_till_done() # Verify device entry is removed device_entry = device_reg.async_get_device(set(), {("mac", mac)}) assert device_entry is None # Verify retained discovery topic has been cleared mac = mac.replace(":", "") mqtt_mock.async_publish.assert_has_calls( [ call(f"tasmota/discovery/{mac}/config", "", 0, True), call(f"tasmota/discovery/{mac}/sensors", "", 0, True), ], any_order=True, )
[ "async", "def", "test_device_remove_stale_tasmota_device", "(", "hass", ",", "device_reg", ",", "hass_ws_client", ",", "mqtt_mock", ",", "setup_tasmota", ")", ":", "config_entry", "=", "hass", ".", "config_entries", ".", "async_entries", "(", "\"tasmota\"", ")", "[", "0", "]", "mac", "=", "\"12:34:56:AB:CD:EF\"", "device_entry", "=", "device_reg", ".", "async_get_or_create", "(", "config_entry_id", "=", "config_entry", ".", "entry_id", ",", "connections", "=", "{", "(", "\"mac\"", ",", "mac", ")", "}", ",", ")", "assert", "device_entry", "is", "not", "None", "device_reg", ".", "async_remove_device", "(", "device_entry", ".", "id", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "# Verify device entry is removed", "device_entry", "=", "device_reg", ".", "async_get_device", "(", "set", "(", ")", ",", "{", "(", "\"mac\"", ",", "mac", ")", "}", ")", "assert", "device_entry", "is", "None", "# Verify retained discovery topic has been cleared", "mac", "=", "mac", ".", "replace", "(", "\":\"", ",", "\"\"", ")", "mqtt_mock", ".", "async_publish", ".", "assert_has_calls", "(", "[", "call", "(", "f\"tasmota/discovery/{mac}/config\"", ",", "\"\"", ",", "0", ",", "True", ")", ",", "call", "(", "f\"tasmota/discovery/{mac}/sensors\"", ",", "\"\"", ",", "0", ",", "True", ")", ",", "]", ",", "any_order", "=", "True", ",", ")" ]
[ 69, 0 ]
[ 97, 5 ]
python
en
['en', 'en', 'en']
True
test_tasmota_ws_remove_discovered_device
( hass, device_reg, entity_reg, hass_ws_client, mqtt_mock, setup_tasmota )
Test Tasmota websocket device removal.
Test Tasmota websocket device removal.
async def test_tasmota_ws_remove_discovered_device( hass, device_reg, entity_reg, hass_ws_client, mqtt_mock, setup_tasmota ): """Test Tasmota websocket device removal.""" config = copy.deepcopy(DEFAULT_CONFIG) mac = config["mac"] async_fire_mqtt_message(hass, f"{DEFAULT_PREFIX}/{mac}/config", json.dumps(config)) await hass.async_block_till_done() # Verify device entry is created device_entry = device_reg.async_get_device(set(), {("mac", mac)}) assert device_entry is not None client = await hass_ws_client(hass) await client.send_json( {"id": 5, "type": "tasmota/device/remove", "device_id": device_entry.id} ) response = await client.receive_json() assert response["success"] # Verify device entry is cleared device_entry = device_reg.async_get_device(set(), {("mac", mac)}) assert device_entry is None
[ "async", "def", "test_tasmota_ws_remove_discovered_device", "(", "hass", ",", "device_reg", ",", "entity_reg", ",", "hass_ws_client", ",", "mqtt_mock", ",", "setup_tasmota", ")", ":", "config", "=", "copy", ".", "deepcopy", "(", "DEFAULT_CONFIG", ")", "mac", "=", "config", "[", "\"mac\"", "]", "async_fire_mqtt_message", "(", "hass", ",", "f\"{DEFAULT_PREFIX}/{mac}/config\"", ",", "json", ".", "dumps", "(", "config", ")", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "# Verify device entry is created", "device_entry", "=", "device_reg", ".", "async_get_device", "(", "set", "(", ")", ",", "{", "(", "\"mac\"", ",", "mac", ")", "}", ")", "assert", "device_entry", "is", "not", "None", "client", "=", "await", "hass_ws_client", "(", "hass", ")", "await", "client", ".", "send_json", "(", "{", "\"id\"", ":", "5", ",", "\"type\"", ":", "\"tasmota/device/remove\"", ",", "\"device_id\"", ":", "device_entry", ".", "id", "}", ")", "response", "=", "await", "client", ".", "receive_json", "(", ")", "assert", "response", "[", "\"success\"", "]", "# Verify device entry is cleared", "device_entry", "=", "device_reg", ".", "async_get_device", "(", "set", "(", ")", ",", "{", "(", "\"mac\"", ",", "mac", ")", "}", ")", "assert", "device_entry", "is", "None" ]
[ 100, 0 ]
[ 123, 31 ]
python
da
['nl', 'da', 'it']
False
test_tasmota_ws_remove_discovered_device_twice
( hass, device_reg, hass_ws_client, mqtt_mock, setup_tasmota )
Test Tasmota websocket device removal.
Test Tasmota websocket device removal.
async def test_tasmota_ws_remove_discovered_device_twice( hass, device_reg, hass_ws_client, mqtt_mock, setup_tasmota ): """Test Tasmota websocket device removal.""" config = copy.deepcopy(DEFAULT_CONFIG) mac = config["mac"] async_fire_mqtt_message(hass, f"{DEFAULT_PREFIX}/{mac}/config", json.dumps(config)) await hass.async_block_till_done() # Verify device entry is created device_entry = device_reg.async_get_device(set(), {("mac", mac)}) assert device_entry is not None client = await hass_ws_client(hass) await client.send_json( {"id": 5, "type": "tasmota/device/remove", "device_id": device_entry.id} ) response = await client.receive_json() assert response["success"] await client.send_json( {"id": 6, "type": "tasmota/device/remove", "device_id": device_entry.id} ) response = await client.receive_json() assert not response["success"] assert response["error"]["code"] == websocket_api.const.ERR_NOT_FOUND assert response["error"]["message"] == "Device not found"
[ "async", "def", "test_tasmota_ws_remove_discovered_device_twice", "(", "hass", ",", "device_reg", ",", "hass_ws_client", ",", "mqtt_mock", ",", "setup_tasmota", ")", ":", "config", "=", "copy", ".", "deepcopy", "(", "DEFAULT_CONFIG", ")", "mac", "=", "config", "[", "\"mac\"", "]", "async_fire_mqtt_message", "(", "hass", ",", "f\"{DEFAULT_PREFIX}/{mac}/config\"", ",", "json", ".", "dumps", "(", "config", ")", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "# Verify device entry is created", "device_entry", "=", "device_reg", ".", "async_get_device", "(", "set", "(", ")", ",", "{", "(", "\"mac\"", ",", "mac", ")", "}", ")", "assert", "device_entry", "is", "not", "None", "client", "=", "await", "hass_ws_client", "(", "hass", ")", "await", "client", ".", "send_json", "(", "{", "\"id\"", ":", "5", ",", "\"type\"", ":", "\"tasmota/device/remove\"", ",", "\"device_id\"", ":", "device_entry", ".", "id", "}", ")", "response", "=", "await", "client", ".", "receive_json", "(", ")", "assert", "response", "[", "\"success\"", "]", "await", "client", ".", "send_json", "(", "{", "\"id\"", ":", "6", ",", "\"type\"", ":", "\"tasmota/device/remove\"", ",", "\"device_id\"", ":", "device_entry", ".", "id", "}", ")", "response", "=", "await", "client", ".", "receive_json", "(", ")", "assert", "not", "response", "[", "\"success\"", "]", "assert", "response", "[", "\"error\"", "]", "[", "\"code\"", "]", "==", "websocket_api", ".", "const", ".", "ERR_NOT_FOUND", "assert", "response", "[", "\"error\"", "]", "[", "\"message\"", "]", "==", "\"Device not found\"" ]
[ 126, 0 ]
[ 153, 61 ]
python
da
['nl', 'da', 'it']
False
test_tasmota_ws_remove_non_tasmota_device
( hass, device_reg, hass_ws_client, mqtt_mock, setup_tasmota )
Test Tasmota websocket device removal of device belonging to other domain.
Test Tasmota websocket device removal of device belonging to other domain.
async def test_tasmota_ws_remove_non_tasmota_device( hass, device_reg, hass_ws_client, mqtt_mock, setup_tasmota ): """Test Tasmota websocket device removal of device belonging to other domain.""" config_entry = MockConfigEntry(domain="test") config_entry.add_to_hass(hass) device_entry = device_reg.async_get_or_create( config_entry_id=config_entry.entry_id, connections={("mac", "12:34:56:AB:CD:EF")}, ) assert device_entry is not None client = await hass_ws_client(hass) await client.send_json( {"id": 5, "type": "tasmota/device/remove", "device_id": device_entry.id} ) response = await client.receive_json() assert not response["success"] assert response["error"]["code"] == websocket_api.const.ERR_NOT_FOUND
[ "async", "def", "test_tasmota_ws_remove_non_tasmota_device", "(", "hass", ",", "device_reg", ",", "hass_ws_client", ",", "mqtt_mock", ",", "setup_tasmota", ")", ":", "config_entry", "=", "MockConfigEntry", "(", "domain", "=", "\"test\"", ")", "config_entry", ".", "add_to_hass", "(", "hass", ")", "device_entry", "=", "device_reg", ".", "async_get_or_create", "(", "config_entry_id", "=", "config_entry", ".", "entry_id", ",", "connections", "=", "{", "(", "\"mac\"", ",", "\"12:34:56:AB:CD:EF\"", ")", "}", ",", ")", "assert", "device_entry", "is", "not", "None", "client", "=", "await", "hass_ws_client", "(", "hass", ")", "await", "client", ".", "send_json", "(", "{", "\"id\"", ":", "5", ",", "\"type\"", ":", "\"tasmota/device/remove\"", ",", "\"device_id\"", ":", "device_entry", ".", "id", "}", ")", "response", "=", "await", "client", ".", "receive_json", "(", ")", "assert", "not", "response", "[", "\"success\"", "]", "assert", "response", "[", "\"error\"", "]", "[", "\"code\"", "]", "==", "websocket_api", ".", "const", ".", "ERR_NOT_FOUND" ]
[ 156, 0 ]
[ 175, 73 ]
python
en
['en', 'en', '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" ]
[ 26, 0 ]
[ 28, 8 ]
python
en
['da', 'en', 'en']
True
gpslogger_client
(loop, hass, aiohttp_client)
Mock client for GPSLogger (unauthenticated).
Mock client for GPSLogger (unauthenticated).
async def gpslogger_client(loop, hass, aiohttp_client): """Mock client for GPSLogger (unauthenticated).""" assert await async_setup_component(hass, "persistent_notification", {}) 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 aiohttp_client(hass.http.app)
[ "async", "def", "gpslogger_client", "(", "loop", ",", "hass", ",", "aiohttp_client", ")", ":", "assert", "await", "async_setup_component", "(", "hass", ",", "\"persistent_notification\"", ",", "{", "}", ")", "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", "aiohttp_client", "(", "hass", ".", "http", ".", "app", ")" ]
[ 32, 0 ]
[ 41, 50 ]
python
en
['en', 'en', 'en']
True
setup_zones
(loop, hass)
Set up Zone config in HA.
Set up Zone config in HA.
async def setup_zones(loop, hass): """Set up Zone config in HA.""" assert await async_setup_component( hass, zone.DOMAIN, { "zone": { "name": "Home", "latitude": HOME_LATITUDE, "longitude": HOME_LONGITUDE, "radius": 100, } }, ) await hass.async_block_till_done()
[ "async", "def", "setup_zones", "(", "loop", ",", "hass", ")", ":", "assert", "await", "async_setup_component", "(", "hass", ",", "zone", ".", "DOMAIN", ",", "{", "\"zone\"", ":", "{", "\"name\"", ":", "\"Home\"", ",", "\"latitude\"", ":", "HOME_LATITUDE", ",", "\"longitude\"", ":", "HOME_LONGITUDE", ",", "\"radius\"", ":", "100", ",", "}", "}", ",", ")", "await", "hass", ".", "async_block_till_done", "(", ")" ]
[ 45, 0 ]
[ 59, 38 ]
python
en
['en', 'en', 'en']
True
webhook_id
(hass, gpslogger_client)
Initialize the GPSLogger component and get the webhook_id.
Initialize the GPSLogger component and get the webhook_id.
async def webhook_id(hass, gpslogger_client): """Initialize the GPSLogger 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( DOMAIN, 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", ",", "gpslogger_client", ")", ":", "await", "async_process_ha_core_config", "(", "hass", ",", "{", "\"internal_url\"", ":", "\"http://example.local:8123\"", "}", ",", ")", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "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\"", "]" ]
[ 63, 0 ]
[ 78, 46 ]
python
en
['en', 'en', 'en']
True
test_missing_data
(hass, gpslogger_client, webhook_id)
Test missing data.
Test missing data.
async def test_missing_data(hass, gpslogger_client, webhook_id): """Test missing data.""" url = f"/api/webhook/{webhook_id}" data = {"latitude": 1.0, "longitude": 1.1, "device": "123"} # No data req = await gpslogger_client.post(url) await hass.async_block_till_done() assert req.status == HTTP_UNPROCESSABLE_ENTITY # No latitude copy = data.copy() del copy["latitude"] req = await gpslogger_client.post(url, data=copy) await hass.async_block_till_done() assert req.status == HTTP_UNPROCESSABLE_ENTITY # No device copy = data.copy() del copy["device"] req = await gpslogger_client.post(url, data=copy) await hass.async_block_till_done() assert req.status == HTTP_UNPROCESSABLE_ENTITY
[ "async", "def", "test_missing_data", "(", "hass", ",", "gpslogger_client", ",", "webhook_id", ")", ":", "url", "=", "f\"/api/webhook/{webhook_id}\"", "data", "=", "{", "\"latitude\"", ":", "1.0", ",", "\"longitude\"", ":", "1.1", ",", "\"device\"", ":", "\"123\"", "}", "# No data", "req", "=", "await", "gpslogger_client", ".", "post", "(", "url", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "req", ".", "status", "==", "HTTP_UNPROCESSABLE_ENTITY", "# No latitude", "copy", "=", "data", ".", "copy", "(", ")", "del", "copy", "[", "\"latitude\"", "]", "req", "=", "await", "gpslogger_client", ".", "post", "(", "url", ",", "data", "=", "copy", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "req", ".", "status", "==", "HTTP_UNPROCESSABLE_ENTITY", "# No device", "copy", "=", "data", ".", "copy", "(", ")", "del", "copy", "[", "\"device\"", "]", "req", "=", "await", "gpslogger_client", ".", "post", "(", "url", ",", "data", "=", "copy", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "req", ".", "status", "==", "HTTP_UNPROCESSABLE_ENTITY" ]
[ 81, 0 ]
[ 104, 50 ]
python
de
['de', 'no', 'en']
False
test_enter_and_exit
(hass, gpslogger_client, webhook_id)
Test when there is a known zone.
Test when there is a known zone.
async def test_enter_and_exit(hass, gpslogger_client, webhook_id): """Test when there is a known zone.""" url = f"/api/webhook/{webhook_id}" data = {"latitude": HOME_LATITUDE, "longitude": HOME_LONGITUDE, "device": "123"} # Enter the Home req = await gpslogger_client.post(url, data=data) await hass.async_block_till_done() assert req.status == HTTP_OK state_name = hass.states.get(f"{DEVICE_TRACKER_DOMAIN}.{data['device']}").state assert STATE_HOME == state_name # Enter Home again req = await gpslogger_client.post(url, data=data) await hass.async_block_till_done() assert req.status == HTTP_OK state_name = hass.states.get(f"{DEVICE_TRACKER_DOMAIN}.{data['device']}").state assert STATE_HOME == state_name data["longitude"] = 0 data["latitude"] = 0 # Enter Somewhere else req = await gpslogger_client.post(url, data=data) await hass.async_block_till_done() assert req.status == HTTP_OK state_name = hass.states.get(f"{DEVICE_TRACKER_DOMAIN}.{data['device']}").state assert STATE_NOT_HOME == state_name dev_reg = await hass.helpers.device_registry.async_get_registry() assert len(dev_reg.devices) == 1 ent_reg = await hass.helpers.entity_registry.async_get_registry() assert len(ent_reg.entities) == 1
[ "async", "def", "test_enter_and_exit", "(", "hass", ",", "gpslogger_client", ",", "webhook_id", ")", ":", "url", "=", "f\"/api/webhook/{webhook_id}\"", "data", "=", "{", "\"latitude\"", ":", "HOME_LATITUDE", ",", "\"longitude\"", ":", "HOME_LONGITUDE", ",", "\"device\"", ":", "\"123\"", "}", "# Enter the Home", "req", "=", "await", "gpslogger_client", ".", "post", "(", "url", ",", "data", "=", "data", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "req", ".", "status", "==", "HTTP_OK", "state_name", "=", "hass", ".", "states", ".", "get", "(", "f\"{DEVICE_TRACKER_DOMAIN}.{data['device']}\"", ")", ".", "state", "assert", "STATE_HOME", "==", "state_name", "# Enter Home again", "req", "=", "await", "gpslogger_client", ".", "post", "(", "url", ",", "data", "=", "data", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "req", ".", "status", "==", "HTTP_OK", "state_name", "=", "hass", ".", "states", ".", "get", "(", "f\"{DEVICE_TRACKER_DOMAIN}.{data['device']}\"", ")", ".", "state", "assert", "STATE_HOME", "==", "state_name", "data", "[", "\"longitude\"", "]", "=", "0", "data", "[", "\"latitude\"", "]", "=", "0", "# Enter Somewhere else", "req", "=", "await", "gpslogger_client", ".", "post", "(", "url", ",", "data", "=", "data", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "req", ".", "status", "==", "HTTP_OK", "state_name", "=", "hass", ".", "states", ".", "get", "(", "f\"{DEVICE_TRACKER_DOMAIN}.{data['device']}\"", ")", ".", "state", "assert", "STATE_NOT_HOME", "==", "state_name", "dev_reg", "=", "await", "hass", ".", "helpers", ".", "device_registry", ".", "async_get_registry", "(", ")", "assert", "len", "(", "dev_reg", ".", "devices", ")", "==", "1", "ent_reg", "=", "await", "hass", ".", "helpers", ".", "entity_registry", ".", "async_get_registry", "(", ")", "assert", "len", "(", "ent_reg", ".", "entities", ")", "==", "1" ]
[ 107, 0 ]
[ 141, 37 ]
python
en
['en', 'en', 'en']
True
test_enter_with_attrs
(hass, gpslogger_client, webhook_id)
Test when additional attributes are present.
Test when additional attributes are present.
async def test_enter_with_attrs(hass, gpslogger_client, webhook_id): """Test when additional attributes are present.""" url = f"/api/webhook/{webhook_id}" data = { "latitude": 1.0, "longitude": 1.1, "device": "123", "accuracy": 10.5, "battery": 10, "speed": 100, "direction": 105.32, "altitude": 102, "provider": "gps", "activity": "running", } req = await gpslogger_client.post(url, data=data) await hass.async_block_till_done() assert req.status == HTTP_OK state = hass.states.get(f"{DEVICE_TRACKER_DOMAIN}.{data['device']}") assert state.state == STATE_NOT_HOME assert state.attributes["gps_accuracy"] == 10.5 assert state.attributes["battery_level"] == 10.0 assert state.attributes["speed"] == 100.0 assert state.attributes["direction"] == 105.32 assert state.attributes["altitude"] == 102.0 assert state.attributes["provider"] == "gps" assert state.attributes["activity"] == "running" data = { "latitude": HOME_LATITUDE, "longitude": HOME_LONGITUDE, "device": "123", "accuracy": 123, "battery": 23, "speed": 23, "direction": 123, "altitude": 123, "provider": "gps", "activity": "idle", } req = await gpslogger_client.post(url, data=data) await hass.async_block_till_done() assert req.status == HTTP_OK state = hass.states.get(f"{DEVICE_TRACKER_DOMAIN}.{data['device']}") assert state.state == STATE_HOME assert state.attributes["gps_accuracy"] == 123 assert state.attributes["battery_level"] == 23 assert state.attributes["speed"] == 23 assert state.attributes["direction"] == 123 assert state.attributes["altitude"] == 123 assert state.attributes["provider"] == "gps" assert state.attributes["activity"] == "idle"
[ "async", "def", "test_enter_with_attrs", "(", "hass", ",", "gpslogger_client", ",", "webhook_id", ")", ":", "url", "=", "f\"/api/webhook/{webhook_id}\"", "data", "=", "{", "\"latitude\"", ":", "1.0", ",", "\"longitude\"", ":", "1.1", ",", "\"device\"", ":", "\"123\"", ",", "\"accuracy\"", ":", "10.5", ",", "\"battery\"", ":", "10", ",", "\"speed\"", ":", "100", ",", "\"direction\"", ":", "105.32", ",", "\"altitude\"", ":", "102", ",", "\"provider\"", ":", "\"gps\"", ",", "\"activity\"", ":", "\"running\"", ",", "}", "req", "=", "await", "gpslogger_client", ".", "post", "(", "url", ",", "data", "=", "data", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "req", ".", "status", "==", "HTTP_OK", "state", "=", "hass", ".", "states", ".", "get", "(", "f\"{DEVICE_TRACKER_DOMAIN}.{data['device']}\"", ")", "assert", "state", ".", "state", "==", "STATE_NOT_HOME", "assert", "state", ".", "attributes", "[", "\"gps_accuracy\"", "]", "==", "10.5", "assert", "state", ".", "attributes", "[", "\"battery_level\"", "]", "==", "10.0", "assert", "state", ".", "attributes", "[", "\"speed\"", "]", "==", "100.0", "assert", "state", ".", "attributes", "[", "\"direction\"", "]", "==", "105.32", "assert", "state", ".", "attributes", "[", "\"altitude\"", "]", "==", "102.0", "assert", "state", ".", "attributes", "[", "\"provider\"", "]", "==", "\"gps\"", "assert", "state", ".", "attributes", "[", "\"activity\"", "]", "==", "\"running\"", "data", "=", "{", "\"latitude\"", ":", "HOME_LATITUDE", ",", "\"longitude\"", ":", "HOME_LONGITUDE", ",", "\"device\"", ":", "\"123\"", ",", "\"accuracy\"", ":", "123", ",", "\"battery\"", ":", "23", ",", "\"speed\"", ":", "23", ",", "\"direction\"", ":", "123", ",", "\"altitude\"", ":", "123", ",", "\"provider\"", ":", "\"gps\"", ",", "\"activity\"", ":", "\"idle\"", ",", "}", "req", "=", "await", "gpslogger_client", ".", "post", "(", "url", ",", "data", "=", "data", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "req", ".", "status", "==", "HTTP_OK", "state", "=", "hass", ".", "states", ".", "get", "(", "f\"{DEVICE_TRACKER_DOMAIN}.{data['device']}\"", ")", "assert", "state", ".", "state", "==", "STATE_HOME", "assert", "state", ".", "attributes", "[", "\"gps_accuracy\"", "]", "==", "123", "assert", "state", ".", "attributes", "[", "\"battery_level\"", "]", "==", "23", "assert", "state", ".", "attributes", "[", "\"speed\"", "]", "==", "23", "assert", "state", ".", "attributes", "[", "\"direction\"", "]", "==", "123", "assert", "state", ".", "attributes", "[", "\"altitude\"", "]", "==", "123", "assert", "state", ".", "attributes", "[", "\"provider\"", "]", "==", "\"gps\"", "assert", "state", ".", "attributes", "[", "\"activity\"", "]", "==", "\"idle\"" ]
[ 144, 0 ]
[ 198, 49 ]
python
en
['en', 'en', 'en']
True
test_load_unload_entry
(hass, gpslogger_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, gpslogger_client, webhook_id): """Test that the appropriate dispatch signals are added and removed.""" url = f"/api/webhook/{webhook_id}" data = {"latitude": HOME_LATITUDE, "longitude": HOME_LONGITUDE, "device": "123"} # Enter the Home req = await gpslogger_client.post(url, data=data) await hass.async_block_till_done() assert req.status == HTTP_OK state_name = hass.states.get(f"{DEVICE_TRACKER_DOMAIN}.{data['device']}").state assert STATE_HOME == state_name assert len(hass.data[DATA_DISPATCHER][TRACKER_UPDATE]) == 1 entry = hass.config_entries.async_entries(DOMAIN)[0] assert await gpslogger.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", ",", "gpslogger_client", ",", "webhook_id", ")", ":", "url", "=", "f\"/api/webhook/{webhook_id}\"", "data", "=", "{", "\"latitude\"", ":", "HOME_LATITUDE", ",", "\"longitude\"", ":", "HOME_LONGITUDE", ",", "\"device\"", ":", "\"123\"", "}", "# Enter the Home", "req", "=", "await", "gpslogger_client", ".", "post", "(", "url", ",", "data", "=", "data", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "req", ".", "status", "==", "HTTP_OK", "state_name", "=", "hass", ".", "states", ".", "get", "(", "f\"{DEVICE_TRACKER_DOMAIN}.{data['device']}\"", ")", ".", "state", "assert", "STATE_HOME", "==", "state_name", "assert", "len", "(", "hass", ".", "data", "[", "DATA_DISPATCHER", "]", "[", "TRACKER_UPDATE", "]", ")", "==", "1", "entry", "=", "hass", ".", "config_entries", ".", "async_entries", "(", "DOMAIN", ")", "[", "0", "]", "assert", "await", "gpslogger", ".", "async_unload_entry", "(", "hass", ",", "entry", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "not", "hass", ".", "data", "[", "DATA_DISPATCHER", "]", "[", "TRACKER_UPDATE", "]" ]
[ 204, 0 ]
[ 221, 57 ]
python
en
['en', 'en', 'en']
True
mock_storage
(hass_storage)
Autouse hass_storage for the TestCase tests.
Autouse hass_storage for the TestCase tests.
def mock_storage(hass_storage): """Autouse hass_storage for the TestCase tests."""
[ "def", "mock_storage", "(", "hass_storage", ")", ":" ]
[ 35, 0 ]
[ 36, 54 ]
python
en
['en', 'en', 'en']
True
device_reg
(hass)
Return an empty, loaded, registry.
Return an empty, loaded, registry.
def device_reg(hass): """Return an empty, loaded, registry.""" return mock_device_registry(hass)
[ "def", "device_reg", "(", "hass", ")", ":", "return", "mock_device_registry", "(", "hass", ")" ]
[ 40, 0 ]
[ 42, 37 ]
python
en
['en', 'fy', 'en']
True
entity_reg
(hass)
Return an empty, loaded, registry.
Return an empty, loaded, registry.
def entity_reg(hass): """Return an empty, loaded, registry.""" return mock_registry(hass)
[ "def", "entity_reg", "(", "hass", ")", ":", "return", "mock_registry", "(", "hass", ")" ]
[ 46, 0 ]
[ 48, 30 ]
python
en
['en', 'fy', 'en']
True
mock_mqtt
()
Make sure connection is established.
Make sure connection is established.
def mock_mqtt(): """Make sure connection is established.""" with patch("homeassistant.components.mqtt.MQTT") as mock_mqtt: mock_mqtt.return_value.async_connect = AsyncMock(return_value=True) mock_mqtt.return_value.async_disconnect = AsyncMock(return_value=True) yield mock_mqtt
[ "def", "mock_mqtt", "(", ")", ":", "with", "patch", "(", "\"homeassistant.components.mqtt.MQTT\"", ")", "as", "mock_mqtt", ":", "mock_mqtt", ".", "return_value", ".", "async_connect", "=", "AsyncMock", "(", "return_value", "=", "True", ")", "mock_mqtt", ".", "return_value", ".", "async_disconnect", "=", "AsyncMock", "(", "return_value", "=", "True", ")", "yield", "mock_mqtt" ]
[ 52, 0 ]
[ 57, 23 ]
python
en
['en', 'da', 'en']
True
calls
()
Fixture to record calls.
Fixture to record calls.
def calls(): """Fixture to record calls.""" return []
[ "def", "calls", "(", ")", ":", "return", "[", "]" ]
[ 61, 0 ]
[ 63, 13 ]
python
en
['en', 'ca', 'en']
True
record_calls
(calls)
Fixture to record calls.
Fixture to record calls.
def record_calls(calls): """Fixture to record calls.""" @callback def record_calls(*args): """Record calls.""" calls.append(args) return record_calls
[ "def", "record_calls", "(", "calls", ")", ":", "@", "callback", "def", "record_calls", "(", "*", "args", ")", ":", "\"\"\"Record calls.\"\"\"", "calls", ".", "append", "(", "args", ")", "return", "record_calls" ]
[ 67, 0 ]
[ 75, 23 ]
python
en
['en', 'ca', 'en']
True
test_mqtt_connects_on_home_assistant_mqtt_setup
( hass, mqtt_client_mock, mqtt_mock )
Test if client is connected after mqtt init on bootstrap.
Test if client is connected after mqtt init on bootstrap.
async def test_mqtt_connects_on_home_assistant_mqtt_setup( hass, mqtt_client_mock, mqtt_mock ): """Test if client is connected after mqtt init on bootstrap.""" assert mqtt_client_mock.connect.call_count == 1
[ "async", "def", "test_mqtt_connects_on_home_assistant_mqtt_setup", "(", "hass", ",", "mqtt_client_mock", ",", "mqtt_mock", ")", ":", "assert", "mqtt_client_mock", ".", "connect", ".", "call_count", "==", "1" ]
[ 78, 0 ]
[ 82, 51 ]
python
en
['en', 'en', 'en']
True
test_mqtt_disconnects_on_home_assistant_stop
(hass, mqtt_mock)
Test if client stops on HA stop.
Test if client stops on HA stop.
async def test_mqtt_disconnects_on_home_assistant_stop(hass, mqtt_mock): """Test if client stops on HA stop.""" hass.bus.fire(EVENT_HOMEASSISTANT_STOP) await hass.async_block_till_done() await hass.async_block_till_done() assert mqtt_mock.async_disconnect.called
[ "async", "def", "test_mqtt_disconnects_on_home_assistant_stop", "(", "hass", ",", "mqtt_mock", ")", ":", "hass", ".", "bus", ".", "fire", "(", "EVENT_HOMEASSISTANT_STOP", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "mqtt_mock", ".", "async_disconnect", ".", "called" ]
[ 85, 0 ]
[ 90, 44 ]
python
en
['en', 'en', 'en']
True
test_publish_calls_service
(hass, mqtt_mock, calls, record_calls)
Test the publishing of call to services.
Test the publishing of call to services.
async def test_publish_calls_service(hass, mqtt_mock, calls, record_calls): """Test the publishing of call to services.""" hass.bus.async_listen_once(EVENT_CALL_SERVICE, record_calls) mqtt.async_publish(hass, "test-topic", "test-payload") await hass.async_block_till_done() assert len(calls) == 1 assert calls[0][0].data["service_data"][mqtt.ATTR_TOPIC] == "test-topic" assert calls[0][0].data["service_data"][mqtt.ATTR_PAYLOAD] == "test-payload"
[ "async", "def", "test_publish_calls_service", "(", "hass", ",", "mqtt_mock", ",", "calls", ",", "record_calls", ")", ":", "hass", ".", "bus", ".", "async_listen_once", "(", "EVENT_CALL_SERVICE", ",", "record_calls", ")", "mqtt", ".", "async_publish", "(", "hass", ",", "\"test-topic\"", ",", "\"test-payload\"", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "calls", ")", "==", "1", "assert", "calls", "[", "0", "]", "[", "0", "]", ".", "data", "[", "\"service_data\"", "]", "[", "mqtt", ".", "ATTR_TOPIC", "]", "==", "\"test-topic\"", "assert", "calls", "[", "0", "]", "[", "0", "]", ".", "data", "[", "\"service_data\"", "]", "[", "mqtt", ".", "ATTR_PAYLOAD", "]", "==", "\"test-payload\"" ]
[ 93, 0 ]
[ 103, 80 ]
python
en
['en', 'en', 'en']
True
test_service_call_without_topic_does_not_publish
(hass, mqtt_mock)
Test the service call if topic is missing.
Test the service call if topic is missing.
async def test_service_call_without_topic_does_not_publish(hass, mqtt_mock): """Test the service call if topic is missing.""" hass.bus.fire( EVENT_CALL_SERVICE, {ATTR_DOMAIN: mqtt.DOMAIN, ATTR_SERVICE: mqtt.SERVICE_PUBLISH}, ) await hass.async_block_till_done() assert not mqtt_mock.async_publish.called
[ "async", "def", "test_service_call_without_topic_does_not_publish", "(", "hass", ",", "mqtt_mock", ")", ":", "hass", ".", "bus", ".", "fire", "(", "EVENT_CALL_SERVICE", ",", "{", "ATTR_DOMAIN", ":", "mqtt", ".", "DOMAIN", ",", "ATTR_SERVICE", ":", "mqtt", ".", "SERVICE_PUBLISH", "}", ",", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "not", "mqtt_mock", ".", "async_publish", ".", "called" ]
[ 106, 0 ]
[ 113, 45 ]
python
en
['en', 'en', 'en']
True
test_service_call_with_template_payload_renders_template
(hass, mqtt_mock)
Test the service call with rendered template. If 'payload_template' is provided and 'payload' is not, then render it.
Test the service call with rendered template.
async def test_service_call_with_template_payload_renders_template(hass, mqtt_mock): """Test the service call with rendered template. If 'payload_template' is provided and 'payload' is not, then render it. """ mqtt.async_publish_template(hass, "test/topic", "{{ 1+1 }}") await hass.async_block_till_done() assert mqtt_mock.async_publish.called assert mqtt_mock.async_publish.call_args[0][1] == "2"
[ "async", "def", "test_service_call_with_template_payload_renders_template", "(", "hass", ",", "mqtt_mock", ")", ":", "mqtt", ".", "async_publish_template", "(", "hass", ",", "\"test/topic\"", ",", "\"{{ 1+1 }}\"", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "mqtt_mock", ".", "async_publish", ".", "called", "assert", "mqtt_mock", ".", "async_publish", ".", "call_args", "[", "0", "]", "[", "1", "]", "==", "\"2\"" ]
[ 116, 0 ]
[ 124, 57 ]
python
en
['en', 'en', 'en']
True
test_service_call_with_payload_doesnt_render_template
(hass, mqtt_mock)
Test the service call with unrendered template. If both 'payload' and 'payload_template' are provided then fail.
Test the service call with unrendered template.
async def test_service_call_with_payload_doesnt_render_template(hass, mqtt_mock): """Test the service call with unrendered template. If both 'payload' and 'payload_template' are provided then fail. """ payload = "not a template" payload_template = "a template" with pytest.raises(vol.Invalid): await hass.services.async_call( mqtt.DOMAIN, mqtt.SERVICE_PUBLISH, { mqtt.ATTR_TOPIC: "test/topic", mqtt.ATTR_PAYLOAD: payload, mqtt.ATTR_PAYLOAD_TEMPLATE: payload_template, }, blocking=True, ) assert not mqtt_mock.async_publish.called
[ "async", "def", "test_service_call_with_payload_doesnt_render_template", "(", "hass", ",", "mqtt_mock", ")", ":", "payload", "=", "\"not a template\"", "payload_template", "=", "\"a template\"", "with", "pytest", ".", "raises", "(", "vol", ".", "Invalid", ")", ":", "await", "hass", ".", "services", ".", "async_call", "(", "mqtt", ".", "DOMAIN", ",", "mqtt", ".", "SERVICE_PUBLISH", ",", "{", "mqtt", ".", "ATTR_TOPIC", ":", "\"test/topic\"", ",", "mqtt", ".", "ATTR_PAYLOAD", ":", "payload", ",", "mqtt", ".", "ATTR_PAYLOAD_TEMPLATE", ":", "payload_template", ",", "}", ",", "blocking", "=", "True", ",", ")", "assert", "not", "mqtt_mock", ".", "async_publish", ".", "called" ]
[ 127, 0 ]
[ 145, 45 ]
python
en
['en', 'en', 'en']
True
test_service_call_with_ascii_qos_retain_flags
(hass, mqtt_mock)
Test the service call with args that can be misinterpreted. Empty payload message and ascii formatted qos and retain flags.
Test the service call with args that can be misinterpreted.
async def test_service_call_with_ascii_qos_retain_flags(hass, mqtt_mock): """Test the service call with args that can be misinterpreted. Empty payload message and ascii formatted qos and retain flags. """ await hass.services.async_call( mqtt.DOMAIN, mqtt.SERVICE_PUBLISH, { mqtt.ATTR_TOPIC: "test/topic", mqtt.ATTR_PAYLOAD: "", mqtt.ATTR_QOS: "2", mqtt.ATTR_RETAIN: "no", }, blocking=True, ) assert mqtt_mock.async_publish.called assert mqtt_mock.async_publish.call_args[0][2] == 2 assert not mqtt_mock.async_publish.call_args[0][3]
[ "async", "def", "test_service_call_with_ascii_qos_retain_flags", "(", "hass", ",", "mqtt_mock", ")", ":", "await", "hass", ".", "services", ".", "async_call", "(", "mqtt", ".", "DOMAIN", ",", "mqtt", ".", "SERVICE_PUBLISH", ",", "{", "mqtt", ".", "ATTR_TOPIC", ":", "\"test/topic\"", ",", "mqtt", ".", "ATTR_PAYLOAD", ":", "\"\"", ",", "mqtt", ".", "ATTR_QOS", ":", "\"2\"", ",", "mqtt", ".", "ATTR_RETAIN", ":", "\"no\"", ",", "}", ",", "blocking", "=", "True", ",", ")", "assert", "mqtt_mock", ".", "async_publish", ".", "called", "assert", "mqtt_mock", ".", "async_publish", ".", "call_args", "[", "0", "]", "[", "2", "]", "==", "2", "assert", "not", "mqtt_mock", ".", "async_publish", ".", "call_args", "[", "0", "]", "[", "3", "]" ]
[ 148, 0 ]
[ 166, 54 ]
python
en
['en', 'en', 'en']
True
test_validate_topic
()
Test topic name/filter validation.
Test topic name/filter validation.
def test_validate_topic(): """Test topic name/filter validation.""" # Invalid UTF-8, must not contain U+D800 to U+DFFF. with pytest.raises(vol.Invalid): mqtt.util.valid_topic("\ud800") with pytest.raises(vol.Invalid): mqtt.util.valid_topic("\udfff") # Topic MUST NOT be empty with pytest.raises(vol.Invalid): mqtt.util.valid_topic("") # Topic MUST NOT be longer than 65535 encoded bytes. with pytest.raises(vol.Invalid): mqtt.util.valid_topic("ü" * 32768) # UTF-8 MUST NOT include null character with pytest.raises(vol.Invalid): mqtt.util.valid_topic("bad\0one") # Topics "SHOULD NOT" include these special characters # (not MUST NOT, RFC2119). The receiver MAY close the connection. mqtt.util.valid_topic("\u0001") mqtt.util.valid_topic("\u001F") mqtt.util.valid_topic("\u009F") mqtt.util.valid_topic("\u009F") mqtt.util.valid_topic("\uffff")
[ "def", "test_validate_topic", "(", ")", ":", "# Invalid UTF-8, must not contain U+D800 to U+DFFF.", "with", "pytest", ".", "raises", "(", "vol", ".", "Invalid", ")", ":", "mqtt", ".", "util", ".", "valid_topic", "(", "\"\\ud800\"", ")", "with", "pytest", ".", "raises", "(", "vol", ".", "Invalid", ")", ":", "mqtt", ".", "util", ".", "valid_topic", "(", "\"\\udfff\"", ")", "# Topic MUST NOT be empty", "with", "pytest", ".", "raises", "(", "vol", ".", "Invalid", ")", ":", "mqtt", ".", "util", ".", "valid_topic", "(", "\"\"", ")", "# Topic MUST NOT be longer than 65535 encoded bytes.", "with", "pytest", ".", "raises", "(", "vol", ".", "Invalid", ")", ":", "mqtt", ".", "util", ".", "valid_topic", "(", "\"ü\" ", " ", "2768)", "", "# UTF-8 MUST NOT include null character", "with", "pytest", ".", "raises", "(", "vol", ".", "Invalid", ")", ":", "mqtt", ".", "util", ".", "valid_topic", "(", "\"bad\\0one\"", ")", "# Topics \"SHOULD NOT\" include these special characters", "# (not MUST NOT, RFC2119). The receiver MAY close the connection.", "mqtt", ".", "util", ".", "valid_topic", "(", "\"\\u0001\"", ")", "mqtt", ".", "util", ".", "valid_topic", "(", "\"\\u001F\"", ")", "mqtt", ".", "util", ".", "valid_topic", "(", "\"\\u009F\"", ")", "mqtt", ".", "util", ".", "valid_topic", "(", "\"\\u009F\"", ")", "mqtt", ".", "util", ".", "valid_topic", "(", "\"\\uffff\"", ")" ]
[ 169, 0 ]
[ 192, 35 ]
python
en
['en', 'en', 'en']
True
test_validate_subscribe_topic
()
Test invalid subscribe topics.
Test invalid subscribe topics.
def test_validate_subscribe_topic(): """Test invalid subscribe topics.""" mqtt.valid_subscribe_topic("#") mqtt.valid_subscribe_topic("sport/#") with pytest.raises(vol.Invalid): mqtt.valid_subscribe_topic("sport/#/") with pytest.raises(vol.Invalid): mqtt.valid_subscribe_topic("foo/bar#") with pytest.raises(vol.Invalid): mqtt.valid_subscribe_topic("foo/#/bar") mqtt.valid_subscribe_topic("+") mqtt.valid_subscribe_topic("+/tennis/#") with pytest.raises(vol.Invalid): mqtt.valid_subscribe_topic("sport+") with pytest.raises(vol.Invalid): mqtt.valid_subscribe_topic("sport+/") with pytest.raises(vol.Invalid): mqtt.valid_subscribe_topic("sport/+1") with pytest.raises(vol.Invalid): mqtt.valid_subscribe_topic("sport/+#") with pytest.raises(vol.Invalid): mqtt.valid_subscribe_topic("bad+topic") mqtt.valid_subscribe_topic("sport/+/player1") mqtt.valid_subscribe_topic("/finance") mqtt.valid_subscribe_topic("+/+") mqtt.valid_subscribe_topic("$SYS/#")
[ "def", "test_validate_subscribe_topic", "(", ")", ":", "mqtt", ".", "valid_subscribe_topic", "(", "\"#\"", ")", "mqtt", ".", "valid_subscribe_topic", "(", "\"sport/#\"", ")", "with", "pytest", ".", "raises", "(", "vol", ".", "Invalid", ")", ":", "mqtt", ".", "valid_subscribe_topic", "(", "\"sport/#/\"", ")", "with", "pytest", ".", "raises", "(", "vol", ".", "Invalid", ")", ":", "mqtt", ".", "valid_subscribe_topic", "(", "\"foo/bar#\"", ")", "with", "pytest", ".", "raises", "(", "vol", ".", "Invalid", ")", ":", "mqtt", ".", "valid_subscribe_topic", "(", "\"foo/#/bar\"", ")", "mqtt", ".", "valid_subscribe_topic", "(", "\"+\"", ")", "mqtt", ".", "valid_subscribe_topic", "(", "\"+/tennis/#\"", ")", "with", "pytest", ".", "raises", "(", "vol", ".", "Invalid", ")", ":", "mqtt", ".", "valid_subscribe_topic", "(", "\"sport+\"", ")", "with", "pytest", ".", "raises", "(", "vol", ".", "Invalid", ")", ":", "mqtt", ".", "valid_subscribe_topic", "(", "\"sport+/\"", ")", "with", "pytest", ".", "raises", "(", "vol", ".", "Invalid", ")", ":", "mqtt", ".", "valid_subscribe_topic", "(", "\"sport/+1\"", ")", "with", "pytest", ".", "raises", "(", "vol", ".", "Invalid", ")", ":", "mqtt", ".", "valid_subscribe_topic", "(", "\"sport/+#\"", ")", "with", "pytest", ".", "raises", "(", "vol", ".", "Invalid", ")", ":", "mqtt", ".", "valid_subscribe_topic", "(", "\"bad+topic\"", ")", "mqtt", ".", "valid_subscribe_topic", "(", "\"sport/+/player1\"", ")", "mqtt", ".", "valid_subscribe_topic", "(", "\"/finance\"", ")", "mqtt", ".", "valid_subscribe_topic", "(", "\"+/+\"", ")", "mqtt", ".", "valid_subscribe_topic", "(", "\"$SYS/#\"", ")" ]
[ 195, 0 ]
[ 221, 40 ]
python
en
['en', 'en', 'en']
True
test_validate_publish_topic
()
Test invalid publish topics.
Test invalid publish topics.
def test_validate_publish_topic(): """Test invalid publish topics.""" with pytest.raises(vol.Invalid): mqtt.valid_publish_topic("pub+") with pytest.raises(vol.Invalid): mqtt.valid_publish_topic("pub/+") with pytest.raises(vol.Invalid): mqtt.valid_publish_topic("1#") with pytest.raises(vol.Invalid): mqtt.valid_publish_topic("bad+topic") mqtt.valid_publish_topic("//") # Topic names beginning with $ SHOULD NOT be used, but can mqtt.valid_publish_topic("$SYS/")
[ "def", "test_validate_publish_topic", "(", ")", ":", "with", "pytest", ".", "raises", "(", "vol", ".", "Invalid", ")", ":", "mqtt", ".", "valid_publish_topic", "(", "\"pub+\"", ")", "with", "pytest", ".", "raises", "(", "vol", ".", "Invalid", ")", ":", "mqtt", ".", "valid_publish_topic", "(", "\"pub/+\"", ")", "with", "pytest", ".", "raises", "(", "vol", ".", "Invalid", ")", ":", "mqtt", ".", "valid_publish_topic", "(", "\"1#\"", ")", "with", "pytest", ".", "raises", "(", "vol", ".", "Invalid", ")", ":", "mqtt", ".", "valid_publish_topic", "(", "\"bad+topic\"", ")", "mqtt", ".", "valid_publish_topic", "(", "\"//\"", ")", "# Topic names beginning with $ SHOULD NOT be used, but can", "mqtt", ".", "valid_publish_topic", "(", "\"$SYS/\"", ")" ]
[ 224, 0 ]
[ 237, 37 ]
python
en
['en', 'mt', 'en']
True
test_entity_device_info_schema
()
Test MQTT entity device info validation.
Test MQTT entity device info validation.
def test_entity_device_info_schema(): """Test MQTT entity device info validation.""" # just identifier mqtt.MQTT_ENTITY_DEVICE_INFO_SCHEMA({"identifiers": ["abcd"]}) mqtt.MQTT_ENTITY_DEVICE_INFO_SCHEMA({"identifiers": "abcd"}) # just connection mqtt.MQTT_ENTITY_DEVICE_INFO_SCHEMA({"connections": [["mac", "02:5b:26:a8:dc:12"]]}) # full device info mqtt.MQTT_ENTITY_DEVICE_INFO_SCHEMA( { "identifiers": ["helloworld", "hello"], "connections": [["mac", "02:5b:26:a8:dc:12"], ["zigbee", "zigbee_id"]], "manufacturer": "Whatever", "name": "Beer", "model": "Glass", "sw_version": "0.1-beta", } ) # full device info with via_device mqtt.MQTT_ENTITY_DEVICE_INFO_SCHEMA( { "identifiers": ["helloworld", "hello"], "connections": [["mac", "02:5b:26:a8:dc:12"], ["zigbee", "zigbee_id"]], "manufacturer": "Whatever", "name": "Beer", "model": "Glass", "sw_version": "0.1-beta", "via_device": "test-hub", } ) # no identifiers with pytest.raises(vol.Invalid): mqtt.MQTT_ENTITY_DEVICE_INFO_SCHEMA( { "manufacturer": "Whatever", "name": "Beer", "model": "Glass", "sw_version": "0.1-beta", } ) # empty identifiers with pytest.raises(vol.Invalid): mqtt.MQTT_ENTITY_DEVICE_INFO_SCHEMA( {"identifiers": [], "connections": [], "name": "Beer"} )
[ "def", "test_entity_device_info_schema", "(", ")", ":", "# just identifier", "mqtt", ".", "MQTT_ENTITY_DEVICE_INFO_SCHEMA", "(", "{", "\"identifiers\"", ":", "[", "\"abcd\"", "]", "}", ")", "mqtt", ".", "MQTT_ENTITY_DEVICE_INFO_SCHEMA", "(", "{", "\"identifiers\"", ":", "\"abcd\"", "}", ")", "# just connection", "mqtt", ".", "MQTT_ENTITY_DEVICE_INFO_SCHEMA", "(", "{", "\"connections\"", ":", "[", "[", "\"mac\"", ",", "\"02:5b:26:a8:dc:12\"", "]", "]", "}", ")", "# full device info", "mqtt", ".", "MQTT_ENTITY_DEVICE_INFO_SCHEMA", "(", "{", "\"identifiers\"", ":", "[", "\"helloworld\"", ",", "\"hello\"", "]", ",", "\"connections\"", ":", "[", "[", "\"mac\"", ",", "\"02:5b:26:a8:dc:12\"", "]", ",", "[", "\"zigbee\"", ",", "\"zigbee_id\"", "]", "]", ",", "\"manufacturer\"", ":", "\"Whatever\"", ",", "\"name\"", ":", "\"Beer\"", ",", "\"model\"", ":", "\"Glass\"", ",", "\"sw_version\"", ":", "\"0.1-beta\"", ",", "}", ")", "# full device info with via_device", "mqtt", ".", "MQTT_ENTITY_DEVICE_INFO_SCHEMA", "(", "{", "\"identifiers\"", ":", "[", "\"helloworld\"", ",", "\"hello\"", "]", ",", "\"connections\"", ":", "[", "[", "\"mac\"", ",", "\"02:5b:26:a8:dc:12\"", "]", ",", "[", "\"zigbee\"", ",", "\"zigbee_id\"", "]", "]", ",", "\"manufacturer\"", ":", "\"Whatever\"", ",", "\"name\"", ":", "\"Beer\"", ",", "\"model\"", ":", "\"Glass\"", ",", "\"sw_version\"", ":", "\"0.1-beta\"", ",", "\"via_device\"", ":", "\"test-hub\"", ",", "}", ")", "# no identifiers", "with", "pytest", ".", "raises", "(", "vol", ".", "Invalid", ")", ":", "mqtt", ".", "MQTT_ENTITY_DEVICE_INFO_SCHEMA", "(", "{", "\"manufacturer\"", ":", "\"Whatever\"", ",", "\"name\"", ":", "\"Beer\"", ",", "\"model\"", ":", "\"Glass\"", ",", "\"sw_version\"", ":", "\"0.1-beta\"", ",", "}", ")", "# empty identifiers", "with", "pytest", ".", "raises", "(", "vol", ".", "Invalid", ")", ":", "mqtt", ".", "MQTT_ENTITY_DEVICE_INFO_SCHEMA", "(", "{", "\"identifiers\"", ":", "[", "]", ",", "\"connections\"", ":", "[", "]", ",", "\"name\"", ":", "\"Beer\"", "}", ")" ]
[ 240, 0 ]
[ 284, 9 ]
python
en
['en', 'ru-Latn', 'it']
False
test_receiving_non_utf8_message_gets_logged
( hass, mqtt_mock, calls, record_calls, caplog )
Test receiving a non utf8 encoded message.
Test receiving a non utf8 encoded message.
async def test_receiving_non_utf8_message_gets_logged( hass, mqtt_mock, calls, record_calls, caplog ): """Test receiving a non utf8 encoded message.""" await mqtt.async_subscribe(hass, "test-topic", record_calls) async_fire_mqtt_message(hass, "test-topic", b"\x9a") await hass.async_block_till_done() assert ( "Can't decode payload b'\\x9a' on test-topic with encoding utf-8" in caplog.text )
[ "async", "def", "test_receiving_non_utf8_message_gets_logged", "(", "hass", ",", "mqtt_mock", ",", "calls", ",", "record_calls", ",", "caplog", ")", ":", "await", "mqtt", ".", "async_subscribe", "(", "hass", ",", "\"test-topic\"", ",", "record_calls", ")", "async_fire_mqtt_message", "(", "hass", ",", "\"test-topic\"", ",", "b\"\\x9a\"", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "(", "\"Can't decode payload b'\\\\x9a' on test-topic with encoding utf-8\"", "in", "caplog", ".", "text", ")" ]
[ 287, 0 ]
[ 298, 5 ]
python
en
['en', 'en', 'en']
True
test_all_subscriptions_run_when_decode_fails
( hass, mqtt_mock, calls, record_calls )
Test all other subscriptions still run when decode fails for one.
Test all other subscriptions still run when decode fails for one.
async def test_all_subscriptions_run_when_decode_fails( hass, mqtt_mock, calls, record_calls ): """Test all other subscriptions still run when decode fails for one.""" await mqtt.async_subscribe(hass, "test-topic", record_calls, encoding="ascii") await mqtt.async_subscribe(hass, "test-topic", record_calls) async_fire_mqtt_message(hass, "test-topic", TEMP_CELSIUS) await hass.async_block_till_done() assert len(calls) == 1
[ "async", "def", "test_all_subscriptions_run_when_decode_fails", "(", "hass", ",", "mqtt_mock", ",", "calls", ",", "record_calls", ")", ":", "await", "mqtt", ".", "async_subscribe", "(", "hass", ",", "\"test-topic\"", ",", "record_calls", ",", "encoding", "=", "\"ascii\"", ")", "await", "mqtt", ".", "async_subscribe", "(", "hass", ",", "\"test-topic\"", ",", "record_calls", ")", "async_fire_mqtt_message", "(", "hass", ",", "\"test-topic\"", ",", "TEMP_CELSIUS", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "calls", ")", "==", "1" ]
[ 301, 0 ]
[ 311, 26 ]
python
en
['en', 'en', 'en']
True
test_subscribe_topic
(hass, mqtt_mock, calls, record_calls)
Test the subscription of a topic.
Test the subscription of a topic.
async def test_subscribe_topic(hass, mqtt_mock, calls, record_calls): """Test the subscription of a topic.""" unsub = await mqtt.async_subscribe(hass, "test-topic", record_calls) async_fire_mqtt_message(hass, "test-topic", "test-payload") await hass.async_block_till_done() assert len(calls) == 1 assert calls[0][0].topic == "test-topic" assert calls[0][0].payload == "test-payload" unsub() async_fire_mqtt_message(hass, "test-topic", "test-payload") await hass.async_block_till_done() assert len(calls) == 1
[ "async", "def", "test_subscribe_topic", "(", "hass", ",", "mqtt_mock", ",", "calls", ",", "record_calls", ")", ":", "unsub", "=", "await", "mqtt", ".", "async_subscribe", "(", "hass", ",", "\"test-topic\"", ",", "record_calls", ")", "async_fire_mqtt_message", "(", "hass", ",", "\"test-topic\"", ",", "\"test-payload\"", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "calls", ")", "==", "1", "assert", "calls", "[", "0", "]", "[", "0", "]", ".", "topic", "==", "\"test-topic\"", "assert", "calls", "[", "0", "]", "[", "0", "]", ".", "payload", "==", "\"test-payload\"", "unsub", "(", ")", "async_fire_mqtt_message", "(", "hass", ",", "\"test-topic\"", ",", "\"test-payload\"", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "calls", ")", "==", "1" ]
[ 314, 0 ]
[ 330, 26 ]
python
en
['en', 'en', 'en']
True
test_subscribe_deprecated
(hass, mqtt_mock)
Test the subscription of a topic using deprecated callback signature.
Test the subscription of a topic using deprecated callback signature.
async def test_subscribe_deprecated(hass, mqtt_mock): """Test the subscription of a topic using deprecated callback signature.""" calls = [] @callback def record_calls(topic, payload, qos): """Record calls.""" calls.append((topic, payload, qos)) unsub = await mqtt.async_subscribe(hass, "test-topic", record_calls) async_fire_mqtt_message(hass, "test-topic", "test-payload") await hass.async_block_till_done() assert len(calls) == 1 assert calls[0][0] == "test-topic" assert calls[0][1] == "test-payload" unsub() async_fire_mqtt_message(hass, "test-topic", "test-payload") await hass.async_block_till_done() assert len(calls) == 1
[ "async", "def", "test_subscribe_deprecated", "(", "hass", ",", "mqtt_mock", ")", ":", "calls", "=", "[", "]", "@", "callback", "def", "record_calls", "(", "topic", ",", "payload", ",", "qos", ")", ":", "\"\"\"Record calls.\"\"\"", "calls", ".", "append", "(", "(", "topic", ",", "payload", ",", "qos", ")", ")", "unsub", "=", "await", "mqtt", ".", "async_subscribe", "(", "hass", ",", "\"test-topic\"", ",", "record_calls", ")", "async_fire_mqtt_message", "(", "hass", ",", "\"test-topic\"", ",", "\"test-payload\"", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "calls", ")", "==", "1", "assert", "calls", "[", "0", "]", "[", "0", "]", "==", "\"test-topic\"", "assert", "calls", "[", "0", "]", "[", "1", "]", "==", "\"test-payload\"", "unsub", "(", ")", "async_fire_mqtt_message", "(", "hass", ",", "\"test-topic\"", ",", "\"test-payload\"", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "calls", ")", "==", "1" ]
[ 333, 0 ]
[ 356, 26 ]
python
en
['en', 'en', 'en']
True
test_subscribe_deprecated_async
(hass, mqtt_mock)
Test the subscription of a topic using deprecated callback signature.
Test the subscription of a topic using deprecated callback signature.
async def test_subscribe_deprecated_async(hass, mqtt_mock): """Test the subscription of a topic using deprecated callback signature.""" calls = [] async def record_calls(topic, payload, qos): """Record calls.""" calls.append((topic, payload, qos)) unsub = await mqtt.async_subscribe(hass, "test-topic", record_calls) async_fire_mqtt_message(hass, "test-topic", "test-payload") await hass.async_block_till_done() assert len(calls) == 1 assert calls[0][0] == "test-topic" assert calls[0][1] == "test-payload" unsub() async_fire_mqtt_message(hass, "test-topic", "test-payload") await hass.async_block_till_done() assert len(calls) == 1
[ "async", "def", "test_subscribe_deprecated_async", "(", "hass", ",", "mqtt_mock", ")", ":", "calls", "=", "[", "]", "async", "def", "record_calls", "(", "topic", ",", "payload", ",", "qos", ")", ":", "\"\"\"Record calls.\"\"\"", "calls", ".", "append", "(", "(", "topic", ",", "payload", ",", "qos", ")", ")", "unsub", "=", "await", "mqtt", ".", "async_subscribe", "(", "hass", ",", "\"test-topic\"", ",", "record_calls", ")", "async_fire_mqtt_message", "(", "hass", ",", "\"test-topic\"", ",", "\"test-payload\"", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "calls", ")", "==", "1", "assert", "calls", "[", "0", "]", "[", "0", "]", "==", "\"test-topic\"", "assert", "calls", "[", "0", "]", "[", "1", "]", "==", "\"test-payload\"", "unsub", "(", ")", "async_fire_mqtt_message", "(", "hass", ",", "\"test-topic\"", ",", "\"test-payload\"", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "calls", ")", "==", "1" ]
[ 359, 0 ]
[ 381, 26 ]
python
en
['en', 'en', 'en']
True
test_subscribe_topic_not_match
(hass, mqtt_mock, calls, record_calls)
Test if subscribed topic is not a match.
Test if subscribed topic is not a match.
async def test_subscribe_topic_not_match(hass, mqtt_mock, calls, record_calls): """Test if subscribed topic is not a match.""" await mqtt.async_subscribe(hass, "test-topic", record_calls) async_fire_mqtt_message(hass, "another-test-topic", "test-payload") await hass.async_block_till_done() assert len(calls) == 0
[ "async", "def", "test_subscribe_topic_not_match", "(", "hass", ",", "mqtt_mock", ",", "calls", ",", "record_calls", ")", ":", "await", "mqtt", ".", "async_subscribe", "(", "hass", ",", "\"test-topic\"", ",", "record_calls", ")", "async_fire_mqtt_message", "(", "hass", ",", "\"another-test-topic\"", ",", "\"test-payload\"", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "calls", ")", "==", "0" ]
[ 384, 0 ]
[ 391, 26 ]
python
en
['en', 'en', 'en']
True
test_subscribe_topic_level_wildcard
(hass, mqtt_mock, calls, record_calls)
Test the subscription of wildcard topics.
Test the subscription of wildcard topics.
async def test_subscribe_topic_level_wildcard(hass, mqtt_mock, calls, record_calls): """Test the subscription of wildcard topics.""" await mqtt.async_subscribe(hass, "test-topic/+/on", record_calls) async_fire_mqtt_message(hass, "test-topic/bier/on", "test-payload") await hass.async_block_till_done() assert len(calls) == 1 assert calls[0][0].topic == "test-topic/bier/on" assert calls[0][0].payload == "test-payload"
[ "async", "def", "test_subscribe_topic_level_wildcard", "(", "hass", ",", "mqtt_mock", ",", "calls", ",", "record_calls", ")", ":", "await", "mqtt", ".", "async_subscribe", "(", "hass", ",", "\"test-topic/+/on\"", ",", "record_calls", ")", "async_fire_mqtt_message", "(", "hass", ",", "\"test-topic/bier/on\"", ",", "\"test-payload\"", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "calls", ")", "==", "1", "assert", "calls", "[", "0", "]", "[", "0", "]", ".", "topic", "==", "\"test-topic/bier/on\"", "assert", "calls", "[", "0", "]", "[", "0", "]", ".", "payload", "==", "\"test-payload\"" ]
[ 394, 0 ]
[ 403, 48 ]
python
en
['en', 'en', 'en']
True
test_subscribe_topic_level_wildcard_no_subtree_match
( hass, mqtt_mock, calls, record_calls )
Test the subscription of wildcard topics.
Test the subscription of wildcard topics.
async def test_subscribe_topic_level_wildcard_no_subtree_match( hass, mqtt_mock, calls, record_calls ): """Test the subscription of wildcard topics.""" await mqtt.async_subscribe(hass, "test-topic/+/on", record_calls) async_fire_mqtt_message(hass, "test-topic/bier", "test-payload") await hass.async_block_till_done() assert len(calls) == 0
[ "async", "def", "test_subscribe_topic_level_wildcard_no_subtree_match", "(", "hass", ",", "mqtt_mock", ",", "calls", ",", "record_calls", ")", ":", "await", "mqtt", ".", "async_subscribe", "(", "hass", ",", "\"test-topic/+/on\"", ",", "record_calls", ")", "async_fire_mqtt_message", "(", "hass", ",", "\"test-topic/bier\"", ",", "\"test-payload\"", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "calls", ")", "==", "0" ]
[ 406, 0 ]
[ 415, 26 ]
python
en
['en', 'en', 'en']
True
test_subscribe_topic_level_wildcard_root_topic_no_subtree_match
( hass, mqtt_mock, calls, record_calls )
Test the subscription of wildcard topics.
Test the subscription of wildcard topics.
async def test_subscribe_topic_level_wildcard_root_topic_no_subtree_match( hass, mqtt_mock, calls, record_calls ): """Test the subscription of wildcard topics.""" await mqtt.async_subscribe(hass, "test-topic/#", record_calls) async_fire_mqtt_message(hass, "test-topic-123", "test-payload") await hass.async_block_till_done() assert len(calls) == 0
[ "async", "def", "test_subscribe_topic_level_wildcard_root_topic_no_subtree_match", "(", "hass", ",", "mqtt_mock", ",", "calls", ",", "record_calls", ")", ":", "await", "mqtt", ".", "async_subscribe", "(", "hass", ",", "\"test-topic/#\"", ",", "record_calls", ")", "async_fire_mqtt_message", "(", "hass", ",", "\"test-topic-123\"", ",", "\"test-payload\"", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "calls", ")", "==", "0" ]
[ 418, 0 ]
[ 427, 26 ]
python
en
['en', 'en', 'en']
True
test_subscribe_topic_subtree_wildcard_subtree_topic
( hass, mqtt_mock, calls, record_calls )
Test the subscription of wildcard topics.
Test the subscription of wildcard topics.
async def test_subscribe_topic_subtree_wildcard_subtree_topic( hass, mqtt_mock, calls, record_calls ): """Test the subscription of wildcard topics.""" await mqtt.async_subscribe(hass, "test-topic/#", record_calls) async_fire_mqtt_message(hass, "test-topic/bier/on", "test-payload") await hass.async_block_till_done() assert len(calls) == 1 assert calls[0][0].topic == "test-topic/bier/on" assert calls[0][0].payload == "test-payload"
[ "async", "def", "test_subscribe_topic_subtree_wildcard_subtree_topic", "(", "hass", ",", "mqtt_mock", ",", "calls", ",", "record_calls", ")", ":", "await", "mqtt", ".", "async_subscribe", "(", "hass", ",", "\"test-topic/#\"", ",", "record_calls", ")", "async_fire_mqtt_message", "(", "hass", ",", "\"test-topic/bier/on\"", ",", "\"test-payload\"", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "calls", ")", "==", "1", "assert", "calls", "[", "0", "]", "[", "0", "]", ".", "topic", "==", "\"test-topic/bier/on\"", "assert", "calls", "[", "0", "]", "[", "0", "]", ".", "payload", "==", "\"test-payload\"" ]
[ 430, 0 ]
[ 441, 48 ]
python
en
['en', 'en', 'en']
True
test_subscribe_topic_subtree_wildcard_root_topic
( hass, mqtt_mock, calls, record_calls )
Test the subscription of wildcard topics.
Test the subscription of wildcard topics.
async def test_subscribe_topic_subtree_wildcard_root_topic( hass, mqtt_mock, calls, record_calls ): """Test the subscription of wildcard topics.""" await mqtt.async_subscribe(hass, "test-topic/#", record_calls) async_fire_mqtt_message(hass, "test-topic", "test-payload") await hass.async_block_till_done() assert len(calls) == 1 assert calls[0][0].topic == "test-topic" assert calls[0][0].payload == "test-payload"
[ "async", "def", "test_subscribe_topic_subtree_wildcard_root_topic", "(", "hass", ",", "mqtt_mock", ",", "calls", ",", "record_calls", ")", ":", "await", "mqtt", ".", "async_subscribe", "(", "hass", ",", "\"test-topic/#\"", ",", "record_calls", ")", "async_fire_mqtt_message", "(", "hass", ",", "\"test-topic\"", ",", "\"test-payload\"", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "calls", ")", "==", "1", "assert", "calls", "[", "0", "]", "[", "0", "]", ".", "topic", "==", "\"test-topic\"", "assert", "calls", "[", "0", "]", "[", "0", "]", ".", "payload", "==", "\"test-payload\"" ]
[ 444, 0 ]
[ 455, 48 ]
python
en
['en', 'en', 'en']
True
test_subscribe_topic_subtree_wildcard_no_match
( hass, mqtt_mock, calls, record_calls )
Test the subscription of wildcard topics.
Test the subscription of wildcard topics.
async def test_subscribe_topic_subtree_wildcard_no_match( hass, mqtt_mock, calls, record_calls ): """Test the subscription of wildcard topics.""" await mqtt.async_subscribe(hass, "test-topic/#", record_calls) async_fire_mqtt_message(hass, "another-test-topic", "test-payload") await hass.async_block_till_done() assert len(calls) == 0
[ "async", "def", "test_subscribe_topic_subtree_wildcard_no_match", "(", "hass", ",", "mqtt_mock", ",", "calls", ",", "record_calls", ")", ":", "await", "mqtt", ".", "async_subscribe", "(", "hass", ",", "\"test-topic/#\"", ",", "record_calls", ")", "async_fire_mqtt_message", "(", "hass", ",", "\"another-test-topic\"", ",", "\"test-payload\"", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "calls", ")", "==", "0" ]
[ 458, 0 ]
[ 467, 26 ]
python
en
['en', 'en', 'en']
True
test_subscribe_topic_level_wildcard_and_wildcard_root_topic
( hass, mqtt_mock, calls, record_calls )
Test the subscription of wildcard topics.
Test the subscription of wildcard topics.
async def test_subscribe_topic_level_wildcard_and_wildcard_root_topic( hass, mqtt_mock, calls, record_calls ): """Test the subscription of wildcard topics.""" await mqtt.async_subscribe(hass, "+/test-topic/#", record_calls) async_fire_mqtt_message(hass, "hi/test-topic", "test-payload") await hass.async_block_till_done() assert len(calls) == 1 assert calls[0][0].topic == "hi/test-topic" assert calls[0][0].payload == "test-payload"
[ "async", "def", "test_subscribe_topic_level_wildcard_and_wildcard_root_topic", "(", "hass", ",", "mqtt_mock", ",", "calls", ",", "record_calls", ")", ":", "await", "mqtt", ".", "async_subscribe", "(", "hass", ",", "\"+/test-topic/#\"", ",", "record_calls", ")", "async_fire_mqtt_message", "(", "hass", ",", "\"hi/test-topic\"", ",", "\"test-payload\"", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "calls", ")", "==", "1", "assert", "calls", "[", "0", "]", "[", "0", "]", ".", "topic", "==", "\"hi/test-topic\"", "assert", "calls", "[", "0", "]", "[", "0", "]", ".", "payload", "==", "\"test-payload\"" ]
[ 470, 0 ]
[ 481, 48 ]
python
en
['en', 'en', 'en']
True
test_subscribe_topic_level_wildcard_and_wildcard_subtree_topic
( hass, mqtt_mock, calls, record_calls )
Test the subscription of wildcard topics.
Test the subscription of wildcard topics.
async def test_subscribe_topic_level_wildcard_and_wildcard_subtree_topic( hass, mqtt_mock, calls, record_calls ): """Test the subscription of wildcard topics.""" await mqtt.async_subscribe(hass, "+/test-topic/#", record_calls) async_fire_mqtt_message(hass, "hi/test-topic/here-iam", "test-payload") await hass.async_block_till_done() assert len(calls) == 1 assert calls[0][0].topic == "hi/test-topic/here-iam" assert calls[0][0].payload == "test-payload"
[ "async", "def", "test_subscribe_topic_level_wildcard_and_wildcard_subtree_topic", "(", "hass", ",", "mqtt_mock", ",", "calls", ",", "record_calls", ")", ":", "await", "mqtt", ".", "async_subscribe", "(", "hass", ",", "\"+/test-topic/#\"", ",", "record_calls", ")", "async_fire_mqtt_message", "(", "hass", ",", "\"hi/test-topic/here-iam\"", ",", "\"test-payload\"", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "calls", ")", "==", "1", "assert", "calls", "[", "0", "]", "[", "0", "]", ".", "topic", "==", "\"hi/test-topic/here-iam\"", "assert", "calls", "[", "0", "]", "[", "0", "]", ".", "payload", "==", "\"test-payload\"" ]
[ 484, 0 ]
[ 495, 48 ]
python
en
['en', 'en', 'en']
True
test_subscribe_topic_level_wildcard_and_wildcard_level_no_match
( hass, mqtt_mock, calls, record_calls )
Test the subscription of wildcard topics.
Test the subscription of wildcard topics.
async def test_subscribe_topic_level_wildcard_and_wildcard_level_no_match( hass, mqtt_mock, calls, record_calls ): """Test the subscription of wildcard topics.""" await mqtt.async_subscribe(hass, "+/test-topic/#", record_calls) async_fire_mqtt_message(hass, "hi/here-iam/test-topic", "test-payload") await hass.async_block_till_done() assert len(calls) == 0
[ "async", "def", "test_subscribe_topic_level_wildcard_and_wildcard_level_no_match", "(", "hass", ",", "mqtt_mock", ",", "calls", ",", "record_calls", ")", ":", "await", "mqtt", ".", "async_subscribe", "(", "hass", ",", "\"+/test-topic/#\"", ",", "record_calls", ")", "async_fire_mqtt_message", "(", "hass", ",", "\"hi/here-iam/test-topic\"", ",", "\"test-payload\"", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "calls", ")", "==", "0" ]
[ 498, 0 ]
[ 507, 26 ]
python
en
['en', 'en', 'en']
True
test_subscribe_topic_level_wildcard_and_wildcard_no_match
( hass, mqtt_mock, calls, record_calls )
Test the subscription of wildcard topics.
Test the subscription of wildcard topics.
async def test_subscribe_topic_level_wildcard_and_wildcard_no_match( hass, mqtt_mock, calls, record_calls ): """Test the subscription of wildcard topics.""" await mqtt.async_subscribe(hass, "+/test-topic/#", record_calls) async_fire_mqtt_message(hass, "hi/another-test-topic", "test-payload") await hass.async_block_till_done() assert len(calls) == 0
[ "async", "def", "test_subscribe_topic_level_wildcard_and_wildcard_no_match", "(", "hass", ",", "mqtt_mock", ",", "calls", ",", "record_calls", ")", ":", "await", "mqtt", ".", "async_subscribe", "(", "hass", ",", "\"+/test-topic/#\"", ",", "record_calls", ")", "async_fire_mqtt_message", "(", "hass", ",", "\"hi/another-test-topic\"", ",", "\"test-payload\"", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "calls", ")", "==", "0" ]
[ 510, 0 ]
[ 519, 26 ]
python
en
['en', 'en', 'en']
True
test_subscribe_topic_sys_root
(hass, mqtt_mock, calls, record_calls)
Test the subscription of $ root topics.
Test the subscription of $ root topics.
async def test_subscribe_topic_sys_root(hass, mqtt_mock, calls, record_calls): """Test the subscription of $ root topics.""" await mqtt.async_subscribe(hass, "$test-topic/subtree/on", record_calls) async_fire_mqtt_message(hass, "$test-topic/subtree/on", "test-payload") await hass.async_block_till_done() assert len(calls) == 1 assert calls[0][0].topic == "$test-topic/subtree/on" assert calls[0][0].payload == "test-payload"
[ "async", "def", "test_subscribe_topic_sys_root", "(", "hass", ",", "mqtt_mock", ",", "calls", ",", "record_calls", ")", ":", "await", "mqtt", ".", "async_subscribe", "(", "hass", ",", "\"$test-topic/subtree/on\"", ",", "record_calls", ")", "async_fire_mqtt_message", "(", "hass", ",", "\"$test-topic/subtree/on\"", ",", "\"test-payload\"", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "calls", ")", "==", "1", "assert", "calls", "[", "0", "]", "[", "0", "]", ".", "topic", "==", "\"$test-topic/subtree/on\"", "assert", "calls", "[", "0", "]", "[", "0", "]", ".", "payload", "==", "\"test-payload\"" ]
[ 522, 0 ]
[ 531, 48 ]
python
en
['en', 'en', 'en']
True
test_subscribe_topic_sys_root_and_wildcard_topic
( hass, mqtt_mock, calls, record_calls )
Test the subscription of $ root and wildcard topics.
Test the subscription of $ root and wildcard topics.
async def test_subscribe_topic_sys_root_and_wildcard_topic( hass, mqtt_mock, calls, record_calls ): """Test the subscription of $ root and wildcard topics.""" await mqtt.async_subscribe(hass, "$test-topic/#", record_calls) async_fire_mqtt_message(hass, "$test-topic/some-topic", "test-payload") await hass.async_block_till_done() assert len(calls) == 1 assert calls[0][0].topic == "$test-topic/some-topic" assert calls[0][0].payload == "test-payload"
[ "async", "def", "test_subscribe_topic_sys_root_and_wildcard_topic", "(", "hass", ",", "mqtt_mock", ",", "calls", ",", "record_calls", ")", ":", "await", "mqtt", ".", "async_subscribe", "(", "hass", ",", "\"$test-topic/#\"", ",", "record_calls", ")", "async_fire_mqtt_message", "(", "hass", ",", "\"$test-topic/some-topic\"", ",", "\"test-payload\"", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "calls", ")", "==", "1", "assert", "calls", "[", "0", "]", "[", "0", "]", ".", "topic", "==", "\"$test-topic/some-topic\"", "assert", "calls", "[", "0", "]", "[", "0", "]", ".", "payload", "==", "\"test-payload\"" ]
[ 534, 0 ]
[ 545, 48 ]
python
en
['en', 'en', 'en']
True
test_subscribe_topic_sys_root_and_wildcard_subtree_topic
( hass, mqtt_mock, calls, record_calls )
Test the subscription of $ root and wildcard subtree topics.
Test the subscription of $ root and wildcard subtree topics.
async def test_subscribe_topic_sys_root_and_wildcard_subtree_topic( hass, mqtt_mock, calls, record_calls ): """Test the subscription of $ root and wildcard subtree topics.""" await mqtt.async_subscribe(hass, "$test-topic/subtree/#", record_calls) async_fire_mqtt_message(hass, "$test-topic/subtree/some-topic", "test-payload") await hass.async_block_till_done() assert len(calls) == 1 assert calls[0][0].topic == "$test-topic/subtree/some-topic" assert calls[0][0].payload == "test-payload"
[ "async", "def", "test_subscribe_topic_sys_root_and_wildcard_subtree_topic", "(", "hass", ",", "mqtt_mock", ",", "calls", ",", "record_calls", ")", ":", "await", "mqtt", ".", "async_subscribe", "(", "hass", ",", "\"$test-topic/subtree/#\"", ",", "record_calls", ")", "async_fire_mqtt_message", "(", "hass", ",", "\"$test-topic/subtree/some-topic\"", ",", "\"test-payload\"", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "calls", ")", "==", "1", "assert", "calls", "[", "0", "]", "[", "0", "]", ".", "topic", "==", "\"$test-topic/subtree/some-topic\"", "assert", "calls", "[", "0", "]", "[", "0", "]", ".", "payload", "==", "\"test-payload\"" ]
[ 548, 0 ]
[ 559, 48 ]
python
en
['en', 'en', 'en']
True
test_subscribe_special_characters
(hass, mqtt_mock, calls, record_calls)
Test the subscription to topics with special characters.
Test the subscription to topics with special characters.
async def test_subscribe_special_characters(hass, mqtt_mock, calls, record_calls): """Test the subscription to topics with special characters.""" topic = "/test-topic/$(.)[^]{-}" payload = "p4y.l[]a|> ?" await mqtt.async_subscribe(hass, topic, record_calls) async_fire_mqtt_message(hass, topic, payload) await hass.async_block_till_done() assert len(calls) == 1 assert calls[0][0].topic == topic assert calls[0][0].payload == payload
[ "async", "def", "test_subscribe_special_characters", "(", "hass", ",", "mqtt_mock", ",", "calls", ",", "record_calls", ")", ":", "topic", "=", "\"/test-topic/$(.)[^]{-}\"", "payload", "=", "\"p4y.l[]a|> ?\"", "await", "mqtt", ".", "async_subscribe", "(", "hass", ",", "topic", ",", "record_calls", ")", "async_fire_mqtt_message", "(", "hass", ",", "topic", ",", "payload", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "calls", ")", "==", "1", "assert", "calls", "[", "0", "]", "[", "0", "]", ".", "topic", "==", "topic", "assert", "calls", "[", "0", "]", "[", "0", "]", ".", "payload", "==", "payload" ]
[ 562, 0 ]
[ 573, 41 ]
python
en
['en', 'en', 'en']
True
test_subscribe_same_topic
(hass, mqtt_client_mock, mqtt_mock)
Test subscring to same topic twice and simulate retained messages. When subscribing to the same topic again, SUBSCRIBE must be sent to the broker again for it to resend any retained messages.
Test subscring to same topic twice and simulate retained messages.
async def test_subscribe_same_topic(hass, mqtt_client_mock, mqtt_mock): """ Test subscring to same topic twice and simulate retained messages. When subscribing to the same topic again, SUBSCRIBE must be sent to the broker again for it to resend any retained messages. """ # Fake that the client is connected mqtt_mock().connected = True calls_a = MagicMock() await mqtt.async_subscribe(hass, "test/state", calls_a) async_fire_mqtt_message( hass, "test/state", "online" ) # Simulate a (retained) message await hass.async_block_till_done() assert calls_a.called mqtt_client_mock.subscribe.assert_called() calls_a.reset_mock() mqtt_client_mock.reset_mock() calls_b = MagicMock() await mqtt.async_subscribe(hass, "test/state", calls_b) async_fire_mqtt_message( hass, "test/state", "online" ) # Simulate a (retained) message await hass.async_block_till_done() assert calls_a.called assert calls_b.called mqtt_client_mock.subscribe.assert_called()
[ "async", "def", "test_subscribe_same_topic", "(", "hass", ",", "mqtt_client_mock", ",", "mqtt_mock", ")", ":", "# Fake that the client is connected", "mqtt_mock", "(", ")", ".", "connected", "=", "True", "calls_a", "=", "MagicMock", "(", ")", "await", "mqtt", ".", "async_subscribe", "(", "hass", ",", "\"test/state\"", ",", "calls_a", ")", "async_fire_mqtt_message", "(", "hass", ",", "\"test/state\"", ",", "\"online\"", ")", "# Simulate a (retained) message", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "calls_a", ".", "called", "mqtt_client_mock", ".", "subscribe", ".", "assert_called", "(", ")", "calls_a", ".", "reset_mock", "(", ")", "mqtt_client_mock", ".", "reset_mock", "(", ")", "calls_b", "=", "MagicMock", "(", ")", "await", "mqtt", ".", "async_subscribe", "(", "hass", ",", "\"test/state\"", ",", "calls_b", ")", "async_fire_mqtt_message", "(", "hass", ",", "\"test/state\"", ",", "\"online\"", ")", "# Simulate a (retained) message", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "calls_a", ".", "called", "assert", "calls_b", ".", "called", "mqtt_client_mock", ".", "subscribe", ".", "assert_called", "(", ")" ]
[ 576, 0 ]
[ 606, 46 ]
python
en
['en', 'error', 'th']
False
test_not_calling_unsubscribe_with_active_subscribers
( hass, mqtt_client_mock, mqtt_mock )
Test not calling unsubscribe() when other subscribers are active.
Test not calling unsubscribe() when other subscribers are active.
async def test_not_calling_unsubscribe_with_active_subscribers( hass, mqtt_client_mock, mqtt_mock ): """Test not calling unsubscribe() when other subscribers are active.""" # Fake that the client is connected mqtt_mock().connected = True unsub = await mqtt.async_subscribe(hass, "test/state", None) await mqtt.async_subscribe(hass, "test/state", None) await hass.async_block_till_done() assert mqtt_client_mock.subscribe.called unsub() await hass.async_block_till_done() assert not mqtt_client_mock.unsubscribe.called
[ "async", "def", "test_not_calling_unsubscribe_with_active_subscribers", "(", "hass", ",", "mqtt_client_mock", ",", "mqtt_mock", ")", ":", "# Fake that the client is connected", "mqtt_mock", "(", ")", ".", "connected", "=", "True", "unsub", "=", "await", "mqtt", ".", "async_subscribe", "(", "hass", ",", "\"test/state\"", ",", "None", ")", "await", "mqtt", ".", "async_subscribe", "(", "hass", ",", "\"test/state\"", ",", "None", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "mqtt_client_mock", ".", "subscribe", ".", "called", "unsub", "(", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "not", "mqtt_client_mock", ".", "unsubscribe", ".", "called" ]
[ 609, 0 ]
[ 623, 50 ]
python
en
['en', 'en', 'en']
True
test_restore_subscriptions_on_reconnect
(hass, mqtt_client_mock, mqtt_mock)
Test subscriptions are restored on reconnect.
Test subscriptions are restored on reconnect.
async def test_restore_subscriptions_on_reconnect(hass, mqtt_client_mock, mqtt_mock): """Test subscriptions are restored on reconnect.""" # Fake that the client is connected mqtt_mock().connected = True await mqtt.async_subscribe(hass, "test/state", None) await hass.async_block_till_done() assert mqtt_client_mock.subscribe.call_count == 1 mqtt_mock._mqtt_on_disconnect(None, None, 0) mqtt_mock._mqtt_on_connect(None, None, None, 0) await hass.async_block_till_done() assert mqtt_client_mock.subscribe.call_count == 2
[ "async", "def", "test_restore_subscriptions_on_reconnect", "(", "hass", ",", "mqtt_client_mock", ",", "mqtt_mock", ")", ":", "# Fake that the client is connected", "mqtt_mock", "(", ")", ".", "connected", "=", "True", "await", "mqtt", ".", "async_subscribe", "(", "hass", ",", "\"test/state\"", ",", "None", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "mqtt_client_mock", ".", "subscribe", ".", "call_count", "==", "1", "mqtt_mock", ".", "_mqtt_on_disconnect", "(", "None", ",", "None", ",", "0", ")", "mqtt_mock", ".", "_mqtt_on_connect", "(", "None", ",", "None", ",", "None", ",", "0", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "mqtt_client_mock", ".", "subscribe", ".", "call_count", "==", "2" ]
[ 630, 0 ]
[ 642, 53 ]
python
en
['en', 'en', 'en']
True
test_restore_all_active_subscriptions_on_reconnect
( hass, mqtt_client_mock, mqtt_mock )
Test active subscriptions are restored correctly on reconnect.
Test active subscriptions are restored correctly on reconnect.
async def test_restore_all_active_subscriptions_on_reconnect( hass, mqtt_client_mock, mqtt_mock ): """Test active subscriptions are restored correctly on reconnect.""" # Fake that the client is connected mqtt_mock().connected = True unsub = await mqtt.async_subscribe(hass, "test/state", None, qos=2) await mqtt.async_subscribe(hass, "test/state", None) await mqtt.async_subscribe(hass, "test/state", None, qos=1) await hass.async_block_till_done() expected = [ call("test/state", 2), call("test/state", 0), call("test/state", 1), ] assert mqtt_client_mock.subscribe.mock_calls == expected unsub() await hass.async_block_till_done() assert mqtt_client_mock.unsubscribe.call_count == 0 mqtt_mock._mqtt_on_disconnect(None, None, 0) mqtt_mock._mqtt_on_connect(None, None, None, 0) await hass.async_block_till_done() expected.append(call("test/state", 1)) assert mqtt_client_mock.subscribe.mock_calls == expected
[ "async", "def", "test_restore_all_active_subscriptions_on_reconnect", "(", "hass", ",", "mqtt_client_mock", ",", "mqtt_mock", ")", ":", "# Fake that the client is connected", "mqtt_mock", "(", ")", ".", "connected", "=", "True", "unsub", "=", "await", "mqtt", ".", "async_subscribe", "(", "hass", ",", "\"test/state\"", ",", "None", ",", "qos", "=", "2", ")", "await", "mqtt", ".", "async_subscribe", "(", "hass", ",", "\"test/state\"", ",", "None", ")", "await", "mqtt", ".", "async_subscribe", "(", "hass", ",", "\"test/state\"", ",", "None", ",", "qos", "=", "1", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "expected", "=", "[", "call", "(", "\"test/state\"", ",", "2", ")", ",", "call", "(", "\"test/state\"", ",", "0", ")", ",", "call", "(", "\"test/state\"", ",", "1", ")", ",", "]", "assert", "mqtt_client_mock", ".", "subscribe", ".", "mock_calls", "==", "expected", "unsub", "(", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "mqtt_client_mock", ".", "unsubscribe", ".", "call_count", "==", "0", "mqtt_mock", ".", "_mqtt_on_disconnect", "(", "None", ",", "None", ",", "0", ")", "mqtt_mock", ".", "_mqtt_on_connect", "(", "None", ",", "None", ",", "None", ",", "0", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "expected", ".", "append", "(", "call", "(", "\"test/state\"", ",", "1", ")", ")", "assert", "mqtt_client_mock", ".", "subscribe", ".", "mock_calls", "==", "expected" ]
[ 649, 0 ]
[ 677, 60 ]
python
en
['en', 'en', 'en']
True
test_setup_logs_error_if_no_connect_broker
(hass, caplog)
Test for setup failure if connection to broker is missing.
Test for setup failure if connection to broker is missing.
async def test_setup_logs_error_if_no_connect_broker(hass, caplog): """Test for setup failure if connection to broker is missing.""" entry = MockConfigEntry(domain=mqtt.DOMAIN, data={mqtt.CONF_BROKER: "test-broker"}) with patch("paho.mqtt.client.Client") as mock_client: mock_client().connect = lambda *args: 1 assert await mqtt.async_setup_entry(hass, entry) assert "Failed to connect to MQTT server:" in caplog.text
[ "async", "def", "test_setup_logs_error_if_no_connect_broker", "(", "hass", ",", "caplog", ")", ":", "entry", "=", "MockConfigEntry", "(", "domain", "=", "mqtt", ".", "DOMAIN", ",", "data", "=", "{", "mqtt", ".", "CONF_BROKER", ":", "\"test-broker\"", "}", ")", "with", "patch", "(", "\"paho.mqtt.client.Client\"", ")", "as", "mock_client", ":", "mock_client", "(", ")", ".", "connect", "=", "lambda", "*", "args", ":", "1", "assert", "await", "mqtt", ".", "async_setup_entry", "(", "hass", ",", "entry", ")", "assert", "\"Failed to connect to MQTT server:\"", "in", "caplog", ".", "text" ]
[ 680, 0 ]
[ 687, 65 ]
python
en
['en', 'en', 'en']
True
test_setup_raises_ConfigEntryNotReady_if_no_connect_broker
(hass, caplog)
Test for setup failure if connection to broker is missing.
Test for setup failure if connection to broker is missing.
async def test_setup_raises_ConfigEntryNotReady_if_no_connect_broker(hass, caplog): """Test for setup failure if connection to broker is missing.""" entry = MockConfigEntry(domain=mqtt.DOMAIN, data={mqtt.CONF_BROKER: "test-broker"}) with patch("paho.mqtt.client.Client") as mock_client: mock_client().connect = MagicMock(side_effect=OSError("Connection error")) assert await mqtt.async_setup_entry(hass, entry) assert "Failed to connect to MQTT server due to exception:" in caplog.text
[ "async", "def", "test_setup_raises_ConfigEntryNotReady_if_no_connect_broker", "(", "hass", ",", "caplog", ")", ":", "entry", "=", "MockConfigEntry", "(", "domain", "=", "mqtt", ".", "DOMAIN", ",", "data", "=", "{", "mqtt", ".", "CONF_BROKER", ":", "\"test-broker\"", "}", ")", "with", "patch", "(", "\"paho.mqtt.client.Client\"", ")", "as", "mock_client", ":", "mock_client", "(", ")", ".", "connect", "=", "MagicMock", "(", "side_effect", "=", "OSError", "(", "\"Connection error\"", ")", ")", "assert", "await", "mqtt", ".", "async_setup_entry", "(", "hass", ",", "entry", ")", "assert", "\"Failed to connect to MQTT server due to exception:\"", "in", "caplog", ".", "text" ]
[ 690, 0 ]
[ 697, 82 ]
python
en
['en', 'en', 'en']
True
test_setup_uses_certificate_on_certificate_set_to_auto
(hass)
Test setup uses bundled certs when certificate is set to auto.
Test setup uses bundled certs when certificate is set to auto.
async def test_setup_uses_certificate_on_certificate_set_to_auto(hass): """Test setup uses bundled certs when certificate is set to auto.""" calls = [] def mock_tls_set(certificate, certfile=None, keyfile=None, tls_version=None): calls.append((certificate, certfile, keyfile, tls_version)) with patch("paho.mqtt.client.Client") as mock_client: mock_client().tls_set = mock_tls_set entry = MockConfigEntry( domain=mqtt.DOMAIN, data={mqtt.CONF_BROKER: "test-broker", "certificate": "auto"}, ) assert await mqtt.async_setup_entry(hass, entry) assert calls import certifi expectedCertificate = certifi.where() # assert mock_mqtt.mock_calls[0][1][2]["certificate"] == expectedCertificate assert calls[0][0] == expectedCertificate
[ "async", "def", "test_setup_uses_certificate_on_certificate_set_to_auto", "(", "hass", ")", ":", "calls", "=", "[", "]", "def", "mock_tls_set", "(", "certificate", ",", "certfile", "=", "None", ",", "keyfile", "=", "None", ",", "tls_version", "=", "None", ")", ":", "calls", ".", "append", "(", "(", "certificate", ",", "certfile", ",", "keyfile", ",", "tls_version", ")", ")", "with", "patch", "(", "\"paho.mqtt.client.Client\"", ")", "as", "mock_client", ":", "mock_client", "(", ")", ".", "tls_set", "=", "mock_tls_set", "entry", "=", "MockConfigEntry", "(", "domain", "=", "mqtt", ".", "DOMAIN", ",", "data", "=", "{", "mqtt", ".", "CONF_BROKER", ":", "\"test-broker\"", ",", "\"certificate\"", ":", "\"auto\"", "}", ",", ")", "assert", "await", "mqtt", ".", "async_setup_entry", "(", "hass", ",", "entry", ")", "assert", "calls", "import", "certifi", "expectedCertificate", "=", "certifi", ".", "where", "(", ")", "# assert mock_mqtt.mock_calls[0][1][2][\"certificate\"] == expectedCertificate", "assert", "calls", "[", "0", "]", "[", "0", "]", "==", "expectedCertificate" ]
[ 700, 0 ]
[ 722, 49 ]
python
en
['en', 'en', 'en']
True
test_setup_without_tls_config_uses_tlsv1_under_python36
(hass)
Test setup defaults to TLSv1 under python3.6.
Test setup defaults to TLSv1 under python3.6.
async def test_setup_without_tls_config_uses_tlsv1_under_python36(hass): """Test setup defaults to TLSv1 under python3.6.""" calls = [] def mock_tls_set(certificate, certfile=None, keyfile=None, tls_version=None): calls.append((certificate, certfile, keyfile, tls_version)) with patch("paho.mqtt.client.Client") as mock_client: mock_client().tls_set = mock_tls_set entry = MockConfigEntry( domain=mqtt.DOMAIN, data={"certificate": "auto", mqtt.CONF_BROKER: "test-broker"}, ) assert await mqtt.async_setup_entry(hass, entry) assert calls import sys if sys.hexversion >= 0x03060000: expectedTlsVersion = ssl.PROTOCOL_TLS # pylint: disable=no-member else: expectedTlsVersion = ssl.PROTOCOL_TLSv1 assert calls[0][3] == expectedTlsVersion
[ "async", "def", "test_setup_without_tls_config_uses_tlsv1_under_python36", "(", "hass", ")", ":", "calls", "=", "[", "]", "def", "mock_tls_set", "(", "certificate", ",", "certfile", "=", "None", ",", "keyfile", "=", "None", ",", "tls_version", "=", "None", ")", ":", "calls", ".", "append", "(", "(", "certificate", ",", "certfile", ",", "keyfile", ",", "tls_version", ")", ")", "with", "patch", "(", "\"paho.mqtt.client.Client\"", ")", "as", "mock_client", ":", "mock_client", "(", ")", ".", "tls_set", "=", "mock_tls_set", "entry", "=", "MockConfigEntry", "(", "domain", "=", "mqtt", ".", "DOMAIN", ",", "data", "=", "{", "\"certificate\"", ":", "\"auto\"", ",", "mqtt", ".", "CONF_BROKER", ":", "\"test-broker\"", "}", ",", ")", "assert", "await", "mqtt", ".", "async_setup_entry", "(", "hass", ",", "entry", ")", "assert", "calls", "import", "sys", "if", "sys", ".", "hexversion", ">=", "0x03060000", ":", "expectedTlsVersion", "=", "ssl", ".", "PROTOCOL_TLS", "# pylint: disable=no-member", "else", ":", "expectedTlsVersion", "=", "ssl", ".", "PROTOCOL_TLSv1", "assert", "calls", "[", "0", "]", "[", "3", "]", "==", "expectedTlsVersion" ]
[ 725, 0 ]
[ 750, 48 ]
python
en
['en', 'da', 'en']
True
test_custom_birth_message
(hass, mqtt_client_mock, mqtt_mock)
Test sending birth message.
Test sending birth message.
async def test_custom_birth_message(hass, mqtt_client_mock, mqtt_mock): """Test sending birth message.""" birth = asyncio.Event() async def wait_birth(topic, payload, qos): """Handle birth message.""" birth.set() with patch("homeassistant.components.mqtt.DISCOVERY_COOLDOWN", 0.1): await mqtt.async_subscribe(hass, "birth", wait_birth) mqtt_mock._mqtt_on_connect(None, None, 0, 0) await hass.async_block_till_done() await birth.wait() mqtt_client_mock.publish.assert_called_with("birth", "birth", 0, False)
[ "async", "def", "test_custom_birth_message", "(", "hass", ",", "mqtt_client_mock", ",", "mqtt_mock", ")", ":", "birth", "=", "asyncio", ".", "Event", "(", ")", "async", "def", "wait_birth", "(", "topic", ",", "payload", ",", "qos", ")", ":", "\"\"\"Handle birth message.\"\"\"", "birth", ".", "set", "(", ")", "with", "patch", "(", "\"homeassistant.components.mqtt.DISCOVERY_COOLDOWN\"", ",", "0.1", ")", ":", "await", "mqtt", ".", "async_subscribe", "(", "hass", ",", "\"birth\"", ",", "wait_birth", ")", "mqtt_mock", ".", "_mqtt_on_connect", "(", "None", ",", "None", ",", "0", ",", "0", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "await", "birth", ".", "wait", "(", ")", "mqtt_client_mock", ".", "publish", ".", "assert_called_with", "(", "\"birth\"", ",", "\"birth\"", ",", "0", ",", "False", ")" ]
[ 765, 0 ]
[ 778, 79 ]
python
en
['en', 'de', 'en']
True
test_default_birth_message
(hass, mqtt_client_mock, mqtt_mock)
Test sending birth message.
Test sending birth message.
async def test_default_birth_message(hass, mqtt_client_mock, mqtt_mock): """Test sending birth message.""" birth = asyncio.Event() async def wait_birth(topic, payload, qos): """Handle birth message.""" birth.set() with patch("homeassistant.components.mqtt.DISCOVERY_COOLDOWN", 0.1): await mqtt.async_subscribe(hass, "homeassistant/status", wait_birth) mqtt_mock._mqtt_on_connect(None, None, 0, 0) await hass.async_block_till_done() await birth.wait() mqtt_client_mock.publish.assert_called_with( "homeassistant/status", "online", 0, False )
[ "async", "def", "test_default_birth_message", "(", "hass", ",", "mqtt_client_mock", ",", "mqtt_mock", ")", ":", "birth", "=", "asyncio", ".", "Event", "(", ")", "async", "def", "wait_birth", "(", "topic", ",", "payload", ",", "qos", ")", ":", "\"\"\"Handle birth message.\"\"\"", "birth", ".", "set", "(", ")", "with", "patch", "(", "\"homeassistant.components.mqtt.DISCOVERY_COOLDOWN\"", ",", "0.1", ")", ":", "await", "mqtt", ".", "async_subscribe", "(", "hass", ",", "\"homeassistant/status\"", ",", "wait_birth", ")", "mqtt_mock", ".", "_mqtt_on_connect", "(", "None", ",", "None", ",", "0", ",", "0", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "await", "birth", ".", "wait", "(", ")", "mqtt_client_mock", ".", "publish", ".", "assert_called_with", "(", "\"homeassistant/status\"", ",", "\"online\"", ",", "0", ",", "False", ")" ]
[ 781, 0 ]
[ 796, 9 ]
python
en
['en', 'de', 'en']
True
test_no_birth_message
(hass, mqtt_client_mock, mqtt_mock)
Test disabling birth message.
Test disabling birth message.
async def test_no_birth_message(hass, mqtt_client_mock, mqtt_mock): """Test disabling birth message.""" with patch("homeassistant.components.mqtt.DISCOVERY_COOLDOWN", 0.1): mqtt_mock._mqtt_on_connect(None, None, 0, 0) await hass.async_block_till_done() await asyncio.sleep(0.2) mqtt_client_mock.publish.assert_not_called()
[ "async", "def", "test_no_birth_message", "(", "hass", ",", "mqtt_client_mock", ",", "mqtt_mock", ")", ":", "with", "patch", "(", "\"homeassistant.components.mqtt.DISCOVERY_COOLDOWN\"", ",", "0.1", ")", ":", "mqtt_mock", ".", "_mqtt_on_connect", "(", "None", ",", "None", ",", "0", ",", "0", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "await", "asyncio", ".", "sleep", "(", "0.2", ")", "mqtt_client_mock", ".", "publish", ".", "assert_not_called", "(", ")" ]
[ 803, 0 ]
[ 809, 52 ]
python
de
['fr', 'de', 'en']
False
test_custom_will_message
(hass, mqtt_client_mock, mqtt_mock)
Test will message.
Test will message.
async def test_custom_will_message(hass, mqtt_client_mock, mqtt_mock): """Test will message.""" mqtt_client_mock.will_set.assert_called_with( topic="death", payload="death", qos=0, retain=False )
[ "async", "def", "test_custom_will_message", "(", "hass", ",", "mqtt_client_mock", ",", "mqtt_mock", ")", ":", "mqtt_client_mock", ".", "will_set", ".", "assert_called_with", "(", "topic", "=", "\"death\"", ",", "payload", "=", "\"death\"", ",", "qos", "=", "0", ",", "retain", "=", "False", ")" ]
[ 824, 0 ]
[ 828, 5 ]
python
en
['en', 'en', 'en']
True
test_default_will_message
(hass, mqtt_client_mock, mqtt_mock)
Test will message.
Test will message.
async def test_default_will_message(hass, mqtt_client_mock, mqtt_mock): """Test will message.""" mqtt_client_mock.will_set.assert_called_with( topic="homeassistant/status", payload="offline", qos=0, retain=False )
[ "async", "def", "test_default_will_message", "(", "hass", ",", "mqtt_client_mock", ",", "mqtt_mock", ")", ":", "mqtt_client_mock", ".", "will_set", ".", "assert_called_with", "(", "topic", "=", "\"homeassistant/status\"", ",", "payload", "=", "\"offline\"", ",", "qos", "=", "0", ",", "retain", "=", "False", ")" ]
[ 831, 0 ]
[ 835, 5 ]
python
en
['en', 'en', 'en']
True
test_no_will_message
(hass, mqtt_client_mock, mqtt_mock)
Test will message.
Test will message.
async def test_no_will_message(hass, mqtt_client_mock, mqtt_mock): """Test will message.""" mqtt_client_mock.will_set.assert_not_called()
[ "async", "def", "test_no_will_message", "(", "hass", ",", "mqtt_client_mock", ",", "mqtt_mock", ")", ":", "mqtt_client_mock", ".", "will_set", ".", "assert_not_called", "(", ")" ]
[ 842, 0 ]
[ 844, 49 ]
python
en
['en', 'en', 'en']
True
test_mqtt_subscribes_topics_on_connect
(hass, mqtt_client_mock, mqtt_mock)
Test subscription to topic on connect.
Test subscription to topic on connect.
async def test_mqtt_subscribes_topics_on_connect(hass, mqtt_client_mock, mqtt_mock): """Test subscription to topic on connect.""" await mqtt.async_subscribe(hass, "topic/test", None) await mqtt.async_subscribe(hass, "home/sensor", None, 2) await mqtt.async_subscribe(hass, "still/pending", None) await mqtt.async_subscribe(hass, "still/pending", None, 1) hass.add_job = MagicMock() mqtt_mock._mqtt_on_connect(None, None, 0, 0) await hass.async_block_till_done() assert mqtt_client_mock.disconnect.call_count == 0 expected = {"topic/test": 0, "home/sensor": 2, "still/pending": 1} calls = {call[1][1]: call[1][2] for call in hass.add_job.mock_calls} assert calls == expected
[ "async", "def", "test_mqtt_subscribes_topics_on_connect", "(", "hass", ",", "mqtt_client_mock", ",", "mqtt_mock", ")", ":", "await", "mqtt", ".", "async_subscribe", "(", "hass", ",", "\"topic/test\"", ",", "None", ")", "await", "mqtt", ".", "async_subscribe", "(", "hass", ",", "\"home/sensor\"", ",", "None", ",", "2", ")", "await", "mqtt", ".", "async_subscribe", "(", "hass", ",", "\"still/pending\"", ",", "None", ")", "await", "mqtt", ".", "async_subscribe", "(", "hass", ",", "\"still/pending\"", ",", "None", ",", "1", ")", "hass", ".", "add_job", "=", "MagicMock", "(", ")", "mqtt_mock", ".", "_mqtt_on_connect", "(", "None", ",", "None", ",", "0", ",", "0", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "mqtt_client_mock", ".", "disconnect", ".", "call_count", "==", "0", "expected", "=", "{", "\"topic/test\"", ":", "0", ",", "\"home/sensor\"", ":", "2", ",", "\"still/pending\"", ":", "1", "}", "calls", "=", "{", "call", "[", "1", "]", "[", "1", "]", ":", "call", "[", "1", "]", "[", "2", "]", "for", "call", "in", "hass", ".", "add_job", ".", "mock_calls", "}", "assert", "calls", "==", "expected" ]
[ 857, 0 ]
[ 873, 28 ]
python
en
['en', 'en', 'en']
True
test_setup_fails_without_config
(hass)
Test if the MQTT component fails to load with no config.
Test if the MQTT component fails to load with no config.
async def test_setup_fails_without_config(hass): """Test if the MQTT component fails to load with no config.""" assert not await async_setup_component(hass, mqtt.DOMAIN, {})
[ "async", "def", "test_setup_fails_without_config", "(", "hass", ")", ":", "assert", "not", "await", "async_setup_component", "(", "hass", ",", "mqtt", ".", "DOMAIN", ",", "{", "}", ")" ]
[ 876, 0 ]
[ 878, 65 ]
python
en
['en', 'en', 'en']
True
test_message_callback_exception_gets_logged
(hass, caplog, mqtt_mock)
Test exception raised by message handler.
Test exception raised by message handler.
async def test_message_callback_exception_gets_logged(hass, caplog, mqtt_mock): """Test exception raised by message handler.""" @callback def bad_handler(*args): """Record calls.""" raise Exception("This is a bad message callback") await mqtt.async_subscribe(hass, "test-topic", bad_handler) async_fire_mqtt_message(hass, "test-topic", "test") await hass.async_block_till_done() assert ( "Exception in bad_handler when handling msg on 'test-topic':" " 'test'" in caplog.text )
[ "async", "def", "test_message_callback_exception_gets_logged", "(", "hass", ",", "caplog", ",", "mqtt_mock", ")", ":", "@", "callback", "def", "bad_handler", "(", "*", "args", ")", ":", "\"\"\"Record calls.\"\"\"", "raise", "Exception", "(", "\"This is a bad message callback\"", ")", "await", "mqtt", ".", "async_subscribe", "(", "hass", ",", "\"test-topic\"", ",", "bad_handler", ")", "async_fire_mqtt_message", "(", "hass", ",", "\"test-topic\"", ",", "\"test\"", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "(", "\"Exception in bad_handler when handling msg on 'test-topic':\"", "\" 'test'\"", "in", "caplog", ".", "text", ")" ]
[ 882, 0 ]
[ 897, 5 ]
python
en
['en', 'en', 'en']
True
test_mqtt_ws_subscription
(hass, hass_ws_client, mqtt_mock)
Test MQTT websocket subscription.
Test MQTT websocket subscription.
async def test_mqtt_ws_subscription(hass, hass_ws_client, mqtt_mock): """Test MQTT websocket subscription.""" client = await hass_ws_client(hass) await client.send_json({"id": 5, "type": "mqtt/subscribe", "topic": "test-topic"}) response = await client.receive_json() assert response["success"] async_fire_mqtt_message(hass, "test-topic", "test1") async_fire_mqtt_message(hass, "test-topic", "test2") response = await client.receive_json() assert response["event"]["topic"] == "test-topic" assert response["event"]["payload"] == "test1" response = await client.receive_json() assert response["event"]["topic"] == "test-topic" assert response["event"]["payload"] == "test2" # Unsubscribe await client.send_json({"id": 8, "type": "unsubscribe_events", "subscription": 5}) response = await client.receive_json() assert response["success"]
[ "async", "def", "test_mqtt_ws_subscription", "(", "hass", ",", "hass_ws_client", ",", "mqtt_mock", ")", ":", "client", "=", "await", "hass_ws_client", "(", "hass", ")", "await", "client", ".", "send_json", "(", "{", "\"id\"", ":", "5", ",", "\"type\"", ":", "\"mqtt/subscribe\"", ",", "\"topic\"", ":", "\"test-topic\"", "}", ")", "response", "=", "await", "client", ".", "receive_json", "(", ")", "assert", "response", "[", "\"success\"", "]", "async_fire_mqtt_message", "(", "hass", ",", "\"test-topic\"", ",", "\"test1\"", ")", "async_fire_mqtt_message", "(", "hass", ",", "\"test-topic\"", ",", "\"test2\"", ")", "response", "=", "await", "client", ".", "receive_json", "(", ")", "assert", "response", "[", "\"event\"", "]", "[", "\"topic\"", "]", "==", "\"test-topic\"", "assert", "response", "[", "\"event\"", "]", "[", "\"payload\"", "]", "==", "\"test1\"", "response", "=", "await", "client", ".", "receive_json", "(", ")", "assert", "response", "[", "\"event\"", "]", "[", "\"topic\"", "]", "==", "\"test-topic\"", "assert", "response", "[", "\"event\"", "]", "[", "\"payload\"", "]", "==", "\"test2\"", "# Unsubscribe", "await", "client", ".", "send_json", "(", "{", "\"id\"", ":", "8", ",", "\"type\"", ":", "\"unsubscribe_events\"", ",", "\"subscription\"", ":", "5", "}", ")", "response", "=", "await", "client", ".", "receive_json", "(", ")", "assert", "response", "[", "\"success\"", "]" ]
[ 900, 0 ]
[ 921, 30 ]
python
en
['en', 'sv', 'it']
False
test_dump_service
(hass, mqtt_mock)
Test that we can dump a topic.
Test that we can dump a topic.
async def test_dump_service(hass, mqtt_mock): """Test that we can dump a topic.""" mopen = mock_open() await hass.services.async_call( "mqtt", "dump", {"topic": "bla/#", "duration": 3}, blocking=True ) async_fire_mqtt_message(hass, "bla/1", "test1") async_fire_mqtt_message(hass, "bla/2", "test2") with patch("homeassistant.components.mqtt.open", mopen): async_fire_time_changed(hass, utcnow() + timedelta(seconds=3)) await hass.async_block_till_done() writes = mopen.return_value.write.mock_calls assert len(writes) == 2 assert writes[0][1][0] == "bla/1,test1\n" assert writes[1][1][0] == "bla/2,test2\n"
[ "async", "def", "test_dump_service", "(", "hass", ",", "mqtt_mock", ")", ":", "mopen", "=", "mock_open", "(", ")", "await", "hass", ".", "services", ".", "async_call", "(", "\"mqtt\"", ",", "\"dump\"", ",", "{", "\"topic\"", ":", "\"bla/#\"", ",", "\"duration\"", ":", "3", "}", ",", "blocking", "=", "True", ")", "async_fire_mqtt_message", "(", "hass", ",", "\"bla/1\"", ",", "\"test1\"", ")", "async_fire_mqtt_message", "(", "hass", ",", "\"bla/2\"", ",", "\"test2\"", ")", "with", "patch", "(", "\"homeassistant.components.mqtt.open\"", ",", "mopen", ")", ":", "async_fire_time_changed", "(", "hass", ",", "utcnow", "(", ")", "+", "timedelta", "(", "seconds", "=", "3", ")", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "writes", "=", "mopen", ".", "return_value", ".", "write", ".", "mock_calls", "assert", "len", "(", "writes", ")", "==", "2", "assert", "writes", "[", "0", "]", "[", "1", "]", "[", "0", "]", "==", "\"bla/1,test1\\n\"", "assert", "writes", "[", "1", "]", "[", "1", "]", "[", "0", "]", "==", "\"bla/2,test2\\n\"" ]
[ 924, 0 ]
[ 941, 45 ]
python
en
['en', 'en', 'en']
True
test_mqtt_ws_remove_discovered_device
( hass, device_reg, entity_reg, hass_ws_client, mqtt_mock )
Test MQTT websocket device removal.
Test MQTT websocket device removal.
async def test_mqtt_ws_remove_discovered_device( hass, device_reg, entity_reg, hass_ws_client, mqtt_mock ): """Test MQTT websocket device removal.""" data = ( '{ "device":{"identifiers":["0AFFD2"]},' ' "state_topic": "foobar/sensor",' ' "unique_id": "unique" }' ) async_fire_mqtt_message(hass, "homeassistant/sensor/bla/config", data) await hass.async_block_till_done() # Verify device entry is created device_entry = device_reg.async_get_device({("mqtt", "0AFFD2")}, set()) assert device_entry is not None client = await hass_ws_client(hass) await client.send_json( {"id": 5, "type": "mqtt/device/remove", "device_id": device_entry.id} ) response = await client.receive_json() assert response["success"] # Verify device entry is cleared device_entry = device_reg.async_get_device({("mqtt", "0AFFD2")}, set()) assert device_entry is None
[ "async", "def", "test_mqtt_ws_remove_discovered_device", "(", "hass", ",", "device_reg", ",", "entity_reg", ",", "hass_ws_client", ",", "mqtt_mock", ")", ":", "data", "=", "(", "'{ \"device\":{\"identifiers\":[\"0AFFD2\"]},'", "' \"state_topic\": \"foobar/sensor\",'", "' \"unique_id\": \"unique\" }'", ")", "async_fire_mqtt_message", "(", "hass", ",", "\"homeassistant/sensor/bla/config\"", ",", "data", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "# Verify device entry is created", "device_entry", "=", "device_reg", ".", "async_get_device", "(", "{", "(", "\"mqtt\"", ",", "\"0AFFD2\"", ")", "}", ",", "set", "(", ")", ")", "assert", "device_entry", "is", "not", "None", "client", "=", "await", "hass_ws_client", "(", "hass", ")", "await", "client", ".", "send_json", "(", "{", "\"id\"", ":", "5", ",", "\"type\"", ":", "\"mqtt/device/remove\"", ",", "\"device_id\"", ":", "device_entry", ".", "id", "}", ")", "response", "=", "await", "client", ".", "receive_json", "(", ")", "assert", "response", "[", "\"success\"", "]", "# Verify device entry is cleared", "device_entry", "=", "device_reg", ".", "async_get_device", "(", "{", "(", "\"mqtt\"", ",", "\"0AFFD2\"", ")", "}", ",", "set", "(", ")", ")", "assert", "device_entry", "is", "None" ]
[ 944, 0 ]
[ 970, 31 ]
python
fr
['fr', 'fy', 'it']
False
test_mqtt_ws_remove_discovered_device_twice
( hass, device_reg, hass_ws_client, mqtt_mock )
Test MQTT websocket device removal.
Test MQTT websocket device removal.
async def test_mqtt_ws_remove_discovered_device_twice( hass, device_reg, hass_ws_client, mqtt_mock ): """Test MQTT websocket device removal.""" data = ( '{ "device":{"identifiers":["0AFFD2"]},' ' "state_topic": "foobar/sensor",' ' "unique_id": "unique" }' ) async_fire_mqtt_message(hass, "homeassistant/sensor/bla/config", data) await hass.async_block_till_done() device_entry = device_reg.async_get_device({("mqtt", "0AFFD2")}, set()) assert device_entry is not None client = await hass_ws_client(hass) await client.send_json( {"id": 5, "type": "mqtt/device/remove", "device_id": device_entry.id} ) response = await client.receive_json() assert response["success"] await client.send_json( {"id": 6, "type": "mqtt/device/remove", "device_id": device_entry.id} ) response = await client.receive_json() assert not response["success"] assert response["error"]["code"] == websocket_api.const.ERR_NOT_FOUND
[ "async", "def", "test_mqtt_ws_remove_discovered_device_twice", "(", "hass", ",", "device_reg", ",", "hass_ws_client", ",", "mqtt_mock", ")", ":", "data", "=", "(", "'{ \"device\":{\"identifiers\":[\"0AFFD2\"]},'", "' \"state_topic\": \"foobar/sensor\",'", "' \"unique_id\": \"unique\" }'", ")", "async_fire_mqtt_message", "(", "hass", ",", "\"homeassistant/sensor/bla/config\"", ",", "data", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "device_entry", "=", "device_reg", ".", "async_get_device", "(", "{", "(", "\"mqtt\"", ",", "\"0AFFD2\"", ")", "}", ",", "set", "(", ")", ")", "assert", "device_entry", "is", "not", "None", "client", "=", "await", "hass_ws_client", "(", "hass", ")", "await", "client", ".", "send_json", "(", "{", "\"id\"", ":", "5", ",", "\"type\"", ":", "\"mqtt/device/remove\"", ",", "\"device_id\"", ":", "device_entry", ".", "id", "}", ")", "response", "=", "await", "client", ".", "receive_json", "(", ")", "assert", "response", "[", "\"success\"", "]", "await", "client", ".", "send_json", "(", "{", "\"id\"", ":", "6", ",", "\"type\"", ":", "\"mqtt/device/remove\"", ",", "\"device_id\"", ":", "device_entry", ".", "id", "}", ")", "response", "=", "await", "client", ".", "receive_json", "(", ")", "assert", "not", "response", "[", "\"success\"", "]", "assert", "response", "[", "\"error\"", "]", "[", "\"code\"", "]", "==", "websocket_api", ".", "const", ".", "ERR_NOT_FOUND" ]
[ 973, 0 ]
[ 1001, 73 ]
python
fr
['fr', 'fy', 'it']
False
test_mqtt_ws_remove_discovered_device_same_topic
( hass, device_reg, hass_ws_client, mqtt_mock )
Test MQTT websocket device removal.
Test MQTT websocket device removal.
async def test_mqtt_ws_remove_discovered_device_same_topic( hass, device_reg, hass_ws_client, mqtt_mock ): """Test MQTT websocket device removal.""" data = ( '{ "device":{"identifiers":["0AFFD2"]},' ' "state_topic": "foobar/sensor",' ' "availability_topic": "foobar/sensor",' ' "unique_id": "unique" }' ) async_fire_mqtt_message(hass, "homeassistant/sensor/bla/config", data) await hass.async_block_till_done() device_entry = device_reg.async_get_device({("mqtt", "0AFFD2")}, set()) assert device_entry is not None client = await hass_ws_client(hass) await client.send_json( {"id": 5, "type": "mqtt/device/remove", "device_id": device_entry.id} ) response = await client.receive_json() assert response["success"] await client.send_json( {"id": 6, "type": "mqtt/device/remove", "device_id": device_entry.id} ) response = await client.receive_json() assert not response["success"] assert response["error"]["code"] == websocket_api.const.ERR_NOT_FOUND
[ "async", "def", "test_mqtt_ws_remove_discovered_device_same_topic", "(", "hass", ",", "device_reg", ",", "hass_ws_client", ",", "mqtt_mock", ")", ":", "data", "=", "(", "'{ \"device\":{\"identifiers\":[\"0AFFD2\"]},'", "' \"state_topic\": \"foobar/sensor\",'", "' \"availability_topic\": \"foobar/sensor\",'", "' \"unique_id\": \"unique\" }'", ")", "async_fire_mqtt_message", "(", "hass", ",", "\"homeassistant/sensor/bla/config\"", ",", "data", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "device_entry", "=", "device_reg", ".", "async_get_device", "(", "{", "(", "\"mqtt\"", ",", "\"0AFFD2\"", ")", "}", ",", "set", "(", ")", ")", "assert", "device_entry", "is", "not", "None", "client", "=", "await", "hass_ws_client", "(", "hass", ")", "await", "client", ".", "send_json", "(", "{", "\"id\"", ":", "5", ",", "\"type\"", ":", "\"mqtt/device/remove\"", ",", "\"device_id\"", ":", "device_entry", ".", "id", "}", ")", "response", "=", "await", "client", ".", "receive_json", "(", ")", "assert", "response", "[", "\"success\"", "]", "await", "client", ".", "send_json", "(", "{", "\"id\"", ":", "6", ",", "\"type\"", ":", "\"mqtt/device/remove\"", ",", "\"device_id\"", ":", "device_entry", ".", "id", "}", ")", "response", "=", "await", "client", ".", "receive_json", "(", ")", "assert", "not", "response", "[", "\"success\"", "]", "assert", "response", "[", "\"error\"", "]", "[", "\"code\"", "]", "==", "websocket_api", ".", "const", ".", "ERR_NOT_FOUND" ]
[ 1004, 0 ]
[ 1033, 73 ]
python
fr
['fr', 'fy', 'it']
False
test_mqtt_ws_remove_non_mqtt_device
( hass, device_reg, hass_ws_client, mqtt_mock )
Test MQTT websocket device removal of device belonging to other domain.
Test MQTT websocket device removal of device belonging to other domain.
async def test_mqtt_ws_remove_non_mqtt_device( hass, device_reg, hass_ws_client, mqtt_mock ): """Test MQTT websocket device removal of device belonging to other domain.""" config_entry = MockConfigEntry(domain="test") config_entry.add_to_hass(hass) device_entry = device_reg.async_get_or_create( config_entry_id=config_entry.entry_id, connections={(device_registry.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")}, ) assert device_entry is not None client = await hass_ws_client(hass) await client.send_json( {"id": 5, "type": "mqtt/device/remove", "device_id": device_entry.id} ) response = await client.receive_json() assert not response["success"] assert response["error"]["code"] == websocket_api.const.ERR_NOT_FOUND
[ "async", "def", "test_mqtt_ws_remove_non_mqtt_device", "(", "hass", ",", "device_reg", ",", "hass_ws_client", ",", "mqtt_mock", ")", ":", "config_entry", "=", "MockConfigEntry", "(", "domain", "=", "\"test\"", ")", "config_entry", ".", "add_to_hass", "(", "hass", ")", "device_entry", "=", "device_reg", ".", "async_get_or_create", "(", "config_entry_id", "=", "config_entry", ".", "entry_id", ",", "connections", "=", "{", "(", "device_registry", ".", "CONNECTION_NETWORK_MAC", ",", "\"12:34:56:AB:CD:EF\"", ")", "}", ",", ")", "assert", "device_entry", "is", "not", "None", "client", "=", "await", "hass_ws_client", "(", "hass", ")", "await", "client", ".", "send_json", "(", "{", "\"id\"", ":", "5", ",", "\"type\"", ":", "\"mqtt/device/remove\"", ",", "\"device_id\"", ":", "device_entry", ".", "id", "}", ")", "response", "=", "await", "client", ".", "receive_json", "(", ")", "assert", "not", "response", "[", "\"success\"", "]", "assert", "response", "[", "\"error\"", "]", "[", "\"code\"", "]", "==", "websocket_api", ".", "const", ".", "ERR_NOT_FOUND" ]
[ 1036, 0 ]
[ 1055, 73 ]
python
en
['en', 'en', 'en']
True
test_mqtt_ws_get_device_debug_info
( hass, device_reg, hass_ws_client, mqtt_mock )
Test MQTT websocket device debug info.
Test MQTT websocket device debug info.
async def test_mqtt_ws_get_device_debug_info( hass, device_reg, hass_ws_client, mqtt_mock ): """Test MQTT websocket device debug info.""" config = { "device": {"identifiers": ["0AFFD2"]}, "platform": "mqtt", "state_topic": "foobar/sensor", "unique_id": "unique", } data = json.dumps(config) async_fire_mqtt_message(hass, "homeassistant/sensor/bla/config", data) await hass.async_block_till_done() # Verify device entry is created device_entry = device_reg.async_get_device({("mqtt", "0AFFD2")}, set()) assert device_entry is not None client = await hass_ws_client(hass) await client.send_json( {"id": 5, "type": "mqtt/device/debug_info", "device_id": device_entry.id} ) response = await client.receive_json() assert response["success"] expected_result = { "entities": [ { "entity_id": "sensor.mqtt_sensor", "subscriptions": [{"topic": "foobar/sensor", "messages": []}], "discovery_data": { "payload": config, "topic": "homeassistant/sensor/bla/config", }, } ], "triggers": [], } assert response["result"] == expected_result
[ "async", "def", "test_mqtt_ws_get_device_debug_info", "(", "hass", ",", "device_reg", ",", "hass_ws_client", ",", "mqtt_mock", ")", ":", "config", "=", "{", "\"device\"", ":", "{", "\"identifiers\"", ":", "[", "\"0AFFD2\"", "]", "}", ",", "\"platform\"", ":", "\"mqtt\"", ",", "\"state_topic\"", ":", "\"foobar/sensor\"", ",", "\"unique_id\"", ":", "\"unique\"", ",", "}", "data", "=", "json", ".", "dumps", "(", "config", ")", "async_fire_mqtt_message", "(", "hass", ",", "\"homeassistant/sensor/bla/config\"", ",", "data", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "# Verify device entry is created", "device_entry", "=", "device_reg", ".", "async_get_device", "(", "{", "(", "\"mqtt\"", ",", "\"0AFFD2\"", ")", "}", ",", "set", "(", ")", ")", "assert", "device_entry", "is", "not", "None", "client", "=", "await", "hass_ws_client", "(", "hass", ")", "await", "client", ".", "send_json", "(", "{", "\"id\"", ":", "5", ",", "\"type\"", ":", "\"mqtt/device/debug_info\"", ",", "\"device_id\"", ":", "device_entry", ".", "id", "}", ")", "response", "=", "await", "client", ".", "receive_json", "(", ")", "assert", "response", "[", "\"success\"", "]", "expected_result", "=", "{", "\"entities\"", ":", "[", "{", "\"entity_id\"", ":", "\"sensor.mqtt_sensor\"", ",", "\"subscriptions\"", ":", "[", "{", "\"topic\"", ":", "\"foobar/sensor\"", ",", "\"messages\"", ":", "[", "]", "}", "]", ",", "\"discovery_data\"", ":", "{", "\"payload\"", ":", "config", ",", "\"topic\"", ":", "\"homeassistant/sensor/bla/config\"", ",", "}", ",", "}", "]", ",", "\"triggers\"", ":", "[", "]", ",", "}", "assert", "response", "[", "\"result\"", "]", "==", "expected_result" ]
[ 1058, 0 ]
[ 1096, 48 ]
python
fr
['fr', 'fy', 'it']
False
test_debug_info_multiple_devices
(hass, mqtt_mock)
Test we get correct debug_info when multiple devices are present.
Test we get correct debug_info when multiple devices are present.
async def test_debug_info_multiple_devices(hass, mqtt_mock): """Test we get correct debug_info when multiple devices are present.""" devices = [ { "domain": "sensor", "config": { "device": {"identifiers": ["0AFFD0"]}, "platform": "mqtt", "state_topic": "test-topic-sensor", "unique_id": "unique", }, }, { "domain": "binary_sensor", "config": { "device": {"identifiers": ["0AFFD1"]}, "platform": "mqtt", "state_topic": "test-topic-binary-sensor", "unique_id": "unique", }, }, { "domain": "device_automation", "config": { "automation_type": "trigger", "device": {"identifiers": ["0AFFD2"]}, "platform": "mqtt", "topic": "test-topic1", "type": "foo", "subtype": "bar", }, }, { "domain": "device_automation", "config": { "automation_type": "trigger", "device": {"identifiers": ["0AFFD3"]}, "platform": "mqtt", "topic": "test-topic2", "type": "ikk", "subtype": "baz", }, }, ] registry = await hass.helpers.device_registry.async_get_registry() for d in devices: data = json.dumps(d["config"]) domain = d["domain"] id = d["config"]["device"]["identifiers"][0] async_fire_mqtt_message(hass, f"homeassistant/{domain}/{id}/config", data) await hass.async_block_till_done() for d in devices: domain = d["domain"] id = d["config"]["device"]["identifiers"][0] device = registry.async_get_device({("mqtt", id)}, set()) assert device is not None debug_info_data = await debug_info.info_for_device(hass, device.id) if d["domain"] != "device_automation": assert len(debug_info_data["entities"]) == 1 assert len(debug_info_data["triggers"]) == 0 discovery_data = debug_info_data["entities"][0]["discovery_data"] assert len(debug_info_data["entities"][0]["subscriptions"]) == 1 topic = d["config"]["state_topic"] assert {"topic": topic, "messages": []} in debug_info_data["entities"][0][ "subscriptions" ] else: assert len(debug_info_data["entities"]) == 0 assert len(debug_info_data["triggers"]) == 1 discovery_data = debug_info_data["triggers"][0]["discovery_data"] assert discovery_data["topic"] == f"homeassistant/{domain}/{id}/config" assert discovery_data["payload"] == d["config"]
[ "async", "def", "test_debug_info_multiple_devices", "(", "hass", ",", "mqtt_mock", ")", ":", "devices", "=", "[", "{", "\"domain\"", ":", "\"sensor\"", ",", "\"config\"", ":", "{", "\"device\"", ":", "{", "\"identifiers\"", ":", "[", "\"0AFFD0\"", "]", "}", ",", "\"platform\"", ":", "\"mqtt\"", ",", "\"state_topic\"", ":", "\"test-topic-sensor\"", ",", "\"unique_id\"", ":", "\"unique\"", ",", "}", ",", "}", ",", "{", "\"domain\"", ":", "\"binary_sensor\"", ",", "\"config\"", ":", "{", "\"device\"", ":", "{", "\"identifiers\"", ":", "[", "\"0AFFD1\"", "]", "}", ",", "\"platform\"", ":", "\"mqtt\"", ",", "\"state_topic\"", ":", "\"test-topic-binary-sensor\"", ",", "\"unique_id\"", ":", "\"unique\"", ",", "}", ",", "}", ",", "{", "\"domain\"", ":", "\"device_automation\"", ",", "\"config\"", ":", "{", "\"automation_type\"", ":", "\"trigger\"", ",", "\"device\"", ":", "{", "\"identifiers\"", ":", "[", "\"0AFFD2\"", "]", "}", ",", "\"platform\"", ":", "\"mqtt\"", ",", "\"topic\"", ":", "\"test-topic1\"", ",", "\"type\"", ":", "\"foo\"", ",", "\"subtype\"", ":", "\"bar\"", ",", "}", ",", "}", ",", "{", "\"domain\"", ":", "\"device_automation\"", ",", "\"config\"", ":", "{", "\"automation_type\"", ":", "\"trigger\"", ",", "\"device\"", ":", "{", "\"identifiers\"", ":", "[", "\"0AFFD3\"", "]", "}", ",", "\"platform\"", ":", "\"mqtt\"", ",", "\"topic\"", ":", "\"test-topic2\"", ",", "\"type\"", ":", "\"ikk\"", ",", "\"subtype\"", ":", "\"baz\"", ",", "}", ",", "}", ",", "]", "registry", "=", "await", "hass", ".", "helpers", ".", "device_registry", ".", "async_get_registry", "(", ")", "for", "d", "in", "devices", ":", "data", "=", "json", ".", "dumps", "(", "d", "[", "\"config\"", "]", ")", "domain", "=", "d", "[", "\"domain\"", "]", "id", "=", "d", "[", "\"config\"", "]", "[", "\"device\"", "]", "[", "\"identifiers\"", "]", "[", "0", "]", "async_fire_mqtt_message", "(", "hass", ",", "f\"homeassistant/{domain}/{id}/config\"", ",", "data", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "for", "d", "in", "devices", ":", "domain", "=", "d", "[", "\"domain\"", "]", "id", "=", "d", "[", "\"config\"", "]", "[", "\"device\"", "]", "[", "\"identifiers\"", "]", "[", "0", "]", "device", "=", "registry", ".", "async_get_device", "(", "{", "(", "\"mqtt\"", ",", "id", ")", "}", ",", "set", "(", ")", ")", "assert", "device", "is", "not", "None", "debug_info_data", "=", "await", "debug_info", ".", "info_for_device", "(", "hass", ",", "device", ".", "id", ")", "if", "d", "[", "\"domain\"", "]", "!=", "\"device_automation\"", ":", "assert", "len", "(", "debug_info_data", "[", "\"entities\"", "]", ")", "==", "1", "assert", "len", "(", "debug_info_data", "[", "\"triggers\"", "]", ")", "==", "0", "discovery_data", "=", "debug_info_data", "[", "\"entities\"", "]", "[", "0", "]", "[", "\"discovery_data\"", "]", "assert", "len", "(", "debug_info_data", "[", "\"entities\"", "]", "[", "0", "]", "[", "\"subscriptions\"", "]", ")", "==", "1", "topic", "=", "d", "[", "\"config\"", "]", "[", "\"state_topic\"", "]", "assert", "{", "\"topic\"", ":", "topic", ",", "\"messages\"", ":", "[", "]", "}", "in", "debug_info_data", "[", "\"entities\"", "]", "[", "0", "]", "[", "\"subscriptions\"", "]", "else", ":", "assert", "len", "(", "debug_info_data", "[", "\"entities\"", "]", ")", "==", "0", "assert", "len", "(", "debug_info_data", "[", "\"triggers\"", "]", ")", "==", "1", "discovery_data", "=", "debug_info_data", "[", "\"triggers\"", "]", "[", "0", "]", "[", "\"discovery_data\"", "]", "assert", "discovery_data", "[", "\"topic\"", "]", "==", "f\"homeassistant/{domain}/{id}/config\"", "assert", "discovery_data", "[", "\"payload\"", "]", "==", "d", "[", "\"config\"", "]" ]
[ 1099, 0 ]
[ 1175, 55 ]
python
en
['en', 'en', 'en']
True
test_debug_info_multiple_entities_triggers
(hass, mqtt_mock)
Test we get correct debug_info for a device with multiple entities and triggers.
Test we get correct debug_info for a device with multiple entities and triggers.
async def test_debug_info_multiple_entities_triggers(hass, mqtt_mock): """Test we get correct debug_info for a device with multiple entities and triggers.""" config = [ { "domain": "sensor", "config": { "device": {"identifiers": ["0AFFD0"]}, "platform": "mqtt", "state_topic": "test-topic-sensor", "unique_id": "unique", }, }, { "domain": "binary_sensor", "config": { "device": {"identifiers": ["0AFFD0"]}, "platform": "mqtt", "state_topic": "test-topic-binary-sensor", "unique_id": "unique", }, }, { "domain": "device_automation", "config": { "automation_type": "trigger", "device": {"identifiers": ["0AFFD0"]}, "platform": "mqtt", "topic": "test-topic1", "type": "foo", "subtype": "bar", }, }, { "domain": "device_automation", "config": { "automation_type": "trigger", "device": {"identifiers": ["0AFFD0"]}, "platform": "mqtt", "topic": "test-topic2", "type": "ikk", "subtype": "baz", }, }, ] registry = await hass.helpers.device_registry.async_get_registry() for c in config: data = json.dumps(c["config"]) domain = c["domain"] # Use topic as discovery_id id = c["config"].get("topic", c["config"].get("state_topic")) async_fire_mqtt_message(hass, f"homeassistant/{domain}/{id}/config", data) await hass.async_block_till_done() device_id = config[0]["config"]["device"]["identifiers"][0] device = registry.async_get_device({("mqtt", device_id)}, set()) assert device is not None debug_info_data = await debug_info.info_for_device(hass, device.id) assert len(debug_info_data["entities"]) == 2 assert len(debug_info_data["triggers"]) == 2 for c in config: # Test we get debug info for each entity and trigger domain = c["domain"] # Use topic as discovery_id id = c["config"].get("topic", c["config"].get("state_topic")) if c["domain"] != "device_automation": discovery_data = [e["discovery_data"] for e in debug_info_data["entities"]] topic = c["config"]["state_topic"] assert {"topic": topic, "messages": []} in [ t for e in debug_info_data["entities"] for t in e["subscriptions"] ] else: discovery_data = [e["discovery_data"] for e in debug_info_data["triggers"]] assert { "topic": f"homeassistant/{domain}/{id}/config", "payload": c["config"], } in discovery_data
[ "async", "def", "test_debug_info_multiple_entities_triggers", "(", "hass", ",", "mqtt_mock", ")", ":", "config", "=", "[", "{", "\"domain\"", ":", "\"sensor\"", ",", "\"config\"", ":", "{", "\"device\"", ":", "{", "\"identifiers\"", ":", "[", "\"0AFFD0\"", "]", "}", ",", "\"platform\"", ":", "\"mqtt\"", ",", "\"state_topic\"", ":", "\"test-topic-sensor\"", ",", "\"unique_id\"", ":", "\"unique\"", ",", "}", ",", "}", ",", "{", "\"domain\"", ":", "\"binary_sensor\"", ",", "\"config\"", ":", "{", "\"device\"", ":", "{", "\"identifiers\"", ":", "[", "\"0AFFD0\"", "]", "}", ",", "\"platform\"", ":", "\"mqtt\"", ",", "\"state_topic\"", ":", "\"test-topic-binary-sensor\"", ",", "\"unique_id\"", ":", "\"unique\"", ",", "}", ",", "}", ",", "{", "\"domain\"", ":", "\"device_automation\"", ",", "\"config\"", ":", "{", "\"automation_type\"", ":", "\"trigger\"", ",", "\"device\"", ":", "{", "\"identifiers\"", ":", "[", "\"0AFFD0\"", "]", "}", ",", "\"platform\"", ":", "\"mqtt\"", ",", "\"topic\"", ":", "\"test-topic1\"", ",", "\"type\"", ":", "\"foo\"", ",", "\"subtype\"", ":", "\"bar\"", ",", "}", ",", "}", ",", "{", "\"domain\"", ":", "\"device_automation\"", ",", "\"config\"", ":", "{", "\"automation_type\"", ":", "\"trigger\"", ",", "\"device\"", ":", "{", "\"identifiers\"", ":", "[", "\"0AFFD0\"", "]", "}", ",", "\"platform\"", ":", "\"mqtt\"", ",", "\"topic\"", ":", "\"test-topic2\"", ",", "\"type\"", ":", "\"ikk\"", ",", "\"subtype\"", ":", "\"baz\"", ",", "}", ",", "}", ",", "]", "registry", "=", "await", "hass", ".", "helpers", ".", "device_registry", ".", "async_get_registry", "(", ")", "for", "c", "in", "config", ":", "data", "=", "json", ".", "dumps", "(", "c", "[", "\"config\"", "]", ")", "domain", "=", "c", "[", "\"domain\"", "]", "# Use topic as discovery_id", "id", "=", "c", "[", "\"config\"", "]", ".", "get", "(", "\"topic\"", ",", "c", "[", "\"config\"", "]", ".", "get", "(", "\"state_topic\"", ")", ")", "async_fire_mqtt_message", "(", "hass", ",", "f\"homeassistant/{domain}/{id}/config\"", ",", "data", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "device_id", "=", "config", "[", "0", "]", "[", "\"config\"", "]", "[", "\"device\"", "]", "[", "\"identifiers\"", "]", "[", "0", "]", "device", "=", "registry", ".", "async_get_device", "(", "{", "(", "\"mqtt\"", ",", "device_id", ")", "}", ",", "set", "(", ")", ")", "assert", "device", "is", "not", "None", "debug_info_data", "=", "await", "debug_info", ".", "info_for_device", "(", "hass", ",", "device", ".", "id", ")", "assert", "len", "(", "debug_info_data", "[", "\"entities\"", "]", ")", "==", "2", "assert", "len", "(", "debug_info_data", "[", "\"triggers\"", "]", ")", "==", "2", "for", "c", "in", "config", ":", "# Test we get debug info for each entity and trigger", "domain", "=", "c", "[", "\"domain\"", "]", "# Use topic as discovery_id", "id", "=", "c", "[", "\"config\"", "]", ".", "get", "(", "\"topic\"", ",", "c", "[", "\"config\"", "]", ".", "get", "(", "\"state_topic\"", ")", ")", "if", "c", "[", "\"domain\"", "]", "!=", "\"device_automation\"", ":", "discovery_data", "=", "[", "e", "[", "\"discovery_data\"", "]", "for", "e", "in", "debug_info_data", "[", "\"entities\"", "]", "]", "topic", "=", "c", "[", "\"config\"", "]", "[", "\"state_topic\"", "]", "assert", "{", "\"topic\"", ":", "topic", ",", "\"messages\"", ":", "[", "]", "}", "in", "[", "t", "for", "e", "in", "debug_info_data", "[", "\"entities\"", "]", "for", "t", "in", "e", "[", "\"subscriptions\"", "]", "]", "else", ":", "discovery_data", "=", "[", "e", "[", "\"discovery_data\"", "]", "for", "e", "in", "debug_info_data", "[", "\"triggers\"", "]", "]", "assert", "{", "\"topic\"", ":", "f\"homeassistant/{domain}/{id}/config\"", ",", "\"payload\"", ":", "c", "[", "\"config\"", "]", ",", "}", "in", "discovery_data" ]
[ 1178, 0 ]
[ 1258, 27 ]
python
en
['en', 'en', 'en']
True
test_debug_info_non_mqtt
(hass, device_reg, entity_reg)
Test we get empty debug_info for a device with non MQTT entities.
Test we get empty debug_info for a device with non MQTT entities.
async def test_debug_info_non_mqtt(hass, device_reg, entity_reg): """Test we get empty debug_info for a device with non MQTT entities.""" DOMAIN = "sensor" platform = getattr(hass.components, f"test.{DOMAIN}") platform.init() config_entry = MockConfigEntry(domain="test", data={}) config_entry.add_to_hass(hass) device_entry = device_reg.async_get_or_create( config_entry_id=config_entry.entry_id, connections={(device_registry.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")}, ) for device_class in DEVICE_CLASSES: entity_reg.async_get_or_create( DOMAIN, "test", platform.ENTITIES[device_class].unique_id, device_id=device_entry.id, ) assert await async_setup_component(hass, DOMAIN, {DOMAIN: {"platform": "test"}}) debug_info_data = await debug_info.info_for_device(hass, device_entry.id) assert len(debug_info_data["entities"]) == 0 assert len(debug_info_data["triggers"]) == 0
[ "async", "def", "test_debug_info_non_mqtt", "(", "hass", ",", "device_reg", ",", "entity_reg", ")", ":", "DOMAIN", "=", "\"sensor\"", "platform", "=", "getattr", "(", "hass", ".", "components", ",", "f\"test.{DOMAIN}\"", ")", "platform", ".", "init", "(", ")", "config_entry", "=", "MockConfigEntry", "(", "domain", "=", "\"test\"", ",", "data", "=", "{", "}", ")", "config_entry", ".", "add_to_hass", "(", "hass", ")", "device_entry", "=", "device_reg", ".", "async_get_or_create", "(", "config_entry_id", "=", "config_entry", ".", "entry_id", ",", "connections", "=", "{", "(", "device_registry", ".", "CONNECTION_NETWORK_MAC", ",", "\"12:34:56:AB:CD:EF\"", ")", "}", ",", ")", "for", "device_class", "in", "DEVICE_CLASSES", ":", "entity_reg", ".", "async_get_or_create", "(", "DOMAIN", ",", "\"test\"", ",", "platform", ".", "ENTITIES", "[", "device_class", "]", ".", "unique_id", ",", "device_id", "=", "device_entry", ".", "id", ",", ")", "assert", "await", "async_setup_component", "(", "hass", ",", "DOMAIN", ",", "{", "DOMAIN", ":", "{", "\"platform\"", ":", "\"test\"", "}", "}", ")", "debug_info_data", "=", "await", "debug_info", ".", "info_for_device", "(", "hass", ",", "device_entry", ".", "id", ")", "assert", "len", "(", "debug_info_data", "[", "\"entities\"", "]", ")", "==", "0", "assert", "len", "(", "debug_info_data", "[", "\"triggers\"", "]", ")", "==", "0" ]
[ 1261, 0 ]
[ 1285, 48 ]
python
en
['en', 'en', 'en']
True
test_debug_info_wildcard
(hass, mqtt_mock)
Test debug info.
Test debug info.
async def test_debug_info_wildcard(hass, mqtt_mock): """Test debug info.""" config = { "device": {"identifiers": ["helloworld"]}, "platform": "mqtt", "name": "test", "state_topic": "sensor/#", "unique_id": "veryunique", } registry = await hass.helpers.device_registry.async_get_registry() data = json.dumps(config) async_fire_mqtt_message(hass, "homeassistant/sensor/bla/config", data) await hass.async_block_till_done() device = registry.async_get_device({("mqtt", "helloworld")}, set()) assert device is not None debug_info_data = await debug_info.info_for_device(hass, device.id) assert len(debug_info_data["entities"][0]["subscriptions"]) >= 1 assert {"topic": "sensor/#", "messages": []} in debug_info_data["entities"][0][ "subscriptions" ] start_dt = datetime(2019, 1, 1, 0, 0, 0) with patch("homeassistant.util.dt.utcnow") as dt_utcnow: dt_utcnow.return_value = start_dt async_fire_mqtt_message(hass, "sensor/abc", "123") debug_info_data = await debug_info.info_for_device(hass, device.id) assert len(debug_info_data["entities"][0]["subscriptions"]) >= 1 assert { "topic": "sensor/#", "messages": [ { "payload": "123", "qos": 0, "retain": False, "time": start_dt, "topic": "sensor/abc", } ], } in debug_info_data["entities"][0]["subscriptions"]
[ "async", "def", "test_debug_info_wildcard", "(", "hass", ",", "mqtt_mock", ")", ":", "config", "=", "{", "\"device\"", ":", "{", "\"identifiers\"", ":", "[", "\"helloworld\"", "]", "}", ",", "\"platform\"", ":", "\"mqtt\"", ",", "\"name\"", ":", "\"test\"", ",", "\"state_topic\"", ":", "\"sensor/#\"", ",", "\"unique_id\"", ":", "\"veryunique\"", ",", "}", "registry", "=", "await", "hass", ".", "helpers", ".", "device_registry", ".", "async_get_registry", "(", ")", "data", "=", "json", ".", "dumps", "(", "config", ")", "async_fire_mqtt_message", "(", "hass", ",", "\"homeassistant/sensor/bla/config\"", ",", "data", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "device", "=", "registry", ".", "async_get_device", "(", "{", "(", "\"mqtt\"", ",", "\"helloworld\"", ")", "}", ",", "set", "(", ")", ")", "assert", "device", "is", "not", "None", "debug_info_data", "=", "await", "debug_info", ".", "info_for_device", "(", "hass", ",", "device", ".", "id", ")", "assert", "len", "(", "debug_info_data", "[", "\"entities\"", "]", "[", "0", "]", "[", "\"subscriptions\"", "]", ")", ">=", "1", "assert", "{", "\"topic\"", ":", "\"sensor/#\"", ",", "\"messages\"", ":", "[", "]", "}", "in", "debug_info_data", "[", "\"entities\"", "]", "[", "0", "]", "[", "\"subscriptions\"", "]", "start_dt", "=", "datetime", "(", "2019", ",", "1", ",", "1", ",", "0", ",", "0", ",", "0", ")", "with", "patch", "(", "\"homeassistant.util.dt.utcnow\"", ")", "as", "dt_utcnow", ":", "dt_utcnow", ".", "return_value", "=", "start_dt", "async_fire_mqtt_message", "(", "hass", ",", "\"sensor/abc\"", ",", "\"123\"", ")", "debug_info_data", "=", "await", "debug_info", ".", "info_for_device", "(", "hass", ",", "device", ".", "id", ")", "assert", "len", "(", "debug_info_data", "[", "\"entities\"", "]", "[", "0", "]", "[", "\"subscriptions\"", "]", ")", ">=", "1", "assert", "{", "\"topic\"", ":", "\"sensor/#\"", ",", "\"messages\"", ":", "[", "{", "\"payload\"", ":", "\"123\"", ",", "\"qos\"", ":", "0", ",", "\"retain\"", ":", "False", ",", "\"time\"", ":", "start_dt", ",", "\"topic\"", ":", "\"sensor/abc\"", ",", "}", "]", ",", "}", "in", "debug_info_data", "[", "\"entities\"", "]", "[", "0", "]", "[", "\"subscriptions\"", "]" ]
[ 1288, 0 ]
[ 1331, 56 ]
python
ceb
['fr', 'ceb', 'nl']
False
test_debug_info_filter_same
(hass, mqtt_mock)
Test debug info removes messages with same timestamp.
Test debug info removes messages with same timestamp.
async def test_debug_info_filter_same(hass, mqtt_mock): """Test debug info removes messages with same timestamp.""" config = { "device": {"identifiers": ["helloworld"]}, "platform": "mqtt", "name": "test", "state_topic": "sensor/#", "unique_id": "veryunique", } registry = await hass.helpers.device_registry.async_get_registry() data = json.dumps(config) async_fire_mqtt_message(hass, "homeassistant/sensor/bla/config", data) await hass.async_block_till_done() device = registry.async_get_device({("mqtt", "helloworld")}, set()) assert device is not None debug_info_data = await debug_info.info_for_device(hass, device.id) assert len(debug_info_data["entities"][0]["subscriptions"]) >= 1 assert {"topic": "sensor/#", "messages": []} in debug_info_data["entities"][0][ "subscriptions" ] dt1 = datetime(2019, 1, 1, 0, 0, 0) dt2 = datetime(2019, 1, 1, 0, 0, 1) with patch("homeassistant.util.dt.utcnow") as dt_utcnow: dt_utcnow.return_value = dt1 async_fire_mqtt_message(hass, "sensor/abc", "123") async_fire_mqtt_message(hass, "sensor/abc", "123") dt_utcnow.return_value = dt2 async_fire_mqtt_message(hass, "sensor/abc", "123") debug_info_data = await debug_info.info_for_device(hass, device.id) assert len(debug_info_data["entities"][0]["subscriptions"]) == 1 assert len(debug_info_data["entities"][0]["subscriptions"][0]["messages"]) == 2 assert { "topic": "sensor/#", "messages": [ { "payload": "123", "qos": 0, "retain": False, "time": dt1, "topic": "sensor/abc", }, { "payload": "123", "qos": 0, "retain": False, "time": dt2, "topic": "sensor/abc", }, ], } == debug_info_data["entities"][0]["subscriptions"][0]
[ "async", "def", "test_debug_info_filter_same", "(", "hass", ",", "mqtt_mock", ")", ":", "config", "=", "{", "\"device\"", ":", "{", "\"identifiers\"", ":", "[", "\"helloworld\"", "]", "}", ",", "\"platform\"", ":", "\"mqtt\"", ",", "\"name\"", ":", "\"test\"", ",", "\"state_topic\"", ":", "\"sensor/#\"", ",", "\"unique_id\"", ":", "\"veryunique\"", ",", "}", "registry", "=", "await", "hass", ".", "helpers", ".", "device_registry", ".", "async_get_registry", "(", ")", "data", "=", "json", ".", "dumps", "(", "config", ")", "async_fire_mqtt_message", "(", "hass", ",", "\"homeassistant/sensor/bla/config\"", ",", "data", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "device", "=", "registry", ".", "async_get_device", "(", "{", "(", "\"mqtt\"", ",", "\"helloworld\"", ")", "}", ",", "set", "(", ")", ")", "assert", "device", "is", "not", "None", "debug_info_data", "=", "await", "debug_info", ".", "info_for_device", "(", "hass", ",", "device", ".", "id", ")", "assert", "len", "(", "debug_info_data", "[", "\"entities\"", "]", "[", "0", "]", "[", "\"subscriptions\"", "]", ")", ">=", "1", "assert", "{", "\"topic\"", ":", "\"sensor/#\"", ",", "\"messages\"", ":", "[", "]", "}", "in", "debug_info_data", "[", "\"entities\"", "]", "[", "0", "]", "[", "\"subscriptions\"", "]", "dt1", "=", "datetime", "(", "2019", ",", "1", ",", "1", ",", "0", ",", "0", ",", "0", ")", "dt2", "=", "datetime", "(", "2019", ",", "1", ",", "1", ",", "0", ",", "0", ",", "1", ")", "with", "patch", "(", "\"homeassistant.util.dt.utcnow\"", ")", "as", "dt_utcnow", ":", "dt_utcnow", ".", "return_value", "=", "dt1", "async_fire_mqtt_message", "(", "hass", ",", "\"sensor/abc\"", ",", "\"123\"", ")", "async_fire_mqtt_message", "(", "hass", ",", "\"sensor/abc\"", ",", "\"123\"", ")", "dt_utcnow", ".", "return_value", "=", "dt2", "async_fire_mqtt_message", "(", "hass", ",", "\"sensor/abc\"", ",", "\"123\"", ")", "debug_info_data", "=", "await", "debug_info", ".", "info_for_device", "(", "hass", ",", "device", ".", "id", ")", "assert", "len", "(", "debug_info_data", "[", "\"entities\"", "]", "[", "0", "]", "[", "\"subscriptions\"", "]", ")", "==", "1", "assert", "len", "(", "debug_info_data", "[", "\"entities\"", "]", "[", "0", "]", "[", "\"subscriptions\"", "]", "[", "0", "]", "[", "\"messages\"", "]", ")", "==", "2", "assert", "{", "\"topic\"", ":", "\"sensor/#\"", ",", "\"messages\"", ":", "[", "{", "\"payload\"", ":", "\"123\"", ",", "\"qos\"", ":", "0", ",", "\"retain\"", ":", "False", ",", "\"time\"", ":", "dt1", ",", "\"topic\"", ":", "\"sensor/abc\"", ",", "}", ",", "{", "\"payload\"", ":", "\"123\"", ",", "\"qos\"", ":", "0", ",", "\"retain\"", ":", "False", ",", "\"time\"", ":", "dt2", ",", "\"topic\"", ":", "\"sensor/abc\"", ",", "}", ",", "]", ",", "}", "==", "debug_info_data", "[", "\"entities\"", "]", "[", "0", "]", "[", "\"subscriptions\"", "]", "[", "0", "]" ]
[ 1334, 0 ]
[ 1389, 59 ]
python
en
['en', 'da', 'en']
True
test_debug_info_same_topic
(hass, mqtt_mock)
Test debug info.
Test debug info.
async def test_debug_info_same_topic(hass, mqtt_mock): """Test debug info.""" config = { "device": {"identifiers": ["helloworld"]}, "platform": "mqtt", "name": "test", "state_topic": "sensor/status", "availability_topic": "sensor/status", "unique_id": "veryunique", } registry = await hass.helpers.device_registry.async_get_registry() data = json.dumps(config) async_fire_mqtt_message(hass, "homeassistant/sensor/bla/config", data) await hass.async_block_till_done() device = registry.async_get_device({("mqtt", "helloworld")}, set()) assert device is not None debug_info_data = await debug_info.info_for_device(hass, device.id) assert len(debug_info_data["entities"][0]["subscriptions"]) >= 1 assert {"topic": "sensor/status", "messages": []} in debug_info_data["entities"][0][ "subscriptions" ] start_dt = datetime(2019, 1, 1, 0, 0, 0) with patch("homeassistant.util.dt.utcnow") as dt_utcnow: dt_utcnow.return_value = start_dt async_fire_mqtt_message(hass, "sensor/status", "123", qos=0, retain=False) debug_info_data = await debug_info.info_for_device(hass, device.id) assert len(debug_info_data["entities"][0]["subscriptions"]) == 1 assert { "payload": "123", "qos": 0, "retain": False, "time": start_dt, "topic": "sensor/status", } in debug_info_data["entities"][0]["subscriptions"][0]["messages"] config["availability_topic"] = "sensor/availability" data = json.dumps(config) async_fire_mqtt_message(hass, "homeassistant/sensor/bla/config", data) await hass.async_block_till_done() start_dt = datetime(2019, 1, 1, 0, 0, 0) with patch("homeassistant.util.dt.utcnow") as dt_utcnow: dt_utcnow.return_value = start_dt async_fire_mqtt_message(hass, "sensor/status", "123", qos=0, retain=False)
[ "async", "def", "test_debug_info_same_topic", "(", "hass", ",", "mqtt_mock", ")", ":", "config", "=", "{", "\"device\"", ":", "{", "\"identifiers\"", ":", "[", "\"helloworld\"", "]", "}", ",", "\"platform\"", ":", "\"mqtt\"", ",", "\"name\"", ":", "\"test\"", ",", "\"state_topic\"", ":", "\"sensor/status\"", ",", "\"availability_topic\"", ":", "\"sensor/status\"", ",", "\"unique_id\"", ":", "\"veryunique\"", ",", "}", "registry", "=", "await", "hass", ".", "helpers", ".", "device_registry", ".", "async_get_registry", "(", ")", "data", "=", "json", ".", "dumps", "(", "config", ")", "async_fire_mqtt_message", "(", "hass", ",", "\"homeassistant/sensor/bla/config\"", ",", "data", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "device", "=", "registry", ".", "async_get_device", "(", "{", "(", "\"mqtt\"", ",", "\"helloworld\"", ")", "}", ",", "set", "(", ")", ")", "assert", "device", "is", "not", "None", "debug_info_data", "=", "await", "debug_info", ".", "info_for_device", "(", "hass", ",", "device", ".", "id", ")", "assert", "len", "(", "debug_info_data", "[", "\"entities\"", "]", "[", "0", "]", "[", "\"subscriptions\"", "]", ")", ">=", "1", "assert", "{", "\"topic\"", ":", "\"sensor/status\"", ",", "\"messages\"", ":", "[", "]", "}", "in", "debug_info_data", "[", "\"entities\"", "]", "[", "0", "]", "[", "\"subscriptions\"", "]", "start_dt", "=", "datetime", "(", "2019", ",", "1", ",", "1", ",", "0", ",", "0", ",", "0", ")", "with", "patch", "(", "\"homeassistant.util.dt.utcnow\"", ")", "as", "dt_utcnow", ":", "dt_utcnow", ".", "return_value", "=", "start_dt", "async_fire_mqtt_message", "(", "hass", ",", "\"sensor/status\"", ",", "\"123\"", ",", "qos", "=", "0", ",", "retain", "=", "False", ")", "debug_info_data", "=", "await", "debug_info", ".", "info_for_device", "(", "hass", ",", "device", ".", "id", ")", "assert", "len", "(", "debug_info_data", "[", "\"entities\"", "]", "[", "0", "]", "[", "\"subscriptions\"", "]", ")", "==", "1", "assert", "{", "\"payload\"", ":", "\"123\"", ",", "\"qos\"", ":", "0", ",", "\"retain\"", ":", "False", ",", "\"time\"", ":", "start_dt", ",", "\"topic\"", ":", "\"sensor/status\"", ",", "}", "in", "debug_info_data", "[", "\"entities\"", "]", "[", "0", "]", "[", "\"subscriptions\"", "]", "[", "0", "]", "[", "\"messages\"", "]", "config", "[", "\"availability_topic\"", "]", "=", "\"sensor/availability\"", "data", "=", "json", ".", "dumps", "(", "config", ")", "async_fire_mqtt_message", "(", "hass", ",", "\"homeassistant/sensor/bla/config\"", ",", "data", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "start_dt", "=", "datetime", "(", "2019", ",", "1", ",", "1", ",", "0", ",", "0", ",", "0", ")", "with", "patch", "(", "\"homeassistant.util.dt.utcnow\"", ")", "as", "dt_utcnow", ":", "dt_utcnow", ".", "return_value", "=", "start_dt", "async_fire_mqtt_message", "(", "hass", ",", "\"sensor/status\"", ",", "\"123\"", ",", "qos", "=", "0", ",", "retain", "=", "False", ")" ]
[ 1392, 0 ]
[ 1441, 82 ]
python
ceb
['fr', 'ceb', 'nl']
False
test_debug_info_qos_retain
(hass, mqtt_mock)
Test debug info.
Test debug info.
async def test_debug_info_qos_retain(hass, mqtt_mock): """Test debug info.""" config = { "device": {"identifiers": ["helloworld"]}, "platform": "mqtt", "name": "test", "state_topic": "sensor/#", "unique_id": "veryunique", } registry = await hass.helpers.device_registry.async_get_registry() data = json.dumps(config) async_fire_mqtt_message(hass, "homeassistant/sensor/bla/config", data) await hass.async_block_till_done() device = registry.async_get_device({("mqtt", "helloworld")}, set()) assert device is not None debug_info_data = await debug_info.info_for_device(hass, device.id) assert len(debug_info_data["entities"][0]["subscriptions"]) >= 1 assert {"topic": "sensor/#", "messages": []} in debug_info_data["entities"][0][ "subscriptions" ] start_dt = datetime(2019, 1, 1, 0, 0, 0) with patch("homeassistant.util.dt.utcnow") as dt_utcnow: dt_utcnow.return_value = start_dt async_fire_mqtt_message(hass, "sensor/abc", "123", qos=0, retain=False) async_fire_mqtt_message(hass, "sensor/abc", "123", qos=1, retain=True) async_fire_mqtt_message(hass, "sensor/abc", "123", qos=2, retain=False) debug_info_data = await debug_info.info_for_device(hass, device.id) assert len(debug_info_data["entities"][0]["subscriptions"]) == 1 assert { "payload": "123", "qos": 0, "retain": False, "time": start_dt, "topic": "sensor/abc", } in debug_info_data["entities"][0]["subscriptions"][0]["messages"] assert { "payload": "123", "qos": 1, "retain": True, "time": start_dt, "topic": "sensor/abc", } in debug_info_data["entities"][0]["subscriptions"][0]["messages"] assert { "payload": "123", "qos": 2, "retain": False, "time": start_dt, "topic": "sensor/abc", } in debug_info_data["entities"][0]["subscriptions"][0]["messages"]
[ "async", "def", "test_debug_info_qos_retain", "(", "hass", ",", "mqtt_mock", ")", ":", "config", "=", "{", "\"device\"", ":", "{", "\"identifiers\"", ":", "[", "\"helloworld\"", "]", "}", ",", "\"platform\"", ":", "\"mqtt\"", ",", "\"name\"", ":", "\"test\"", ",", "\"state_topic\"", ":", "\"sensor/#\"", ",", "\"unique_id\"", ":", "\"veryunique\"", ",", "}", "registry", "=", "await", "hass", ".", "helpers", ".", "device_registry", ".", "async_get_registry", "(", ")", "data", "=", "json", ".", "dumps", "(", "config", ")", "async_fire_mqtt_message", "(", "hass", ",", "\"homeassistant/sensor/bla/config\"", ",", "data", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "device", "=", "registry", ".", "async_get_device", "(", "{", "(", "\"mqtt\"", ",", "\"helloworld\"", ")", "}", ",", "set", "(", ")", ")", "assert", "device", "is", "not", "None", "debug_info_data", "=", "await", "debug_info", ".", "info_for_device", "(", "hass", ",", "device", ".", "id", ")", "assert", "len", "(", "debug_info_data", "[", "\"entities\"", "]", "[", "0", "]", "[", "\"subscriptions\"", "]", ")", ">=", "1", "assert", "{", "\"topic\"", ":", "\"sensor/#\"", ",", "\"messages\"", ":", "[", "]", "}", "in", "debug_info_data", "[", "\"entities\"", "]", "[", "0", "]", "[", "\"subscriptions\"", "]", "start_dt", "=", "datetime", "(", "2019", ",", "1", ",", "1", ",", "0", ",", "0", ",", "0", ")", "with", "patch", "(", "\"homeassistant.util.dt.utcnow\"", ")", "as", "dt_utcnow", ":", "dt_utcnow", ".", "return_value", "=", "start_dt", "async_fire_mqtt_message", "(", "hass", ",", "\"sensor/abc\"", ",", "\"123\"", ",", "qos", "=", "0", ",", "retain", "=", "False", ")", "async_fire_mqtt_message", "(", "hass", ",", "\"sensor/abc\"", ",", "\"123\"", ",", "qos", "=", "1", ",", "retain", "=", "True", ")", "async_fire_mqtt_message", "(", "hass", ",", "\"sensor/abc\"", ",", "\"123\"", ",", "qos", "=", "2", ",", "retain", "=", "False", ")", "debug_info_data", "=", "await", "debug_info", ".", "info_for_device", "(", "hass", ",", "device", ".", "id", ")", "assert", "len", "(", "debug_info_data", "[", "\"entities\"", "]", "[", "0", "]", "[", "\"subscriptions\"", "]", ")", "==", "1", "assert", "{", "\"payload\"", ":", "\"123\"", ",", "\"qos\"", ":", "0", ",", "\"retain\"", ":", "False", ",", "\"time\"", ":", "start_dt", ",", "\"topic\"", ":", "\"sensor/abc\"", ",", "}", "in", "debug_info_data", "[", "\"entities\"", "]", "[", "0", "]", "[", "\"subscriptions\"", "]", "[", "0", "]", "[", "\"messages\"", "]", "assert", "{", "\"payload\"", ":", "\"123\"", ",", "\"qos\"", ":", "1", ",", "\"retain\"", ":", "True", ",", "\"time\"", ":", "start_dt", ",", "\"topic\"", ":", "\"sensor/abc\"", ",", "}", "in", "debug_info_data", "[", "\"entities\"", "]", "[", "0", "]", "[", "\"subscriptions\"", "]", "[", "0", "]", "[", "\"messages\"", "]", "assert", "{", "\"payload\"", ":", "\"123\"", ",", "\"qos\"", ":", "2", ",", "\"retain\"", ":", "False", ",", "\"time\"", ":", "start_dt", ",", "\"topic\"", ":", "\"sensor/abc\"", ",", "}", "in", "debug_info_data", "[", "\"entities\"", "]", "[", "0", "]", "[", "\"subscriptions\"", "]", "[", "0", "]", "[", "\"messages\"", "]" ]
[ 1444, 0 ]
[ 1498, 71 ]
python
ceb
['fr', 'ceb', 'nl']
False
test_publish_json_from_template
(hass, mqtt_mock)
Test the publishing of call to services.
Test the publishing of call to services.
async def test_publish_json_from_template(hass, mqtt_mock): """Test the publishing of call to services.""" test_str = "{'valid': 'python', 'invalid': 'json'}" test_str_tpl = "{'valid': '{{ \"python\" }}', 'invalid': 'json'}" await async_setup_component( hass, "script", { "script": { "test_script_payload": { "sequence": { "service": "mqtt.publish", "data": {"topic": "test-topic", "payload": test_str_tpl}, } }, "test_script_payload_template": { "sequence": { "service": "mqtt.publish", "data": { "topic": "test-topic", "payload_template": test_str_tpl, }, } }, } }, ) await hass.services.async_call("script", "test_script_payload", blocking=True) await hass.async_block_till_done() assert mqtt_mock.async_publish.called assert mqtt_mock.async_publish.call_args[0][1] == test_str mqtt_mock.async_publish.reset_mock() assert not mqtt_mock.async_publish.called await hass.services.async_call( "script", "test_script_payload_template", blocking=True ) await hass.async_block_till_done() assert mqtt_mock.async_publish.called assert mqtt_mock.async_publish.call_args[0][1] == test_str
[ "async", "def", "test_publish_json_from_template", "(", "hass", ",", "mqtt_mock", ")", ":", "test_str", "=", "\"{'valid': 'python', 'invalid': 'json'}\"", "test_str_tpl", "=", "\"{'valid': '{{ \\\"python\\\" }}', 'invalid': 'json'}\"", "await", "async_setup_component", "(", "hass", ",", "\"script\"", ",", "{", "\"script\"", ":", "{", "\"test_script_payload\"", ":", "{", "\"sequence\"", ":", "{", "\"service\"", ":", "\"mqtt.publish\"", ",", "\"data\"", ":", "{", "\"topic\"", ":", "\"test-topic\"", ",", "\"payload\"", ":", "test_str_tpl", "}", ",", "}", "}", ",", "\"test_script_payload_template\"", ":", "{", "\"sequence\"", ":", "{", "\"service\"", ":", "\"mqtt.publish\"", ",", "\"data\"", ":", "{", "\"topic\"", ":", "\"test-topic\"", ",", "\"payload_template\"", ":", "test_str_tpl", ",", "}", ",", "}", "}", ",", "}", "}", ",", ")", "await", "hass", ".", "services", ".", "async_call", "(", "\"script\"", ",", "\"test_script_payload\"", ",", "blocking", "=", "True", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "mqtt_mock", ".", "async_publish", ".", "called", "assert", "mqtt_mock", ".", "async_publish", ".", "call_args", "[", "0", "]", "[", "1", "]", "==", "test_str", "mqtt_mock", ".", "async_publish", ".", "reset_mock", "(", ")", "assert", "not", "mqtt_mock", ".", "async_publish", ".", "called", "await", "hass", ".", "services", ".", "async_call", "(", "\"script\"", ",", "\"test_script_payload_template\"", ",", "blocking", "=", "True", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "mqtt_mock", ".", "async_publish", ".", "called", "assert", "mqtt_mock", ".", "async_publish", ".", "call_args", "[", "0", "]", "[", "1", "]", "==", "test_str" ]
[ 1501, 0 ]
[ 1545, 62 ]
python
en
['en', 'en', 'en']
True
PrefixBeamSearch.run
(self, log_probs: np.ndarray, n_best=None, return_ids=False)
Return n_best results from prefix beam decode. If the n_best=1, then we will collapse the singleton dim :param log_probs: The log probabilities :param n_best: The number of results to return, defaults to beam size :param return_ids: Whether to return the raw ids or the characters :return: A list of transcriptions if 1 best, otherwise A list of n-bests of transcriptions
Return n_best results from prefix beam decode. If the n_best=1, then we will collapse the singleton dim
def run(self, log_probs: np.ndarray, n_best=None, return_ids=False): """Return n_best results from prefix beam decode. If the n_best=1, then we will collapse the singleton dim :param log_probs: The log probabilities :param n_best: The number of results to return, defaults to beam size :param return_ids: Whether to return the raw ids or the characters :return: A list of transcriptions if 1 best, otherwise A list of n-bests of transcriptions """ B = log_probs.shape[0] if n_best == None: n_best = self.beam beam_results, beam_scores, timesteps, out_lens = self.ctc_decoder.decode(log_probs) def transform_ids(t): return t if return_ids else (self.vocab_list[t] if t != self.bar_off else '|') transcriptions = [] if n_best == 1: for b in range(B): transcription = [transform_ids(t) for t in beam_results[b][0][: out_lens[b][0]]] transcriptions.append(transcription) else: for b in range(B): n_bests = [] for n in range(n_best): n_best = [transform_ids(t) for t in beam_results[b][n][: out_lens[b][n]]] n_bests.append(n_best) transcriptions.append(n_bests) return transcriptions
[ "def", "run", "(", "self", ",", "log_probs", ":", "np", ".", "ndarray", ",", "n_best", "=", "None", ",", "return_ids", "=", "False", ")", ":", "B", "=", "log_probs", ".", "shape", "[", "0", "]", "if", "n_best", "==", "None", ":", "n_best", "=", "self", ".", "beam", "beam_results", ",", "beam_scores", ",", "timesteps", ",", "out_lens", "=", "self", ".", "ctc_decoder", ".", "decode", "(", "log_probs", ")", "def", "transform_ids", "(", "t", ")", ":", "return", "t", "if", "return_ids", "else", "(", "self", ".", "vocab_list", "[", "t", "]", "if", "t", "!=", "self", ".", "bar_off", "else", "'|'", ")", "transcriptions", "=", "[", "]", "if", "n_best", "==", "1", ":", "for", "b", "in", "range", "(", "B", ")", ":", "transcription", "=", "[", "transform_ids", "(", "t", ")", "for", "t", "in", "beam_results", "[", "b", "]", "[", "0", "]", "[", ":", "out_lens", "[", "b", "]", "[", "0", "]", "]", "]", "transcriptions", ".", "append", "(", "transcription", ")", "else", ":", "for", "b", "in", "range", "(", "B", ")", ":", "n_bests", "=", "[", "]", "for", "n", "in", "range", "(", "n_best", ")", ":", "n_best", "=", "[", "transform_ids", "(", "t", ")", "for", "t", "in", "beam_results", "[", "b", "]", "[", "n", "]", "[", ":", "out_lens", "[", "b", "]", "[", "n", "]", "]", "]", "n_bests", ".", "append", "(", "n_best", ")", "transcriptions", ".", "append", "(", "n_bests", ")", "return", "transcriptions" ]
[ 31, 4 ]
[ 59, 29 ]
python
en
['en', 'en', 'en']
True
User.alt_emails
(self)
Get list of non-primary emails associated with google ID.
Get list of non-primary emails associated with google ID.
def alt_emails(self): """Get list of non-primary emails associated with google ID.""" if not self.alt_email_str: return [] return self.alt_email_str.split(',')
[ "def", "alt_emails", "(", "self", ")", ":", "if", "not", "self", ".", "alt_email_str", ":", "return", "[", "]", "return", "self", ".", "alt_email_str", ".", "split", "(", "','", ")" ]
[ 28, 4 ]
[ 32, 44 ]
python
en
['en', 'en', 'en']
True
User.known_emails
(self)
Get set of all known emails for this user.
Get set of all known emails for this user.
def known_emails(self): """Get set of all known emails for this user.""" name_emails = {i for i in name_dict if name_dict[i] == self.use_name} return {self.email}.union(set(self.alt_emails)).union(name_emails)
[ "def", "known_emails", "(", "self", ")", ":", "name_emails", "=", "{", "i", "for", "i", "in", "name_dict", "if", "name_dict", "[", "i", "]", "==", "self", ".", "use_name", "}", "return", "{", "self", ".", "email", "}", ".", "union", "(", "set", "(", "self", ".", "alt_emails", ")", ")", ".", "union", "(", "name_emails", ")" ]
[ 43, 4 ]
[ 46, 74 ]
python
en
['en', 'en', 'en']
True
def_train_opt
(p)
Return the default optimizer.
Return the default optimizer.
def def_train_opt(p): """ Return the default optimizer. """ return torch.optim.Adam(p, 1e-1, amsgrad=False)
[ "def", "def_train_opt", "(", "p", ")", ":", "return", "torch", ".", "optim", ".", "Adam", "(", "p", ",", "1e-1", ",", "amsgrad", "=", "False", ")" ]
[ 35, 0 ]
[ 39, 51 ]
python
en
['en', 'error', 'th']
False
revcumsum
(U)
Reverse cumulative sum for faster performance.
Reverse cumulative sum for faster performance.
def revcumsum(U): """ Reverse cumulative sum for faster performance. """ return U.flip(dims=[0]).cumsum(dim=0).flip(dims=[0])
[ "def", "revcumsum", "(", "U", ")", ":", "return", "U", ".", "flip", "(", "dims", "=", "[", "0", "]", ")", ".", "cumsum", "(", "dim", "=", "0", ")", ".", "flip", "(", "dims", "=", "[", "0", "]", ")" ]
[ 42, 0 ]
[ 46, 56 ]
python
en
['en', 'error', 'th']
False
LearnabilityMB.ret_val
(self, z)
Get the return value based on z.
Get the return value based on z.
def ret_val(self, z): """ Get the return value based on z. """ if not self.binary: return 1 - z else: return 0.5 * (1 - safesqrt.apply(ramp.apply(z)))
[ "def", "ret_val", "(", "self", ",", "z", ")", ":", "if", "not", "self", ".", "binary", ":", "return", "1", "-", "z", "else", ":", "return", "0.5", "*", "(", "1", "-", "safesqrt", ".", "apply", "(", "ramp", ".", "apply", "(", "z", ")", ")", ")" ]
[ 126, 4 ]
[ 135, 60 ]
python
en
['en', 'error', 'th']
False
Solver.__init__
(self, PreparedData, order, Nminibatch=None, groups=None, soft_groups=None, x0=None, C=1, ftransform=torch.sigmoid, get_train_opt=def_train_opt, accum_steps=1, rng=np.random.RandomState(0), max_norm_clip=1., shuffle=True, device=constants.Device.CPU, verbose=1)
Parameters ---------- PreparedData : Dataset of PrepareData class order : int What order of interactions to include. Higher orders may be more accurate but increase the run time. 12 is the maximum allowed order. Nminibatch : int Number of rows in a mini batch groups : array-like Optional, shape = [n_features] Groups of columns that must be selected as a unit e.g. [0, 0, 1, 2] specifies the first two columns are part of a group. soft_groups : array-like optional, shape = [n_features] Groups of columns come from the same source Used to encourage sparsity of number of sources selected e.g. [0, 0, 1, 2] specifies the first two columns are part of a group. x0 : torch.tensor Optional, initialization of x. C : float Penalty parameter. get_train_opt : function Function that returns a pytorch optimizer, Adam is the default accum_steps : int Number of steps rng : random state max_norm_clip : float Maximum allowable size of the gradient shuffle : bool Whether or not to shuffle data within the dataloader order : int What order of interactions to include. Higher orders may be more accurate but increase the run time. 12 is the maximum allowed order. penalty : int Constant that multiplies the regularization term. ftransform : function Function to transform the x. sigmoid is the default. device : str 'cpu' to run on CPU and 'cuda' to run on GPU. Runs much faster on GPU verbose : int Controls the verbosity when fitting. Set to 0 for no printing 1 or higher for printing every verbose number of gradient steps.
def __init__(self, PreparedData, order, Nminibatch=None, groups=None, soft_groups=None, x0=None, C=1, ftransform=torch.sigmoid, get_train_opt=def_train_opt, accum_steps=1, rng=np.random.RandomState(0), max_norm_clip=1., shuffle=True, device=constants.Device.CPU, verbose=1): """ Parameters ---------- PreparedData : Dataset of PrepareData class order : int What order of interactions to include. Higher orders may be more accurate but increase the run time. 12 is the maximum allowed order. Nminibatch : int Number of rows in a mini batch groups : array-like Optional, shape = [n_features] Groups of columns that must be selected as a unit e.g. [0, 0, 1, 2] specifies the first two columns are part of a group. soft_groups : array-like optional, shape = [n_features] Groups of columns come from the same source Used to encourage sparsity of number of sources selected e.g. [0, 0, 1, 2] specifies the first two columns are part of a group. x0 : torch.tensor Optional, initialization of x. C : float Penalty parameter. get_train_opt : function Function that returns a pytorch optimizer, Adam is the default accum_steps : int Number of steps rng : random state max_norm_clip : float Maximum allowable size of the gradient shuffle : bool Whether or not to shuffle data within the dataloader order : int What order of interactions to include. Higher orders may be more accurate but increase the run time. 12 is the maximum allowed order. penalty : int Constant that multiplies the regularization term. ftransform : function Function to transform the x. sigmoid is the default. device : str 'cpu' to run on CPU and 'cuda' to run on GPU. Runs much faster on GPU verbose : int Controls the verbosity when fitting. Set to 0 for no printing 1 or higher for printing every verbose number of gradient steps. """ super(Solver, self).__init__() self.Ntrain, self.D = PreparedData.N, PreparedData.n_features if groups is not None: # pylint: disable=E1102 groups = torch.tensor(groups, dtype=torch.long) self.groups = groups else: self.groups = None if soft_groups is not None: # pylint: disable=E1102 soft_groups = torch.tensor(soft_groups, dtype=torch.long) self.soft_D = torch.unique(soft_groups).size()[0] else: self.soft_D = None self.soft_groups = soft_groups if Nminibatch is None: Nminibatch = self.Ntrain else: if Nminibatch > self.Ntrain: print('Minibatch larger than sample size.' + (' Reducing from %d to %d.' % (Nminibatch, self.Ntrain))) Nminibatch = self.Ntrain if Nminibatch > PreparedData.max_rows: print('Minibatch larger than mem-allowed.' + (' Reducing from %d to %d.' % (Nminibatch, PreparedData.max_rows))) Nminibatch = int(np.min([Nminibatch, PreparedData.max_rows])) self.Nminibatch = Nminibatch self.accum_steps = accum_steps if x0 is None: x0 = torch.zeros(self.D, 1, dtype=torch.get_default_dtype()) self.ftransform = ftransform self.x = nn.Parameter(x0) self.max_norm = max_norm_clip self.device = device self.verbose = verbose self.multiclass = PreparedData.classification and PreparedData.n_classes and PreparedData.n_classes > 2 if self.multiclass: self.n_classes = PreparedData.n_classes else: self.n_classes = None # whether to treat all classes equally self.balanced = PreparedData.balanced self.ordinal = PreparedData.ordinal if (hasattr(PreparedData, 'mappings') or PreparedData.storage_level == 'disk'): num_workers = PreparedData.num_workers elif PreparedData.storage_level == constants.StorageLevel.DENSE: num_workers = 0 else: num_workers = 0 if constants.Device.CUDA in device: pin_memory = False else: pin_memory = False if num_workers == 0: timeout = 0 else: timeout = 60 self.ds_train = ChunkDataLoader( PreparedData, batch_size=self.Nminibatch, shuffle=shuffle, drop_last=True, num_workers=num_workers, pin_memory=pin_memory, timeout=timeout) self.f_train = LearnabilityMB(self.Nminibatch, self.D, constants.Coefficients.SLE[order], self.groups, binary=PreparedData.classification, device=self.device) self.opt_train = get_train_opt(torch.nn.ParameterList([self.x])) self.it = 0 self.iters_per_epoch = int(np.ceil(len(self.ds_train.dataset) / self.ds_train.batch_size)) self.f_train = self.f_train.to(device) # pylint: disable=E1102 self.w = torch.tensor( C / (C + 1), dtype=torch.get_default_dtype(), requires_grad=False) self.w = self.w.to(device)
[ "def", "__init__", "(", "self", ",", "PreparedData", ",", "order", ",", "Nminibatch", "=", "None", ",", "groups", "=", "None", ",", "soft_groups", "=", "None", ",", "x0", "=", "None", ",", "C", "=", "1", ",", "ftransform", "=", "torch", ".", "sigmoid", ",", "get_train_opt", "=", "def_train_opt", ",", "accum_steps", "=", "1", ",", "rng", "=", "np", ".", "random", ".", "RandomState", "(", "0", ")", ",", "max_norm_clip", "=", "1.", ",", "shuffle", "=", "True", ",", "device", "=", "constants", ".", "Device", ".", "CPU", ",", "verbose", "=", "1", ")", ":", "super", "(", "Solver", ",", "self", ")", ".", "__init__", "(", ")", "self", ".", "Ntrain", ",", "self", ".", "D", "=", "PreparedData", ".", "N", ",", "PreparedData", ".", "n_features", "if", "groups", "is", "not", "None", ":", "# pylint: disable=E1102", "groups", "=", "torch", ".", "tensor", "(", "groups", ",", "dtype", "=", "torch", ".", "long", ")", "self", ".", "groups", "=", "groups", "else", ":", "self", ".", "groups", "=", "None", "if", "soft_groups", "is", "not", "None", ":", "# pylint: disable=E1102", "soft_groups", "=", "torch", ".", "tensor", "(", "soft_groups", ",", "dtype", "=", "torch", ".", "long", ")", "self", ".", "soft_D", "=", "torch", ".", "unique", "(", "soft_groups", ")", ".", "size", "(", ")", "[", "0", "]", "else", ":", "self", ".", "soft_D", "=", "None", "self", ".", "soft_groups", "=", "soft_groups", "if", "Nminibatch", "is", "None", ":", "Nminibatch", "=", "self", ".", "Ntrain", "else", ":", "if", "Nminibatch", ">", "self", ".", "Ntrain", ":", "print", "(", "'Minibatch larger than sample size.'", "+", "(", "' Reducing from %d to %d.'", "%", "(", "Nminibatch", ",", "self", ".", "Ntrain", ")", ")", ")", "Nminibatch", "=", "self", ".", "Ntrain", "if", "Nminibatch", ">", "PreparedData", ".", "max_rows", ":", "print", "(", "'Minibatch larger than mem-allowed.'", "+", "(", "' Reducing from %d to %d.'", "%", "(", "Nminibatch", ",", "PreparedData", ".", "max_rows", ")", ")", ")", "Nminibatch", "=", "int", "(", "np", ".", "min", "(", "[", "Nminibatch", ",", "PreparedData", ".", "max_rows", "]", ")", ")", "self", ".", "Nminibatch", "=", "Nminibatch", "self", ".", "accum_steps", "=", "accum_steps", "if", "x0", "is", "None", ":", "x0", "=", "torch", ".", "zeros", "(", "self", ".", "D", ",", "1", ",", "dtype", "=", "torch", ".", "get_default_dtype", "(", ")", ")", "self", ".", "ftransform", "=", "ftransform", "self", ".", "x", "=", "nn", ".", "Parameter", "(", "x0", ")", "self", ".", "max_norm", "=", "max_norm_clip", "self", ".", "device", "=", "device", "self", ".", "verbose", "=", "verbose", "self", ".", "multiclass", "=", "PreparedData", ".", "classification", "and", "PreparedData", ".", "n_classes", "and", "PreparedData", ".", "n_classes", ">", "2", "if", "self", ".", "multiclass", ":", "self", ".", "n_classes", "=", "PreparedData", ".", "n_classes", "else", ":", "self", ".", "n_classes", "=", "None", "# whether to treat all classes equally", "self", ".", "balanced", "=", "PreparedData", ".", "balanced", "self", ".", "ordinal", "=", "PreparedData", ".", "ordinal", "if", "(", "hasattr", "(", "PreparedData", ",", "'mappings'", ")", "or", "PreparedData", ".", "storage_level", "==", "'disk'", ")", ":", "num_workers", "=", "PreparedData", ".", "num_workers", "elif", "PreparedData", ".", "storage_level", "==", "constants", ".", "StorageLevel", ".", "DENSE", ":", "num_workers", "=", "0", "else", ":", "num_workers", "=", "0", "if", "constants", ".", "Device", ".", "CUDA", "in", "device", ":", "pin_memory", "=", "False", "else", ":", "pin_memory", "=", "False", "if", "num_workers", "==", "0", ":", "timeout", "=", "0", "else", ":", "timeout", "=", "60", "self", ".", "ds_train", "=", "ChunkDataLoader", "(", "PreparedData", ",", "batch_size", "=", "self", ".", "Nminibatch", ",", "shuffle", "=", "shuffle", ",", "drop_last", "=", "True", ",", "num_workers", "=", "num_workers", ",", "pin_memory", "=", "pin_memory", ",", "timeout", "=", "timeout", ")", "self", ".", "f_train", "=", "LearnabilityMB", "(", "self", ".", "Nminibatch", ",", "self", ".", "D", ",", "constants", ".", "Coefficients", ".", "SLE", "[", "order", "]", ",", "self", ".", "groups", ",", "binary", "=", "PreparedData", ".", "classification", ",", "device", "=", "self", ".", "device", ")", "self", ".", "opt_train", "=", "get_train_opt", "(", "torch", ".", "nn", ".", "ParameterList", "(", "[", "self", ".", "x", "]", ")", ")", "self", ".", "it", "=", "0", "self", ".", "iters_per_epoch", "=", "int", "(", "np", ".", "ceil", "(", "len", "(", "self", ".", "ds_train", ".", "dataset", ")", "/", "self", ".", "ds_train", ".", "batch_size", ")", ")", "self", ".", "f_train", "=", "self", ".", "f_train", ".", "to", "(", "device", ")", "# pylint: disable=E1102", "self", ".", "w", "=", "torch", ".", "tensor", "(", "C", "/", "(", "C", "+", "1", ")", ",", "dtype", "=", "torch", ".", "get_default_dtype", "(", ")", ",", "requires_grad", "=", "False", ")", "self", ".", "w", "=", "self", ".", "w", ".", "to", "(", "device", ")" ]
[ 164, 4 ]
[ 316, 34 ]
python
en
['en', 'error', 'th']
False
Solver.penalty
(self, s)
Calculate L1 Penalty.
Calculate L1 Penalty.
def penalty(self, s): """ Calculate L1 Penalty. """ to_return = torch.sum(s) / self.D if self.soft_groups is not None: # if soft_groups, there is an additional penalty for using more # groups s_grouped = torch.zeros(self.soft_D, 1, dtype=torch.get_default_dtype(), device=self.device) for group in torch.unique(self.soft_groups): # groups should be indexed 0 to n_group - 1 # TODO: consider other functions here s_grouped[group] = s[self.soft_groups == group].max() # each component of the penalty contributes .5 # TODO: could make this a user given parameter to_return = (to_return + torch.sum(s_grouped) / self.soft_D) * .5 return to_return
[ "def", "penalty", "(", "self", ",", "s", ")", ":", "to_return", "=", "torch", ".", "sum", "(", "s", ")", "/", "self", ".", "D", "if", "self", ".", "soft_groups", "is", "not", "None", ":", "# if soft_groups, there is an additional penalty for using more", "# groups", "s_grouped", "=", "torch", ".", "zeros", "(", "self", ".", "soft_D", ",", "1", ",", "dtype", "=", "torch", ".", "get_default_dtype", "(", ")", ",", "device", "=", "self", ".", "device", ")", "for", "group", "in", "torch", ".", "unique", "(", "self", ".", "soft_groups", ")", ":", "# groups should be indexed 0 to n_group - 1", "# TODO: consider other functions here", "s_grouped", "[", "group", "]", "=", "s", "[", "self", ".", "soft_groups", "==", "group", "]", ".", "max", "(", ")", "# each component of the penalty contributes .5", "# TODO: could make this a user given parameter", "to_return", "=", "(", "to_return", "+", "torch", ".", "sum", "(", "s_grouped", ")", "/", "self", ".", "soft_D", ")", "*", ".5", "return", "to_return" ]
[ 319, 4 ]
[ 337, 24 ]
python
en
['en', 'error', 'th']
False
Solver.forward_and_backward
(self, s, xsub, ysub, retain_graph=False)
Completes the forward operation and computes gradients for learnability and penalty.
Completes the forward operation and computes gradients for learnability and penalty.
def forward_and_backward(self, s, xsub, ysub, retain_graph=False): """ Completes the forward operation and computes gradients for learnability and penalty. """ f_train = self.f_train(s, xsub, ysub) pen = self.penalty(s).unsqueeze(0).unsqueeze(0) # pylint: disable=E1102 grad_outputs = torch.tensor([[1]], dtype=torch.get_default_dtype(), device=self.device) g1, = torch.autograd.grad([f_train], [self.x], grad_outputs, retain_graph=True) # pylint: disable=E1102 grad_outputs = torch.tensor([[1]], dtype=torch.get_default_dtype(), device=self.device) g2, = torch.autograd.grad([pen], [self.x], grad_outputs, retain_graph=retain_graph) return f_train, pen, g1, g2
[ "def", "forward_and_backward", "(", "self", ",", "s", ",", "xsub", ",", "ysub", ",", "retain_graph", "=", "False", ")", ":", "f_train", "=", "self", ".", "f_train", "(", "s", ",", "xsub", ",", "ysub", ")", "pen", "=", "self", ".", "penalty", "(", "s", ")", ".", "unsqueeze", "(", "0", ")", ".", "unsqueeze", "(", "0", ")", "# pylint: disable=E1102", "grad_outputs", "=", "torch", ".", "tensor", "(", "[", "[", "1", "]", "]", ",", "dtype", "=", "torch", ".", "get_default_dtype", "(", ")", ",", "device", "=", "self", ".", "device", ")", "g1", ",", "=", "torch", ".", "autograd", ".", "grad", "(", "[", "f_train", "]", ",", "[", "self", ".", "x", "]", ",", "grad_outputs", ",", "retain_graph", "=", "True", ")", "# pylint: disable=E1102", "grad_outputs", "=", "torch", ".", "tensor", "(", "[", "[", "1", "]", "]", ",", "dtype", "=", "torch", ".", "get_default_dtype", "(", ")", ",", "device", "=", "self", ".", "device", ")", "g2", ",", "=", "torch", ".", "autograd", ".", "grad", "(", "[", "pen", "]", ",", "[", "self", ".", "x", "]", ",", "grad_outputs", ",", "retain_graph", "=", "retain_graph", ")", "return", "f_train", ",", "pen", ",", "g1", ",", "g2" ]
[ 340, 4 ]
[ 356, 35 ]
python
en
['en', 'error', 'th']
False
Solver.combine_gradient
(self, g1, g2)
Combine gradients from learnability and penalty Parameters ---------- g1 : array-like gradient from learnability g2 : array-like gradient from penalty
Combine gradients from learnability and penalty
def combine_gradient(self, g1, g2): """ Combine gradients from learnability and penalty Parameters ---------- g1 : array-like gradient from learnability g2 : array-like gradient from penalty """ to_return = ((1 - self.w) * g1 + self.w * g2) / self.accum_steps if self.groups is not None: # each column will get a gradient # but we can only up or down groups, so the gradient for the group # should be the average of the gradients of the columns to_return_grouped = torch.zeros_like(self.x) for group in torch.unique(self.groups): to_return_grouped[self.groups == group] = to_return[self.groups == group].mean() to_return = to_return_grouped return to_return
[ "def", "combine_gradient", "(", "self", ",", "g1", ",", "g2", ")", ":", "to_return", "=", "(", "(", "1", "-", "self", ".", "w", ")", "*", "g1", "+", "self", ".", "w", "*", "g2", ")", "/", "self", ".", "accum_steps", "if", "self", ".", "groups", "is", "not", "None", ":", "# each column will get a gradient", "# but we can only up or down groups, so the gradient for the group", "# should be the average of the gradients of the columns", "to_return_grouped", "=", "torch", ".", "zeros_like", "(", "self", ".", "x", ")", "for", "group", "in", "torch", ".", "unique", "(", "self", ".", "groups", ")", ":", "to_return_grouped", "[", "self", ".", "groups", "==", "group", "]", "=", "to_return", "[", "self", ".", "groups", "==", "group", "]", ".", "mean", "(", ")", "to_return", "=", "to_return_grouped", "return", "to_return" ]
[ 359, 4 ]
[ 380, 24 ]
python
en
['en', 'error', 'th']
False
Solver.combine_loss
(self, f_train, pen)
Combine the learnability and L1 penalty.
Combine the learnability and L1 penalty.
def combine_loss(self, f_train, pen): """ Combine the learnability and L1 penalty. """ return ((1 - self.w) * f_train.detach() + self.w * pen.detach()) \ / self.accum_steps
[ "def", "combine_loss", "(", "self", ",", "f_train", ",", "pen", ")", ":", "return", "(", "(", "1", "-", "self", ".", "w", ")", "*", "f_train", ".", "detach", "(", ")", "+", "self", ".", "w", "*", "pen", ".", "detach", "(", ")", ")", "/", "self", ".", "accum_steps" ]
[ 383, 4 ]
[ 388, 30 ]
python
en
['en', 'error', 'th']
False
Solver.transform_y_into_binary
(self, ysub, target_class)
Transforms multiclass classification problems into a binary classification problem.
Transforms multiclass classification problems into a binary classification problem.
def transform_y_into_binary(self, ysub, target_class): """ Transforms multiclass classification problems into a binary classification problem. """ with torch.no_grad(): ysub_binary = torch.zeros_like(ysub) if self.ordinal: # turn ordinal problems into n-1 classifications of is this # example less than rank k if target_class == 0: return None ysub_binary[ysub >= target_class] = 1 ysub_binary[ysub < target_class] = -1 else: # turn multiclass problems into n binary classifications ysub_binary[ysub == target_class] = 1 ysub_binary[ysub != target_class] = -1 return ysub_binary
[ "def", "transform_y_into_binary", "(", "self", ",", "ysub", ",", "target_class", ")", ":", "with", "torch", ".", "no_grad", "(", ")", ":", "ysub_binary", "=", "torch", ".", "zeros_like", "(", "ysub", ")", "if", "self", ".", "ordinal", ":", "# turn ordinal problems into n-1 classifications of is this", "# example less than rank k", "if", "target_class", "==", "0", ":", "return", "None", "ysub_binary", "[", "ysub", ">=", "target_class", "]", "=", "1", "ysub_binary", "[", "ysub", "<", "target_class", "]", "=", "-", "1", "else", ":", "# turn multiclass problems into n binary classifications", "ysub_binary", "[", "ysub", "==", "target_class", "]", "=", "1", "ysub_binary", "[", "ysub", "!=", "target_class", "]", "=", "-", "1", "return", "ysub_binary" ]
[ 391, 4 ]
[ 409, 26 ]
python
en
['en', 'error', 'th']
False
Solver._get_scaling_value
(self, ysub, target_class)
Returns the weight given to a class for multiclass classification.
Returns the weight given to a class for multiclass classification.
def _get_scaling_value(self, ysub, target_class): """ Returns the weight given to a class for multiclass classification. """ if self.balanced: if self.ordinal: return 1 / (torch.unique(ysub).size()[0] - 1) return 1 / torch.unique(ysub).size()[0] else: if self.ordinal: this_class_proportion = torch.mean(ysub >= target_class) normalizing_constant = 0 for i in range(1, self.n_classes): normalizing_constant += torch.mean(ysub >= i) return this_class_proportion / normalizing_constant else: return torch.mean(ysub == target_class)
[ "def", "_get_scaling_value", "(", "self", ",", "ysub", ",", "target_class", ")", ":", "if", "self", ".", "balanced", ":", "if", "self", ".", "ordinal", ":", "return", "1", "/", "(", "torch", ".", "unique", "(", "ysub", ")", ".", "size", "(", ")", "[", "0", "]", "-", "1", ")", "return", "1", "/", "torch", ".", "unique", "(", "ysub", ")", ".", "size", "(", ")", "[", "0", "]", "else", ":", "if", "self", ".", "ordinal", ":", "this_class_proportion", "=", "torch", ".", "mean", "(", "ysub", ">=", "target_class", ")", "normalizing_constant", "=", "0", "for", "i", "in", "range", "(", "1", ",", "self", ".", "n_classes", ")", ":", "normalizing_constant", "+=", "torch", ".", "mean", "(", "ysub", ">=", "i", ")", "return", "this_class_proportion", "/", "normalizing_constant", "else", ":", "return", "torch", ".", "mean", "(", "ysub", "==", "target_class", ")" ]
[ 412, 4 ]
[ 429, 55 ]
python
en
['en', 'error', 'th']
False
Solver._skip_y_forward
(self, y)
Returns boolean of whether to skip the currrent y if there is nothing to be learned from it.
Returns boolean of whether to skip the currrent y if there is nothing to be learned from it.
def _skip_y_forward(self, y): """ Returns boolean of whether to skip the currrent y if there is nothing to be learned from it. """ if y is None: return True elif torch.unique(y).size()[0] < 2: return True else: return False
[ "def", "_skip_y_forward", "(", "self", ",", "y", ")", ":", "if", "y", "is", "None", ":", "return", "True", "elif", "torch", ".", "unique", "(", "y", ")", ".", "size", "(", ")", "[", "0", "]", "<", "2", ":", "return", "True", "else", ":", "return", "False" ]
[ 432, 4 ]
[ 441, 24 ]
python
en
['en', 'error', 'th']
False
Solver.train
(self, f_callback=None, f_stop=None)
Trains the estimator to determine which features to include. Parameters ---------- f_callback : function Function that performs a callback f_stop: function Function that tells you when to stop
Trains the estimator to determine which features to include.
def train(self, f_callback=None, f_stop=None): """ Trains the estimator to determine which features to include. Parameters ---------- f_callback : function Function that performs a callback f_stop: function Function that tells you when to stop """ t = time.time() h = torch.zeros([1, 1], dtype=torch.get_default_dtype()) h = h.to(self.device) # h_complete is so when we divide by the number of classes # we only do that for that minibatch if accumulating h_complete = h.clone() flag_stop = False dataloader_iterator = iter(self.ds_train) self.x.grad = torch.zeros_like(self.x) while not flag_stop: try: xsub, ysub = next(dataloader_iterator) except StopIteration: dataloader_iterator = iter(self.ds_train) xsub, ysub = next(dataloader_iterator) try: s = self.ftransform(self.x) s = s.to(self.device) if self.multiclass: # accumulate gradients over each class, classes range from # 0 to n_classes - 1 #num_classes_batch = torch.unique(ysub).size()[0] for target_class in range(self.n_classes): ysub_binary = self.transform_y_into_binary( ysub, target_class) if self._skip_y_forward(ysub_binary): continue # should should skip if target class is not included # but that changes what we divide by scaling_value = self._get_scaling_value( ysub, target_class) f_train, pen, g1, g2 = self.forward_and_backward( s, xsub, ysub_binary, retain_graph=True) self.x.grad += self.combine_gradient( g1, g2) * scaling_value h += self.combine_loss(f_train, pen) * scaling_value else: if not self._skip_y_forward(ysub): f_train, pen, g1, g2 = self.forward_and_backward( s, xsub, ysub) self.x.grad += self.combine_gradient(g1, g2) h += self.combine_loss(f_train, pen) else: continue h_complete += h self.it += 1 if torch.isnan(h): raise constants.NanError( 'Loss is nan, something may be misconfigured') if self.it % self.accum_steps == 0: torch.nn.utils.clip_grad_norm_( torch.nn.ParameterList([self.x]), max_norm=self.max_norm) self.opt_train.step() t = time.time() - t if f_stop is not None: flag_stop = f_stop(self, h, self.it, t) if f_callback is not None: f_callback(self, h, self.it, t) elif self.verbose and (self.it // self.accum_steps) % self.verbose == 0: epoch = int(self.it / self.iters_per_epoch) print( '[Minibatch: %6d/ Epoch: %3d/ t: %3.3f s] Loss: %0.3f' % (self.it, epoch, t, h_complete / self.accum_steps)) if flag_stop: break self.opt_train.zero_grad() h = 0 h_complete = 0 t = time.time() except KeyboardInterrupt: flag_stop = True break
[ "def", "train", "(", "self", ",", "f_callback", "=", "None", ",", "f_stop", "=", "None", ")", ":", "t", "=", "time", ".", "time", "(", ")", "h", "=", "torch", ".", "zeros", "(", "[", "1", ",", "1", "]", ",", "dtype", "=", "torch", ".", "get_default_dtype", "(", ")", ")", "h", "=", "h", ".", "to", "(", "self", ".", "device", ")", "# h_complete is so when we divide by the number of classes", "# we only do that for that minibatch if accumulating", "h_complete", "=", "h", ".", "clone", "(", ")", "flag_stop", "=", "False", "dataloader_iterator", "=", "iter", "(", "self", ".", "ds_train", ")", "self", ".", "x", ".", "grad", "=", "torch", ".", "zeros_like", "(", "self", ".", "x", ")", "while", "not", "flag_stop", ":", "try", ":", "xsub", ",", "ysub", "=", "next", "(", "dataloader_iterator", ")", "except", "StopIteration", ":", "dataloader_iterator", "=", "iter", "(", "self", ".", "ds_train", ")", "xsub", ",", "ysub", "=", "next", "(", "dataloader_iterator", ")", "try", ":", "s", "=", "self", ".", "ftransform", "(", "self", ".", "x", ")", "s", "=", "s", ".", "to", "(", "self", ".", "device", ")", "if", "self", ".", "multiclass", ":", "# accumulate gradients over each class, classes range from", "# 0 to n_classes - 1", "#num_classes_batch = torch.unique(ysub).size()[0]", "for", "target_class", "in", "range", "(", "self", ".", "n_classes", ")", ":", "ysub_binary", "=", "self", ".", "transform_y_into_binary", "(", "ysub", ",", "target_class", ")", "if", "self", ".", "_skip_y_forward", "(", "ysub_binary", ")", ":", "continue", "# should should skip if target class is not included", "# but that changes what we divide by", "scaling_value", "=", "self", ".", "_get_scaling_value", "(", "ysub", ",", "target_class", ")", "f_train", ",", "pen", ",", "g1", ",", "g2", "=", "self", ".", "forward_and_backward", "(", "s", ",", "xsub", ",", "ysub_binary", ",", "retain_graph", "=", "True", ")", "self", ".", "x", ".", "grad", "+=", "self", ".", "combine_gradient", "(", "g1", ",", "g2", ")", "*", "scaling_value", "h", "+=", "self", ".", "combine_loss", "(", "f_train", ",", "pen", ")", "*", "scaling_value", "else", ":", "if", "not", "self", ".", "_skip_y_forward", "(", "ysub", ")", ":", "f_train", ",", "pen", ",", "g1", ",", "g2", "=", "self", ".", "forward_and_backward", "(", "s", ",", "xsub", ",", "ysub", ")", "self", ".", "x", ".", "grad", "+=", "self", ".", "combine_gradient", "(", "g1", ",", "g2", ")", "h", "+=", "self", ".", "combine_loss", "(", "f_train", ",", "pen", ")", "else", ":", "continue", "h_complete", "+=", "h", "self", ".", "it", "+=", "1", "if", "torch", ".", "isnan", "(", "h", ")", ":", "raise", "constants", ".", "NanError", "(", "'Loss is nan, something may be misconfigured'", ")", "if", "self", ".", "it", "%", "self", ".", "accum_steps", "==", "0", ":", "torch", ".", "nn", ".", "utils", ".", "clip_grad_norm_", "(", "torch", ".", "nn", ".", "ParameterList", "(", "[", "self", ".", "x", "]", ")", ",", "max_norm", "=", "self", ".", "max_norm", ")", "self", ".", "opt_train", ".", "step", "(", ")", "t", "=", "time", ".", "time", "(", ")", "-", "t", "if", "f_stop", "is", "not", "None", ":", "flag_stop", "=", "f_stop", "(", "self", ",", "h", ",", "self", ".", "it", ",", "t", ")", "if", "f_callback", "is", "not", "None", ":", "f_callback", "(", "self", ",", "h", ",", "self", ".", "it", ",", "t", ")", "elif", "self", ".", "verbose", "and", "(", "self", ".", "it", "//", "self", ".", "accum_steps", ")", "%", "self", ".", "verbose", "==", "0", ":", "epoch", "=", "int", "(", "self", ".", "it", "/", "self", ".", "iters_per_epoch", ")", "print", "(", "'[Minibatch: %6d/ Epoch: %3d/ t: %3.3f s] Loss: %0.3f'", "%", "(", "self", ".", "it", ",", "epoch", ",", "t", ",", "h_complete", "/", "self", ".", "accum_steps", ")", ")", "if", "flag_stop", ":", "break", "self", ".", "opt_train", ".", "zero_grad", "(", ")", "h", "=", "0", "h_complete", "=", "0", "t", "=", "time", ".", "time", "(", ")", "except", "KeyboardInterrupt", ":", "flag_stop", "=", "True", "break" ]
[ 444, 4 ]
[ 533, 21 ]
python
en
['en', 'error', 'th']
False
get_device_map
(n_layers, devices)
Returns a dictionary of layers distributed evenly across all devices.
Returns a dictionary of layers distributed evenly across all devices.
def get_device_map(n_layers, devices): """Returns a dictionary of layers distributed evenly across all devices.""" layers = list(range(n_layers)) n_blocks = int(ceil(n_layers / len(devices))) layers_list = list(layers[i : i + n_blocks] for i in range(0, n_layers, n_blocks)) return dict(zip(devices, layers_list))
[ "def", "get_device_map", "(", "n_layers", ",", "devices", ")", ":", "layers", "=", "list", "(", "range", "(", "n_layers", ")", ")", "n_blocks", "=", "int", "(", "ceil", "(", "n_layers", "/", "len", "(", "devices", ")", ")", ")", "layers_list", "=", "list", "(", "layers", "[", "i", ":", "i", "+", "n_blocks", "]", "for", "i", "in", "range", "(", "0", ",", "n_layers", ",", "n_blocks", ")", ")", "return", "dict", "(", "zip", "(", "devices", ",", "layers_list", ")", ")" ]
[ 47, 0 ]
[ 53, 42 ]
python
en
['en', 'en', 'en']
True
test_owserver_switch
(owproxy, hass, device_id)
Test for 1-Wire switch. This test forces all entities to be enabled.
Test for 1-Wire switch.
async def test_owserver_switch(owproxy, hass, device_id): """Test for 1-Wire switch. This test forces all entities to be enabled. """ await async_setup_component(hass, "persistent_notification", {}) entity_registry = mock_registry(hass) mock_device_sensor = MOCK_DEVICE_SENSORS[device_id] device_family = device_id[0:2] dir_return_value = [f"/{device_id}/"] read_side_effect = [device_family.encode()] if "inject_reads" in mock_device_sensor: read_side_effect += mock_device_sensor["inject_reads"] expected_sensors = mock_device_sensor[SWITCH_DOMAIN] for expected_sensor in expected_sensors: read_side_effect.append(expected_sensor["injected_value"]) # Ensure enough read side effect read_side_effect.extend([ProtocolError("Missing injected value")] * 10) owproxy.return_value.dir.return_value = dir_return_value owproxy.return_value.read.side_effect = read_side_effect # Force enable switches patch_device_switches = copy.deepcopy(DEVICE_SWITCHES) for item in patch_device_switches[device_family]: item["default_disabled"] = False with patch( "homeassistant.components.onewire.SUPPORTED_PLATFORMS", [SWITCH_DOMAIN] ), patch.dict( "homeassistant.components.onewire.switch.DEVICE_SWITCHES", patch_device_switches ): await setup_onewire_patched_owserver_integration(hass) await hass.async_block_till_done() assert len(entity_registry.entities) == len(expected_sensors) for expected_sensor in expected_sensors: entity_id = expected_sensor["entity_id"] registry_entry = entity_registry.entities.get(entity_id) assert registry_entry is not None state = hass.states.get(entity_id) assert state.state == expected_sensor["result"] if state.state == STATE_ON: owproxy.return_value.read.side_effect = [b" 0"] expected_sensor["result"] = STATE_OFF elif state.state == STATE_OFF: owproxy.return_value.read.side_effect = [b" 1"] expected_sensor["result"] = STATE_ON await hass.services.async_call( SWITCH_DOMAIN, SERVICE_TOGGLE, {ATTR_ENTITY_ID: entity_id}, blocking=True, ) await hass.async_block_till_done() state = hass.states.get(entity_id) assert state.state == expected_sensor["result"]
[ "async", "def", "test_owserver_switch", "(", "owproxy", ",", "hass", ",", "device_id", ")", ":", "await", "async_setup_component", "(", "hass", ",", "\"persistent_notification\"", ",", "{", "}", ")", "entity_registry", "=", "mock_registry", "(", "hass", ")", "mock_device_sensor", "=", "MOCK_DEVICE_SENSORS", "[", "device_id", "]", "device_family", "=", "device_id", "[", "0", ":", "2", "]", "dir_return_value", "=", "[", "f\"/{device_id}/\"", "]", "read_side_effect", "=", "[", "device_family", ".", "encode", "(", ")", "]", "if", "\"inject_reads\"", "in", "mock_device_sensor", ":", "read_side_effect", "+=", "mock_device_sensor", "[", "\"inject_reads\"", "]", "expected_sensors", "=", "mock_device_sensor", "[", "SWITCH_DOMAIN", "]", "for", "expected_sensor", "in", "expected_sensors", ":", "read_side_effect", ".", "append", "(", "expected_sensor", "[", "\"injected_value\"", "]", ")", "# Ensure enough read side effect", "read_side_effect", ".", "extend", "(", "[", "ProtocolError", "(", "\"Missing injected value\"", ")", "]", "*", "10", ")", "owproxy", ".", "return_value", ".", "dir", ".", "return_value", "=", "dir_return_value", "owproxy", ".", "return_value", ".", "read", ".", "side_effect", "=", "read_side_effect", "# Force enable switches", "patch_device_switches", "=", "copy", ".", "deepcopy", "(", "DEVICE_SWITCHES", ")", "for", "item", "in", "patch_device_switches", "[", "device_family", "]", ":", "item", "[", "\"default_disabled\"", "]", "=", "False", "with", "patch", "(", "\"homeassistant.components.onewire.SUPPORTED_PLATFORMS\"", ",", "[", "SWITCH_DOMAIN", "]", ")", ",", "patch", ".", "dict", "(", "\"homeassistant.components.onewire.switch.DEVICE_SWITCHES\"", ",", "patch_device_switches", ")", ":", "await", "setup_onewire_patched_owserver_integration", "(", "hass", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "entity_registry", ".", "entities", ")", "==", "len", "(", "expected_sensors", ")", "for", "expected_sensor", "in", "expected_sensors", ":", "entity_id", "=", "expected_sensor", "[", "\"entity_id\"", "]", "registry_entry", "=", "entity_registry", ".", "entities", ".", "get", "(", "entity_id", ")", "assert", "registry_entry", "is", "not", "None", "state", "=", "hass", ".", "states", ".", "get", "(", "entity_id", ")", "assert", "state", ".", "state", "==", "expected_sensor", "[", "\"result\"", "]", "if", "state", ".", "state", "==", "STATE_ON", ":", "owproxy", ".", "return_value", ".", "read", ".", "side_effect", "=", "[", "b\" 0\"", "]", "expected_sensor", "[", "\"result\"", "]", "=", "STATE_OFF", "elif", "state", ".", "state", "==", "STATE_OFF", ":", "owproxy", ".", "return_value", ".", "read", ".", "side_effect", "=", "[", "b\" 1\"", "]", "expected_sensor", "[", "\"result\"", "]", "=", "STATE_ON", "await", "hass", ".", "services", ".", "async_call", "(", "SWITCH_DOMAIN", ",", "SERVICE_TOGGLE", ",", "{", "ATTR_ENTITY_ID", ":", "entity_id", "}", ",", "blocking", "=", "True", ",", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "entity_id", ")", "assert", "state", ".", "state", "==", "expected_sensor", "[", "\"result\"", "]" ]
[ 65, 0 ]
[ 128, 55 ]
python
en
['en', 'en', 'en']
True
fortFloat
(s)
Convert a string representation of a floating point value to a float, allowing for some of the peculiarities of allowable Fortran representations.
Convert a string representation of a floating point value to a float, allowing for some of the peculiarities of allowable Fortran representations.
def fortFloat(s): """ Convert a string representation of a floating point value to a float, allowing for some of the peculiarities of allowable Fortran representations. """ s = s.strip() s = s.replace('D', 'E').replace('d', 'e') s = s.replace('E ', 'E+').replace('e ', 'e+') return float(s)
[ "def", "fortFloat", "(", "s", ")", ":", "s", "=", "s", ".", "strip", "(", ")", "s", "=", "s", ".", "replace", "(", "'D'", ",", "'E'", ")", ".", "replace", "(", "'d'", ",", "'e'", ")", "s", "=", "s", ".", "replace", "(", "'E '", ",", "'E+'", ")", ".", "replace", "(", "'e '", ",", "'e+'", ")", "return", "float", "(", "s", ")" ]
[ 837, 0 ]
[ 845, 19 ]
python
en
['en', 'error', 'th']
False