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
list
start_point
list
end_point
list
language
stringclasses
1 value
docstring_language
stringlengths
2
7
docstring_language_predictions
stringlengths
18
23
is_langid_reliable
stringclasses
2 values
test_device_not_found
(zha_client)
Test not found response from get device API.
Test not found response from get device API.
async def test_device_not_found(zha_client): """Test not found response from get device API.""" await zha_client.send_json( {ID: 6, TYPE: "zha/device", ATTR_IEEE: "28:6d:97:00:01:04:11:8c"} ) msg = await zha_client.receive_json() assert msg["id"] == 6 assert msg["type"] == const.TYPE_RESULT assert not msg["success"] assert msg["error"]["code"] == const.ERR_NOT_FOUND
[ "async", "def", "test_device_not_found", "(", "zha_client", ")", ":", "await", "zha_client", ".", "send_json", "(", "{", "ID", ":", "6", ",", "TYPE", ":", "\"zha/device\"", ",", "ATTR_IEEE", ":", "\"28:6d:97:00:01:04:11:8c\"", "}", ")", "msg", "=", "await", "zha_client", ".", "receive_json", "(", ")", "assert", "msg", "[", "\"id\"", "]", "==", "6", "assert", "msg", "[", "\"type\"", "]", "==", "const", ".", "TYPE_RESULT", "assert", "not", "msg", "[", "\"success\"", "]", "assert", "msg", "[", "\"error\"", "]", "[", "\"code\"", "]", "==", "const", ".", "ERR_NOT_FOUND" ]
[ 203, 0 ]
[ 212, 54 ]
python
en
['en', 'en', 'en']
True
test_list_groups
(zha_client)
Test getting zha zigbee groups.
Test getting zha zigbee groups.
async def test_list_groups(zha_client): """Test getting zha zigbee groups.""" await zha_client.send_json({ID: 7, TYPE: "zha/groups"}) msg = await zha_client.receive_json() assert msg["id"] == 7 assert msg["type"] == const.TYPE_RESULT groups = msg["result"] assert len(groups) == 1 for group in groups: assert group["group_id"] == FIXTURE_GRP_ID assert group["name"] == FIXTURE_GRP_NAME assert group["members"] == []
[ "async", "def", "test_list_groups", "(", "zha_client", ")", ":", "await", "zha_client", ".", "send_json", "(", "{", "ID", ":", "7", ",", "TYPE", ":", "\"zha/groups\"", "}", ")", "msg", "=", "await", "zha_client", ".", "receive_json", "(", ")", "assert", "msg", "[", "\"id\"", "]", "==", "7", "assert", "msg", "[", "\"type\"", "]", "==", "const", ".", "TYPE_RESULT", "groups", "=", "msg", "[", "\"result\"", "]", "assert", "len", "(", "groups", ")", "==", "1", "for", "group", "in", "groups", ":", "assert", "group", "[", "\"group_id\"", "]", "==", "FIXTURE_GRP_ID", "assert", "group", "[", "\"name\"", "]", "==", "FIXTURE_GRP_NAME", "assert", "group", "[", "\"members\"", "]", "==", "[", "]" ]
[ 215, 0 ]
[ 229, 37 ]
python
nl
['nl', 'xh', 'nl']
True
test_get_group
(zha_client)
Test getting a specific zha zigbee group.
Test getting a specific zha zigbee group.
async def test_get_group(zha_client): """Test getting a specific zha zigbee group.""" await zha_client.send_json({ID: 8, TYPE: "zha/group", GROUP_ID: FIXTURE_GRP_ID}) msg = await zha_client.receive_json() assert msg["id"] == 8 assert msg["type"] == const.TYPE_RESULT group = msg["result"] assert group is not None assert group["group_id"] == FIXTURE_GRP_ID assert group["name"] == FIXTURE_GRP_NAME assert group["members"] == []
[ "async", "def", "test_get_group", "(", "zha_client", ")", ":", "await", "zha_client", ".", "send_json", "(", "{", "ID", ":", "8", ",", "TYPE", ":", "\"zha/group\"", ",", "GROUP_ID", ":", "FIXTURE_GRP_ID", "}", ")", "msg", "=", "await", "zha_client", ".", "receive_json", "(", ")", "assert", "msg", "[", "\"id\"", "]", "==", "8", "assert", "msg", "[", "\"type\"", "]", "==", "const", ".", "TYPE_RESULT", "group", "=", "msg", "[", "\"result\"", "]", "assert", "group", "is", "not", "None", "assert", "group", "[", "\"group_id\"", "]", "==", "FIXTURE_GRP_ID", "assert", "group", "[", "\"name\"", "]", "==", "FIXTURE_GRP_NAME", "assert", "group", "[", "\"members\"", "]", "==", "[", "]" ]
[ 232, 0 ]
[ 244, 33 ]
python
en
['nl', 'fy', 'en']
False
test_get_group_not_found
(zha_client)
Test not found response from get group API.
Test not found response from get group API.
async def test_get_group_not_found(zha_client): """Test not found response from get group API.""" await zha_client.send_json({ID: 9, TYPE: "zha/group", GROUP_ID: 1_234_567}) msg = await zha_client.receive_json() assert msg["id"] == 9 assert msg["type"] == const.TYPE_RESULT assert not msg["success"] assert msg["error"]["code"] == const.ERR_NOT_FOUND
[ "async", "def", "test_get_group_not_found", "(", "zha_client", ")", ":", "await", "zha_client", ".", "send_json", "(", "{", "ID", ":", "9", ",", "TYPE", ":", "\"zha/group\"", ",", "GROUP_ID", ":", "1_234_567", "}", ")", "msg", "=", "await", "zha_client", ".", "receive_json", "(", ")", "assert", "msg", "[", "\"id\"", "]", "==", "9", "assert", "msg", "[", "\"type\"", "]", "==", "const", ".", "TYPE_RESULT", "assert", "not", "msg", "[", "\"success\"", "]", "assert", "msg", "[", "\"error\"", "]", "[", "\"code\"", "]", "==", "const", ".", "ERR_NOT_FOUND" ]
[ 247, 0 ]
[ 256, 54 ]
python
en
['en', 'en', 'en']
True
test_list_groupable_devices
(zha_client, device_groupable)
Test getting zha devices that have a group cluster.
Test getting zha devices that have a group cluster.
async def test_list_groupable_devices(zha_client, device_groupable): """Test getting zha devices that have a group cluster.""" await zha_client.send_json({ID: 10, TYPE: "zha/devices/groupable"}) msg = await zha_client.receive_json() assert msg["id"] == 10 assert msg["type"] == const.TYPE_RESULT device_endpoints = msg["result"] assert len(device_endpoints) == 1 for endpoint in device_endpoints: assert endpoint["device"][ATTR_IEEE] == "01:2d:6f:00:0a:90:69:e8" assert endpoint["device"][ATTR_MANUFACTURER] is not None assert endpoint["device"][ATTR_MODEL] is not None assert endpoint["device"][ATTR_NAME] is not None assert endpoint["device"][ATTR_QUIRK_APPLIED] is not None assert endpoint["device"]["entities"] is not None assert endpoint["endpoint_id"] is not None assert endpoint["entities"] is not None for entity_reference in endpoint["device"]["entities"]: assert entity_reference[ATTR_NAME] is not None assert entity_reference["entity_id"] is not None for entity_reference in endpoint["entities"]: assert entity_reference["original_name"] is not None # Make sure there are no groupable devices when the device is unavailable # Make device unavailable device_groupable.available = False await zha_client.send_json({ID: 11, TYPE: "zha/devices/groupable"}) msg = await zha_client.receive_json() assert msg["id"] == 11 assert msg["type"] == const.TYPE_RESULT device_endpoints = msg["result"] assert len(device_endpoints) == 0
[ "async", "def", "test_list_groupable_devices", "(", "zha_client", ",", "device_groupable", ")", ":", "await", "zha_client", ".", "send_json", "(", "{", "ID", ":", "10", ",", "TYPE", ":", "\"zha/devices/groupable\"", "}", ")", "msg", "=", "await", "zha_client", ".", "receive_json", "(", ")", "assert", "msg", "[", "\"id\"", "]", "==", "10", "assert", "msg", "[", "\"type\"", "]", "==", "const", ".", "TYPE_RESULT", "device_endpoints", "=", "msg", "[", "\"result\"", "]", "assert", "len", "(", "device_endpoints", ")", "==", "1", "for", "endpoint", "in", "device_endpoints", ":", "assert", "endpoint", "[", "\"device\"", "]", "[", "ATTR_IEEE", "]", "==", "\"01:2d:6f:00:0a:90:69:e8\"", "assert", "endpoint", "[", "\"device\"", "]", "[", "ATTR_MANUFACTURER", "]", "is", "not", "None", "assert", "endpoint", "[", "\"device\"", "]", "[", "ATTR_MODEL", "]", "is", "not", "None", "assert", "endpoint", "[", "\"device\"", "]", "[", "ATTR_NAME", "]", "is", "not", "None", "assert", "endpoint", "[", "\"device\"", "]", "[", "ATTR_QUIRK_APPLIED", "]", "is", "not", "None", "assert", "endpoint", "[", "\"device\"", "]", "[", "\"entities\"", "]", "is", "not", "None", "assert", "endpoint", "[", "\"endpoint_id\"", "]", "is", "not", "None", "assert", "endpoint", "[", "\"entities\"", "]", "is", "not", "None", "for", "entity_reference", "in", "endpoint", "[", "\"device\"", "]", "[", "\"entities\"", "]", ":", "assert", "entity_reference", "[", "ATTR_NAME", "]", "is", "not", "None", "assert", "entity_reference", "[", "\"entity_id\"", "]", "is", "not", "None", "for", "entity_reference", "in", "endpoint", "[", "\"entities\"", "]", ":", "assert", "entity_reference", "[", "\"original_name\"", "]", "is", "not", "None", "# Make sure there are no groupable devices when the device is unavailable", "# Make device unavailable", "device_groupable", ".", "available", "=", "False", "await", "zha_client", ".", "send_json", "(", "{", "ID", ":", "11", ",", "TYPE", ":", "\"zha/devices/groupable\"", "}", ")", "msg", "=", "await", "zha_client", ".", "receive_json", "(", ")", "assert", "msg", "[", "\"id\"", "]", "==", "11", "assert", "msg", "[", "\"type\"", "]", "==", "const", ".", "TYPE_RESULT", "device_endpoints", "=", "msg", "[", "\"result\"", "]", "assert", "len", "(", "device_endpoints", ")", "==", "0" ]
[ 259, 0 ]
[ 299, 37 ]
python
en
['en', 'en', 'en']
True
test_add_group
(zha_client)
Test adding and getting a new zha zigbee group.
Test adding and getting a new zha zigbee group.
async def test_add_group(zha_client): """Test adding and getting a new zha zigbee group.""" await zha_client.send_json({ID: 12, TYPE: "zha/group/add", GROUP_NAME: "new_group"}) msg = await zha_client.receive_json() assert msg["id"] == 12 assert msg["type"] == const.TYPE_RESULT added_group = msg["result"] assert added_group["name"] == "new_group" assert added_group["members"] == [] await zha_client.send_json({ID: 13, TYPE: "zha/groups"}) msg = await zha_client.receive_json() assert msg["id"] == 13 assert msg["type"] == const.TYPE_RESULT groups = msg["result"] assert len(groups) == 2 for group in groups: assert group["name"] == FIXTURE_GRP_NAME or group["name"] == "new_group"
[ "async", "def", "test_add_group", "(", "zha_client", ")", ":", "await", "zha_client", ".", "send_json", "(", "{", "ID", ":", "12", ",", "TYPE", ":", "\"zha/group/add\"", ",", "GROUP_NAME", ":", "\"new_group\"", "}", ")", "msg", "=", "await", "zha_client", ".", "receive_json", "(", ")", "assert", "msg", "[", "\"id\"", "]", "==", "12", "assert", "msg", "[", "\"type\"", "]", "==", "const", ".", "TYPE_RESULT", "added_group", "=", "msg", "[", "\"result\"", "]", "assert", "added_group", "[", "\"name\"", "]", "==", "\"new_group\"", "assert", "added_group", "[", "\"members\"", "]", "==", "[", "]", "await", "zha_client", ".", "send_json", "(", "{", "ID", ":", "13", ",", "TYPE", ":", "\"zha/groups\"", "}", ")", "msg", "=", "await", "zha_client", ".", "receive_json", "(", ")", "assert", "msg", "[", "\"id\"", "]", "==", "13", "assert", "msg", "[", "\"type\"", "]", "==", "const", ".", "TYPE_RESULT", "groups", "=", "msg", "[", "\"result\"", "]", "assert", "len", "(", "groups", ")", "==", "2", "for", "group", "in", "groups", ":", "assert", "group", "[", "\"name\"", "]", "==", "FIXTURE_GRP_NAME", "or", "group", "[", "\"name\"", "]", "==", "\"new_group\"" ]
[ 302, 0 ]
[ 325, 80 ]
python
en
['en', 'en', 'en']
True
test_remove_group
(zha_client)
Test removing a new zha zigbee group.
Test removing a new zha zigbee group.
async def test_remove_group(zha_client): """Test removing a new zha zigbee group.""" await zha_client.send_json({ID: 14, TYPE: "zha/groups"}) msg = await zha_client.receive_json() assert msg["id"] == 14 assert msg["type"] == const.TYPE_RESULT groups = msg["result"] assert len(groups) == 1 await zha_client.send_json( {ID: 15, TYPE: "zha/group/remove", GROUP_IDS: [FIXTURE_GRP_ID]} ) msg = await zha_client.receive_json() assert msg["id"] == 15 assert msg["type"] == const.TYPE_RESULT groups_remaining = msg["result"] assert len(groups_remaining) == 0 await zha_client.send_json({ID: 16, TYPE: "zha/groups"}) msg = await zha_client.receive_json() assert msg["id"] == 16 assert msg["type"] == const.TYPE_RESULT groups = msg["result"] assert len(groups) == 0
[ "async", "def", "test_remove_group", "(", "zha_client", ")", ":", "await", "zha_client", ".", "send_json", "(", "{", "ID", ":", "14", ",", "TYPE", ":", "\"zha/groups\"", "}", ")", "msg", "=", "await", "zha_client", ".", "receive_json", "(", ")", "assert", "msg", "[", "\"id\"", "]", "==", "14", "assert", "msg", "[", "\"type\"", "]", "==", "const", ".", "TYPE_RESULT", "groups", "=", "msg", "[", "\"result\"", "]", "assert", "len", "(", "groups", ")", "==", "1", "await", "zha_client", ".", "send_json", "(", "{", "ID", ":", "15", ",", "TYPE", ":", "\"zha/group/remove\"", ",", "GROUP_IDS", ":", "[", "FIXTURE_GRP_ID", "]", "}", ")", "msg", "=", "await", "zha_client", ".", "receive_json", "(", ")", "assert", "msg", "[", "\"id\"", "]", "==", "15", "assert", "msg", "[", "\"type\"", "]", "==", "const", ".", "TYPE_RESULT", "groups_remaining", "=", "msg", "[", "\"result\"", "]", "assert", "len", "(", "groups_remaining", ")", "==", "0", "await", "zha_client", ".", "send_json", "(", "{", "ID", ":", "16", ",", "TYPE", ":", "\"zha/groups\"", "}", ")", "msg", "=", "await", "zha_client", ".", "receive_json", "(", ")", "assert", "msg", "[", "\"id\"", "]", "==", "16", "assert", "msg", "[", "\"type\"", "]", "==", "const", ".", "TYPE_RESULT", "groups", "=", "msg", "[", "\"result\"", "]", "assert", "len", "(", "groups", ")", "==", "0" ]
[ 328, 0 ]
[ 358, 27 ]
python
en
['br', 'en', 'en']
True
app_controller
(hass, setup_zha)
Fixture for zigpy Application Controller.
Fixture for zigpy Application Controller.
async def app_controller(hass, setup_zha): """Fixture for zigpy Application Controller.""" await setup_zha() controller = hass.data[DATA_ZHA][DATA_ZHA_GATEWAY].application_controller p1 = patch.object(controller, "permit") p2 = patch.object(controller, "permit_with_key", new=AsyncMock()) with p1, p2: yield controller
[ "async", "def", "app_controller", "(", "hass", ",", "setup_zha", ")", ":", "await", "setup_zha", "(", ")", "controller", "=", "hass", ".", "data", "[", "DATA_ZHA", "]", "[", "DATA_ZHA_GATEWAY", "]", ".", "application_controller", "p1", "=", "patch", ".", "object", "(", "controller", ",", "\"permit\"", ")", "p2", "=", "patch", ".", "object", "(", "controller", ",", "\"permit_with_key\"", ",", "new", "=", "AsyncMock", "(", ")", ")", "with", "p1", ",", "p2", ":", "yield", "controller" ]
[ 362, 0 ]
[ 369, 24 ]
python
en
['nl', 'en', 'en']
True
test_permit_ha12
( hass, app_controller, hass_admin_user, params, duration, node )
Test permit service.
Test permit service.
async def test_permit_ha12( hass, app_controller, hass_admin_user, params, duration, node ): """Test permit service.""" await hass.services.async_call( DOMAIN, SERVICE_PERMIT, params, True, Context(user_id=hass_admin_user.id) ) assert app_controller.permit.await_count == 1 assert app_controller.permit.await_args[1]["time_s"] == duration assert app_controller.permit.await_args[1]["node"] == node assert app_controller.permit_with_key.call_count == 0
[ "async", "def", "test_permit_ha12", "(", "hass", ",", "app_controller", ",", "hass_admin_user", ",", "params", ",", "duration", ",", "node", ")", ":", "await", "hass", ".", "services", ".", "async_call", "(", "DOMAIN", ",", "SERVICE_PERMIT", ",", "params", ",", "True", ",", "Context", "(", "user_id", "=", "hass_admin_user", ".", "id", ")", ")", "assert", "app_controller", ".", "permit", ".", "await_count", "==", "1", "assert", "app_controller", ".", "permit", ".", "await_args", "[", "1", "]", "[", "\"time_s\"", "]", "==", "duration", "assert", "app_controller", ".", "permit", ".", "await_args", "[", "1", "]", "[", "\"node\"", "]", "==", "node", "assert", "app_controller", ".", "permit_with_key", ".", "call_count", "==", "0" ]
[ 389, 0 ]
[ 400, 57 ]
python
de
['ro', 'de', 'en']
False
test_permit_with_install_code
( hass, app_controller, hass_admin_user, params, src_ieee, code )
Test permit service with install code.
Test permit service with install code.
async def test_permit_with_install_code( hass, app_controller, hass_admin_user, params, src_ieee, code ): """Test permit service with install code.""" await hass.services.async_call( DOMAIN, SERVICE_PERMIT, params, True, Context(user_id=hass_admin_user.id) ) assert app_controller.permit.await_count == 0 assert app_controller.permit_with_key.call_count == 1 assert app_controller.permit_with_key.await_args[1]["time_s"] == 60 assert app_controller.permit_with_key.await_args[1]["node"] == src_ieee assert app_controller.permit_with_key.await_args[1]["code"] == code
[ "async", "def", "test_permit_with_install_code", "(", "hass", ",", "app_controller", ",", "hass_admin_user", ",", "params", ",", "src_ieee", ",", "code", ")", ":", "await", "hass", ".", "services", ".", "async_call", "(", "DOMAIN", ",", "SERVICE_PERMIT", ",", "params", ",", "True", ",", "Context", "(", "user_id", "=", "hass_admin_user", ".", "id", ")", ")", "assert", "app_controller", ".", "permit", ".", "await_count", "==", "0", "assert", "app_controller", ".", "permit_with_key", ".", "call_count", "==", "1", "assert", "app_controller", ".", "permit_with_key", ".", "await_args", "[", "1", "]", "[", "\"time_s\"", "]", "==", "60", "assert", "app_controller", ".", "permit_with_key", ".", "await_args", "[", "1", "]", "[", "\"node\"", "]", "==", "src_ieee", "assert", "app_controller", ".", "permit_with_key", ".", "await_args", "[", "1", "]", "[", "\"code\"", "]", "==", "code" ]
[ 424, 0 ]
[ 436, 71 ]
python
en
['en', 'en', 'en']
True
test_permit_with_install_code_fail
( hass, app_controller, hass_admin_user, params )
Test permit service with install code.
Test permit service with install code.
async def test_permit_with_install_code_fail( hass, app_controller, hass_admin_user, params ): """Test permit service with install code.""" with pytest.raises(vol.Invalid): await hass.services.async_call( DOMAIN, SERVICE_PERMIT, params, True, Context(user_id=hass_admin_user.id) ) assert app_controller.permit.await_count == 0 assert app_controller.permit_with_key.call_count == 0
[ "async", "def", "test_permit_with_install_code_fail", "(", "hass", ",", "app_controller", ",", "hass_admin_user", ",", "params", ")", ":", "with", "pytest", ".", "raises", "(", "vol", ".", "Invalid", ")", ":", "await", "hass", ".", "services", ".", "async_call", "(", "DOMAIN", ",", "SERVICE_PERMIT", ",", "params", ",", "True", ",", "Context", "(", "user_id", "=", "hass_admin_user", ".", "id", ")", ")", "assert", "app_controller", ".", "permit", ".", "await_count", "==", "0", "assert", "app_controller", ".", "permit_with_key", ".", "call_count", "==", "0" ]
[ 475, 0 ]
[ 485, 57 ]
python
en
['en', 'en', 'en']
True
test_permit_with_qr_code
( hass, app_controller, hass_admin_user, params, src_ieee, code )
Test permit service with install code from qr code.
Test permit service with install code from qr code.
async def test_permit_with_qr_code( hass, app_controller, hass_admin_user, params, src_ieee, code ): """Test permit service with install code from qr code.""" await hass.services.async_call( DOMAIN, SERVICE_PERMIT, params, True, Context(user_id=hass_admin_user.id) ) assert app_controller.permit.await_count == 0 assert app_controller.permit_with_key.call_count == 1 assert app_controller.permit_with_key.await_args[1]["time_s"] == 60 assert app_controller.permit_with_key.await_args[1]["node"] == src_ieee assert app_controller.permit_with_key.await_args[1]["code"] == code
[ "async", "def", "test_permit_with_qr_code", "(", "hass", ",", "app_controller", ",", "hass_admin_user", ",", "params", ",", "src_ieee", ",", "code", ")", ":", "await", "hass", ".", "services", ".", "async_call", "(", "DOMAIN", ",", "SERVICE_PERMIT", ",", "params", ",", "True", ",", "Context", "(", "user_id", "=", "hass_admin_user", ".", "id", ")", ")", "assert", "app_controller", ".", "permit", ".", "await_count", "==", "0", "assert", "app_controller", ".", "permit_with_key", ".", "call_count", "==", "1", "assert", "app_controller", ".", "permit_with_key", ".", "await_args", "[", "1", "]", "[", "\"time_s\"", "]", "==", "60", "assert", "app_controller", ".", "permit_with_key", ".", "await_args", "[", "1", "]", "[", "\"node\"", "]", "==", "src_ieee", "assert", "app_controller", ".", "permit_with_key", ".", "await_args", "[", "1", "]", "[", "\"code\"", "]", "==", "code" ]
[ 513, 0 ]
[ 525, 71 ]
python
en
['en', 'en', 'en']
True
test_ws_permit_with_qr_code
( app_controller, zha_client, params, src_ieee, code )
Test permit service with install code from qr code.
Test permit service with install code from qr code.
async def test_ws_permit_with_qr_code( app_controller, zha_client, params, src_ieee, code ): """Test permit service with install code from qr code.""" await zha_client.send_json( {ID: 14, TYPE: f"{DOMAIN}/devices/{SERVICE_PERMIT}", **params} ) msg = await zha_client.receive_json() assert msg["id"] == 14 assert msg["type"] == const.TYPE_RESULT assert msg["success"] assert app_controller.permit.await_count == 0 assert app_controller.permit_with_key.call_count == 1 assert app_controller.permit_with_key.await_args[1]["time_s"] == 60 assert app_controller.permit_with_key.await_args[1]["node"] == src_ieee assert app_controller.permit_with_key.await_args[1]["code"] == code
[ "async", "def", "test_ws_permit_with_qr_code", "(", "app_controller", ",", "zha_client", ",", "params", ",", "src_ieee", ",", "code", ")", ":", "await", "zha_client", ".", "send_json", "(", "{", "ID", ":", "14", ",", "TYPE", ":", "f\"{DOMAIN}/devices/{SERVICE_PERMIT}\"", ",", "*", "*", "params", "}", ")", "msg", "=", "await", "zha_client", ".", "receive_json", "(", ")", "assert", "msg", "[", "\"id\"", "]", "==", "14", "assert", "msg", "[", "\"type\"", "]", "==", "const", ".", "TYPE_RESULT", "assert", "msg", "[", "\"success\"", "]", "assert", "app_controller", ".", "permit", ".", "await_count", "==", "0", "assert", "app_controller", ".", "permit_with_key", ".", "call_count", "==", "1", "assert", "app_controller", ".", "permit_with_key", ".", "await_args", "[", "1", "]", "[", "\"time_s\"", "]", "==", "60", "assert", "app_controller", ".", "permit_with_key", ".", "await_args", "[", "1", "]", "[", "\"node\"", "]", "==", "src_ieee", "assert", "app_controller", ".", "permit_with_key", ".", "await_args", "[", "1", "]", "[", "\"code\"", "]", "==", "code" ]
[ 529, 0 ]
[ 547, 71 ]
python
en
['en', 'en', 'en']
True
test_ws_permit_with_install_code_fail
(app_controller, zha_client, params)
Test permit ws service with install code.
Test permit ws service with install code.
async def test_ws_permit_with_install_code_fail(app_controller, zha_client, params): """Test permit ws service with install code.""" await zha_client.send_json( {ID: 14, TYPE: f"{DOMAIN}/devices/{SERVICE_PERMIT}", **params} ) msg = await zha_client.receive_json() assert msg["id"] == 14 assert msg["type"] == const.TYPE_RESULT assert msg["success"] is False assert app_controller.permit.await_count == 0 assert app_controller.permit_with_key.call_count == 0
[ "async", "def", "test_ws_permit_with_install_code_fail", "(", "app_controller", ",", "zha_client", ",", "params", ")", ":", "await", "zha_client", ".", "send_json", "(", "{", "ID", ":", "14", ",", "TYPE", ":", "f\"{DOMAIN}/devices/{SERVICE_PERMIT}\"", ",", "*", "*", "params", "}", ")", "msg", "=", "await", "zha_client", ".", "receive_json", "(", ")", "assert", "msg", "[", "\"id\"", "]", "==", "14", "assert", "msg", "[", "\"type\"", "]", "==", "const", ".", "TYPE_RESULT", "assert", "msg", "[", "\"success\"", "]", "is", "False", "assert", "app_controller", ".", "permit", ".", "await_count", "==", "0", "assert", "app_controller", ".", "permit_with_key", ".", "call_count", "==", "0" ]
[ 551, 0 ]
[ 564, 57 ]
python
en
['en', 'en', 'en']
True
test_ws_permit_ha12
(app_controller, zha_client, params, duration, node)
Test permit ws service.
Test permit ws service.
async def test_ws_permit_ha12(app_controller, zha_client, params, duration, node): """Test permit ws service.""" await zha_client.send_json( {ID: 14, TYPE: f"{DOMAIN}/devices/{SERVICE_PERMIT}", **params} ) msg = await zha_client.receive_json() assert msg["id"] == 14 assert msg["type"] == const.TYPE_RESULT assert msg["success"] assert app_controller.permit.await_count == 1 assert app_controller.permit.await_args[1]["time_s"] == duration assert app_controller.permit.await_args[1]["node"] == node assert app_controller.permit_with_key.call_count == 0
[ "async", "def", "test_ws_permit_ha12", "(", "app_controller", ",", "zha_client", ",", "params", ",", "duration", ",", "node", ")", ":", "await", "zha_client", ".", "send_json", "(", "{", "ID", ":", "14", ",", "TYPE", ":", "f\"{DOMAIN}/devices/{SERVICE_PERMIT}\"", ",", "*", "*", "params", "}", ")", "msg", "=", "await", "zha_client", ".", "receive_json", "(", ")", "assert", "msg", "[", "\"id\"", "]", "==", "14", "assert", "msg", "[", "\"type\"", "]", "==", "const", ".", "TYPE_RESULT", "assert", "msg", "[", "\"success\"", "]", "assert", "app_controller", ".", "permit", ".", "await_count", "==", "1", "assert", "app_controller", ".", "permit", ".", "await_args", "[", "1", "]", "[", "\"time_s\"", "]", "==", "duration", "assert", "app_controller", ".", "permit", ".", "await_args", "[", "1", "]", "[", "\"node\"", "]", "==", "node", "assert", "app_controller", ".", "permit_with_key", ".", "call_count", "==", "0" ]
[ 584, 0 ]
[ 599, 57 ]
python
de
['en', 'de', 'pl']
False
TestMbartCc25Enro.test_model_download
(self)
This warms up the cache so that we can time the next test without including download time, which varies between machines.
This warms up the cache so that we can time the next test without including download time, which varies between machines.
def test_model_download(self): """This warms up the cache so that we can time the next test without including download time, which varies between machines.""" MarianMTModel.from_pretrained(MARIAN_MODEL)
[ "def", "test_model_download", "(", "self", ")", ":", "MarianMTModel", ".", "from_pretrained", "(", "MARIAN_MODEL", ")" ]
[ 34, 4 ]
[ 36, 51 ]
python
en
['en', 'en', 'en']
True
is_on
(hass, entity_id)
Return if the alert is firing and not acknowledged.
Return if the alert is firing and not acknowledged.
def is_on(hass, entity_id): """Return if the alert is firing and not acknowledged.""" return hass.states.is_state(entity_id, STATE_ON)
[ "def", "is_on", "(", "hass", ",", "entity_id", ")", ":", "return", "hass", ".", "states", ".", "is_state", "(", "entity_id", ",", "STATE_ON", ")" ]
[ 68, 0 ]
[ 70, 52 ]
python
en
['en', 'en', 'en']
True
async_setup
(hass, config)
Set up the Alert component.
Set up the Alert component.
async def async_setup(hass, config): """Set up the Alert component.""" entities = [] for object_id, cfg in config[DOMAIN].items(): if not cfg: cfg = {} name = cfg[CONF_NAME] watched_entity_id = cfg[CONF_ENTITY_ID] alert_state = cfg[CONF_STATE] repeat = cfg[CONF_REPEAT] skip_first = cfg[CONF_SKIP_FIRST] message_template = cfg.get(CONF_ALERT_MESSAGE) done_message_template = cfg.get(CONF_DONE_MESSAGE) notifiers = cfg[CONF_NOTIFIERS] can_ack = cfg[CONF_CAN_ACK] title_template = cfg.get(CONF_TITLE) data = cfg.get(CONF_DATA) entities.append( Alert( hass, object_id, name, watched_entity_id, alert_state, repeat, skip_first, message_template, done_message_template, notifiers, can_ack, title_template, data, ) ) if not entities: return False async def async_handle_alert_service(service_call): """Handle calls to alert services.""" alert_ids = await service.async_extract_entity_ids(hass, service_call) for alert_id in alert_ids: for alert in entities: if alert.entity_id != alert_id: continue alert.async_set_context(service_call.context) if service_call.service == SERVICE_TURN_ON: await alert.async_turn_on() elif service_call.service == SERVICE_TOGGLE: await alert.async_toggle() else: await alert.async_turn_off() # Setup service calls hass.services.async_register( DOMAIN, SERVICE_TURN_OFF, async_handle_alert_service, schema=ALERT_SERVICE_SCHEMA, ) hass.services.async_register( DOMAIN, SERVICE_TURN_ON, async_handle_alert_service, schema=ALERT_SERVICE_SCHEMA ) hass.services.async_register( DOMAIN, SERVICE_TOGGLE, async_handle_alert_service, schema=ALERT_SERVICE_SCHEMA ) for alert in entities: alert.async_write_ha_state() return True
[ "async", "def", "async_setup", "(", "hass", ",", "config", ")", ":", "entities", "=", "[", "]", "for", "object_id", ",", "cfg", "in", "config", "[", "DOMAIN", "]", ".", "items", "(", ")", ":", "if", "not", "cfg", ":", "cfg", "=", "{", "}", "name", "=", "cfg", "[", "CONF_NAME", "]", "watched_entity_id", "=", "cfg", "[", "CONF_ENTITY_ID", "]", "alert_state", "=", "cfg", "[", "CONF_STATE", "]", "repeat", "=", "cfg", "[", "CONF_REPEAT", "]", "skip_first", "=", "cfg", "[", "CONF_SKIP_FIRST", "]", "message_template", "=", "cfg", ".", "get", "(", "CONF_ALERT_MESSAGE", ")", "done_message_template", "=", "cfg", ".", "get", "(", "CONF_DONE_MESSAGE", ")", "notifiers", "=", "cfg", "[", "CONF_NOTIFIERS", "]", "can_ack", "=", "cfg", "[", "CONF_CAN_ACK", "]", "title_template", "=", "cfg", ".", "get", "(", "CONF_TITLE", ")", "data", "=", "cfg", ".", "get", "(", "CONF_DATA", ")", "entities", ".", "append", "(", "Alert", "(", "hass", ",", "object_id", ",", "name", ",", "watched_entity_id", ",", "alert_state", ",", "repeat", ",", "skip_first", ",", "message_template", ",", "done_message_template", ",", "notifiers", ",", "can_ack", ",", "title_template", ",", "data", ",", ")", ")", "if", "not", "entities", ":", "return", "False", "async", "def", "async_handle_alert_service", "(", "service_call", ")", ":", "\"\"\"Handle calls to alert services.\"\"\"", "alert_ids", "=", "await", "service", ".", "async_extract_entity_ids", "(", "hass", ",", "service_call", ")", "for", "alert_id", "in", "alert_ids", ":", "for", "alert", "in", "entities", ":", "if", "alert", ".", "entity_id", "!=", "alert_id", ":", "continue", "alert", ".", "async_set_context", "(", "service_call", ".", "context", ")", "if", "service_call", ".", "service", "==", "SERVICE_TURN_ON", ":", "await", "alert", ".", "async_turn_on", "(", ")", "elif", "service_call", ".", "service", "==", "SERVICE_TOGGLE", ":", "await", "alert", ".", "async_toggle", "(", ")", "else", ":", "await", "alert", ".", "async_turn_off", "(", ")", "# Setup service calls", "hass", ".", "services", ".", "async_register", "(", "DOMAIN", ",", "SERVICE_TURN_OFF", ",", "async_handle_alert_service", ",", "schema", "=", "ALERT_SERVICE_SCHEMA", ",", ")", "hass", ".", "services", ".", "async_register", "(", "DOMAIN", ",", "SERVICE_TURN_ON", ",", "async_handle_alert_service", ",", "schema", "=", "ALERT_SERVICE_SCHEMA", ")", "hass", ".", "services", ".", "async_register", "(", "DOMAIN", ",", "SERVICE_TOGGLE", ",", "async_handle_alert_service", ",", "schema", "=", "ALERT_SERVICE_SCHEMA", ")", "for", "alert", "in", "entities", ":", "alert", ".", "async_write_ha_state", "(", ")", "return", "True" ]
[ 73, 0 ]
[ 148, 15 ]
python
en
['en', 'da', 'en']
True
Alert.__init__
( self, hass, entity_id, name, watched_entity_id, state, repeat, skip_first, message_template, done_message_template, notifiers, can_ack, title_template, data, )
Initialize the alert.
Initialize the alert.
def __init__( self, hass, entity_id, name, watched_entity_id, state, repeat, skip_first, message_template, done_message_template, notifiers, can_ack, title_template, data, ): """Initialize the alert.""" self.hass = hass self._name = name self._alert_state = state self._skip_first = skip_first self._data = data self._message_template = message_template if self._message_template is not None: self._message_template.hass = hass self._done_message_template = done_message_template if self._done_message_template is not None: self._done_message_template.hass = hass self._title_template = title_template if self._title_template is not None: self._title_template.hass = hass self._notifiers = notifiers self._can_ack = can_ack self._delay = [timedelta(minutes=val) for val in repeat] self._next_delay = 0 self._firing = False self._ack = False self._cancel = None self._send_done_message = False self.entity_id = f"{DOMAIN}.{entity_id}" event.async_track_state_change_event( hass, [watched_entity_id], self.watched_entity_change )
[ "def", "__init__", "(", "self", ",", "hass", ",", "entity_id", ",", "name", ",", "watched_entity_id", ",", "state", ",", "repeat", ",", "skip_first", ",", "message_template", ",", "done_message_template", ",", "notifiers", ",", "can_ack", ",", "title_template", ",", "data", ",", ")", ":", "self", ".", "hass", "=", "hass", "self", ".", "_name", "=", "name", "self", ".", "_alert_state", "=", "state", "self", ".", "_skip_first", "=", "skip_first", "self", ".", "_data", "=", "data", "self", ".", "_message_template", "=", "message_template", "if", "self", ".", "_message_template", "is", "not", "None", ":", "self", ".", "_message_template", ".", "hass", "=", "hass", "self", ".", "_done_message_template", "=", "done_message_template", "if", "self", ".", "_done_message_template", "is", "not", "None", ":", "self", ".", "_done_message_template", ".", "hass", "=", "hass", "self", ".", "_title_template", "=", "title_template", "if", "self", ".", "_title_template", "is", "not", "None", ":", "self", ".", "_title_template", ".", "hass", "=", "hass", "self", ".", "_notifiers", "=", "notifiers", "self", ".", "_can_ack", "=", "can_ack", "self", ".", "_delay", "=", "[", "timedelta", "(", "minutes", "=", "val", ")", "for", "val", "in", "repeat", "]", "self", ".", "_next_delay", "=", "0", "self", ".", "_firing", "=", "False", "self", ".", "_ack", "=", "False", "self", ".", "_cancel", "=", "None", "self", ".", "_send_done_message", "=", "False", "self", ".", "entity_id", "=", "f\"{DOMAIN}.{entity_id}\"", "event", ".", "async_track_state_change_event", "(", "hass", ",", "[", "watched_entity_id", "]", ",", "self", ".", "watched_entity_change", ")" ]
[ 154, 4 ]
[ 203, 9 ]
python
en
['en', 'en', 'en']
True
Alert.name
(self)
Return the name of the alert.
Return the name of the alert.
def name(self): """Return the name of the alert.""" return self._name
[ "def", "name", "(", "self", ")", ":", "return", "self", ".", "_name" ]
[ 206, 4 ]
[ 208, 25 ]
python
en
['en', 'en', 'en']
True
Alert.should_poll
(self)
Home Assistant need not poll these entities.
Home Assistant need not poll these entities.
def should_poll(self): """Home Assistant need not poll these entities.""" return False
[ "def", "should_poll", "(", "self", ")", ":", "return", "False" ]
[ 211, 4 ]
[ 213, 20 ]
python
en
['en', 'en', 'en']
True
Alert.state
(self)
Return the alert status.
Return the alert status.
def state(self): """Return the alert status.""" if self._firing: if self._ack: return STATE_OFF return STATE_ON return STATE_IDLE
[ "def", "state", "(", "self", ")", ":", "if", "self", ".", "_firing", ":", "if", "self", ".", "_ack", ":", "return", "STATE_OFF", "return", "STATE_ON", "return", "STATE_IDLE" ]
[ 216, 4 ]
[ 222, 25 ]
python
en
['en', 'id', 'en']
True
Alert.watched_entity_change
(self, ev)
Determine if the alert should start or stop.
Determine if the alert should start or stop.
async def watched_entity_change(self, ev): """Determine if the alert should start or stop.""" to_state = ev.data.get("new_state") if to_state is None: return _LOGGER.debug("Watched entity (%s) has changed", ev.data.get("entity_id")) if to_state.state == self._alert_state and not self._firing: await self.begin_alerting() if to_state.state != self._alert_state and self._firing: await self.end_alerting()
[ "async", "def", "watched_entity_change", "(", "self", ",", "ev", ")", ":", "to_state", "=", "ev", ".", "data", ".", "get", "(", "\"new_state\"", ")", "if", "to_state", "is", "None", ":", "return", "_LOGGER", ".", "debug", "(", "\"Watched entity (%s) has changed\"", ",", "ev", ".", "data", ".", "get", "(", "\"entity_id\"", ")", ")", "if", "to_state", ".", "state", "==", "self", ".", "_alert_state", "and", "not", "self", ".", "_firing", ":", "await", "self", ".", "begin_alerting", "(", ")", "if", "to_state", ".", "state", "!=", "self", ".", "_alert_state", "and", "self", ".", "_firing", ":", "await", "self", ".", "end_alerting", "(", ")" ]
[ 224, 4 ]
[ 233, 37 ]
python
en
['en', 'en', 'en']
True
Alert.begin_alerting
(self)
Begin the alert procedures.
Begin the alert procedures.
async def begin_alerting(self): """Begin the alert procedures.""" _LOGGER.debug("Beginning Alert: %s", self._name) self._ack = False self._firing = True self._next_delay = 0 if not self._skip_first: await self._notify() else: await self._schedule_notify() self.async_write_ha_state()
[ "async", "def", "begin_alerting", "(", "self", ")", ":", "_LOGGER", ".", "debug", "(", "\"Beginning Alert: %s\"", ",", "self", ".", "_name", ")", "self", ".", "_ack", "=", "False", "self", ".", "_firing", "=", "True", "self", ".", "_next_delay", "=", "0", "if", "not", "self", ".", "_skip_first", ":", "await", "self", ".", "_notify", "(", ")", "else", ":", "await", "self", ".", "_schedule_notify", "(", ")", "self", ".", "async_write_ha_state", "(", ")" ]
[ 235, 4 ]
[ 247, 35 ]
python
en
['en', 'nl', 'en']
True
Alert.end_alerting
(self)
End the alert procedures.
End the alert procedures.
async def end_alerting(self): """End the alert procedures.""" _LOGGER.debug("Ending Alert: %s", self._name) self._cancel() self._ack = False self._firing = False if self._send_done_message: await self._notify_done_message() self.async_write_ha_state()
[ "async", "def", "end_alerting", "(", "self", ")", ":", "_LOGGER", ".", "debug", "(", "\"Ending Alert: %s\"", ",", "self", ".", "_name", ")", "self", ".", "_cancel", "(", ")", "self", ".", "_ack", "=", "False", "self", ".", "_firing", "=", "False", "if", "self", ".", "_send_done_message", ":", "await", "self", ".", "_notify_done_message", "(", ")", "self", ".", "async_write_ha_state", "(", ")" ]
[ 249, 4 ]
[ 257, 35 ]
python
en
['en', 'nl', 'en']
True
Alert._schedule_notify
(self)
Schedule a notification.
Schedule a notification.
async def _schedule_notify(self): """Schedule a notification.""" delay = self._delay[self._next_delay] next_msg = now() + delay self._cancel = event.async_track_point_in_time( self.hass, self._notify, next_msg ) self._next_delay = min(self._next_delay + 1, len(self._delay) - 1)
[ "async", "def", "_schedule_notify", "(", "self", ")", ":", "delay", "=", "self", ".", "_delay", "[", "self", ".", "_next_delay", "]", "next_msg", "=", "now", "(", ")", "+", "delay", "self", ".", "_cancel", "=", "event", ".", "async_track_point_in_time", "(", "self", ".", "hass", ",", "self", ".", "_notify", ",", "next_msg", ")", "self", ".", "_next_delay", "=", "min", "(", "self", ".", "_next_delay", "+", "1", ",", "len", "(", "self", ".", "_delay", ")", "-", "1", ")" ]
[ 259, 4 ]
[ 266, 74 ]
python
en
['en', 'en', 'en']
True
Alert._notify
(self, *args)
Send the alert notification.
Send the alert notification.
async def _notify(self, *args): """Send the alert notification.""" if not self._firing: return if not self._ack: _LOGGER.info("Alerting: %s", self._name) self._send_done_message = True if self._message_template is not None: message = self._message_template.async_render(parse_result=False) else: message = self._name await self._send_notification_message(message) await self._schedule_notify()
[ "async", "def", "_notify", "(", "self", ",", "*", "args", ")", ":", "if", "not", "self", ".", "_firing", ":", "return", "if", "not", "self", ".", "_ack", ":", "_LOGGER", ".", "info", "(", "\"Alerting: %s\"", ",", "self", ".", "_name", ")", "self", ".", "_send_done_message", "=", "True", "if", "self", ".", "_message_template", "is", "not", "None", ":", "message", "=", "self", ".", "_message_template", ".", "async_render", "(", "parse_result", "=", "False", ")", "else", ":", "message", "=", "self", ".", "_name", "await", "self", ".", "_send_notification_message", "(", "message", ")", "await", "self", ".", "_schedule_notify", "(", ")" ]
[ 268, 4 ]
[ 283, 37 ]
python
en
['en', 'lb', 'en']
True
Alert._notify_done_message
(self, *args)
Send notification of complete alert.
Send notification of complete alert.
async def _notify_done_message(self, *args): """Send notification of complete alert.""" _LOGGER.info("Alerting: %s", self._done_message_template) self._send_done_message = False if self._done_message_template is None: return message = self._done_message_template.async_render(parse_result=False) await self._send_notification_message(message)
[ "async", "def", "_notify_done_message", "(", "self", ",", "*", "args", ")", ":", "_LOGGER", ".", "info", "(", "\"Alerting: %s\"", ",", "self", ".", "_done_message_template", ")", "self", ".", "_send_done_message", "=", "False", "if", "self", ".", "_done_message_template", "is", "None", ":", "return", "message", "=", "self", ".", "_done_message_template", ".", "async_render", "(", "parse_result", "=", "False", ")", "await", "self", ".", "_send_notification_message", "(", "message", ")" ]
[ 285, 4 ]
[ 295, 54 ]
python
en
['en', 'nl', 'en']
True
Alert.async_turn_on
(self, **kwargs)
Async Unacknowledge alert.
Async Unacknowledge alert.
async def async_turn_on(self, **kwargs): """Async Unacknowledge alert.""" _LOGGER.debug("Reset Alert: %s", self._name) self._ack = False self.async_write_ha_state()
[ "async", "def", "async_turn_on", "(", "self", ",", "*", "*", "kwargs", ")", ":", "_LOGGER", ".", "debug", "(", "\"Reset Alert: %s\"", ",", "self", ".", "_name", ")", "self", ".", "_ack", "=", "False", "self", ".", "async_write_ha_state", "(", ")" ]
[ 314, 4 ]
[ 318, 35 ]
python
af
['en', 'af', 'it']
False
Alert.async_turn_off
(self, **kwargs)
Async Acknowledge alert.
Async Acknowledge alert.
async def async_turn_off(self, **kwargs): """Async Acknowledge alert.""" _LOGGER.debug("Acknowledged Alert: %s", self._name) self._ack = True self.async_write_ha_state()
[ "async", "def", "async_turn_off", "(", "self", ",", "*", "*", "kwargs", ")", ":", "_LOGGER", ".", "debug", "(", "\"Acknowledged Alert: %s\"", ",", "self", ".", "_name", ")", "self", ".", "_ack", "=", "True", "self", ".", "async_write_ha_state", "(", ")" ]
[ 320, 4 ]
[ 324, 35 ]
python
en
['en', 'hu', 'en']
True
Alert.async_toggle
(self, **kwargs)
Async toggle alert.
Async toggle alert.
async def async_toggle(self, **kwargs): """Async toggle alert.""" if self._ack: return await self.async_turn_on() return await self.async_turn_off()
[ "async", "def", "async_toggle", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "_ack", ":", "return", "await", "self", ".", "async_turn_on", "(", ")", "return", "await", "self", ".", "async_turn_off", "(", ")" ]
[ 326, 4 ]
[ 330, 42 ]
python
en
['en', 'hu', 'en']
True
async_setup_platform
(hass, _, add_entities, discovery_info=None)
Add sensor from the main Qwikswitch component.
Add sensor from the main Qwikswitch component.
async def async_setup_platform(hass, _, add_entities, discovery_info=None): """Add sensor from the main Qwikswitch component.""" if discovery_info is None: return qsusb = hass.data[QWIKSWITCH] _LOGGER.debug("Setup qwikswitch.sensor %s, %s", qsusb, discovery_info) devs = [QSSensor(sensor) for sensor in discovery_info[QWIKSWITCH]] add_entities(devs)
[ "async", "def", "async_setup_platform", "(", "hass", ",", "_", ",", "add_entities", ",", "discovery_info", "=", "None", ")", ":", "if", "discovery_info", "is", "None", ":", "return", "qsusb", "=", "hass", ".", "data", "[", "QWIKSWITCH", "]", "_LOGGER", ".", "debug", "(", "\"Setup qwikswitch.sensor %s, %s\"", ",", "qsusb", ",", "discovery_info", ")", "devs", "=", "[", "QSSensor", "(", "sensor", ")", "for", "sensor", "in", "discovery_info", "[", "QWIKSWITCH", "]", "]", "add_entities", "(", "devs", ")" ]
[ 12, 0 ]
[ 20, 22 ]
python
en
['en', 'en', 'en']
True
QSSensor.__init__
(self, sensor)
Initialize the sensor.
Initialize the sensor.
def __init__(self, sensor): """Initialize the sensor.""" super().__init__(sensor["id"], sensor["name"]) self.channel = sensor["channel"] sensor_type = sensor["type"] self._decode, self.unit = SENSORS[sensor_type] # this cannot happen because it only happens in bool and this should be redirected to binary_sensor assert not isinstance( self.unit, type ), f"boolean sensor id={sensor['id']} name={sensor['name']}"
[ "def", "__init__", "(", "self", ",", "sensor", ")", ":", "super", "(", ")", ".", "__init__", "(", "sensor", "[", "\"id\"", "]", ",", "sensor", "[", "\"name\"", "]", ")", "self", ".", "channel", "=", "sensor", "[", "\"channel\"", "]", "sensor_type", "=", "sensor", "[", "\"type\"", "]", "self", ".", "_decode", ",", "self", ".", "unit", "=", "SENSORS", "[", "sensor_type", "]", "# this cannot happen because it only happens in bool and this should be redirected to binary_sensor", "assert", "not", "isinstance", "(", "self", ".", "unit", ",", "type", ")", ",", "f\"boolean sensor id={sensor['id']} name={sensor['name']}\"" ]
[ 28, 4 ]
[ 39, 68 ]
python
en
['en', 'en', 'en']
True
QSSensor.update_packet
(self, packet)
Receive update packet from QSUSB.
Receive update packet from QSUSB.
def update_packet(self, packet): """Receive update packet from QSUSB.""" val = self._decode(packet, channel=self.channel) _LOGGER.debug( "Update %s (%s:%s) decoded as %s: %s", self.entity_id, self.qsid, self.channel, val, packet, ) if val is not None: self._val = val self.async_write_ha_state()
[ "def", "update_packet", "(", "self", ",", "packet", ")", ":", "val", "=", "self", ".", "_decode", "(", "packet", ",", "channel", "=", "self", ".", "channel", ")", "_LOGGER", ".", "debug", "(", "\"Update %s (%s:%s) decoded as %s: %s\"", ",", "self", ".", "entity_id", ",", "self", ".", "qsid", ",", "self", ".", "channel", ",", "val", ",", "packet", ",", ")", "if", "val", "is", "not", "None", ":", "self", ".", "_val", "=", "val", "self", ".", "async_write_ha_state", "(", ")" ]
[ 42, 4 ]
[ 55, 39 ]
python
en
['en', 'en', 'en']
True
QSSensor.state
(self)
Return the value of the sensor.
Return the value of the sensor.
def state(self): """Return the value of the sensor.""" return str(self._val)
[ "def", "state", "(", "self", ")", ":", "return", "str", "(", "self", ".", "_val", ")" ]
[ 58, 4 ]
[ 60, 29 ]
python
en
['en', 'no', 'en']
True
QSSensor.unique_id
(self)
Return a unique identifier for this sensor.
Return a unique identifier for this sensor.
def unique_id(self): """Return a unique identifier for this sensor.""" return f"qs{self.qsid}:{self.channel}"
[ "def", "unique_id", "(", "self", ")", ":", "return", "f\"qs{self.qsid}:{self.channel}\"" ]
[ 63, 4 ]
[ 65, 46 ]
python
en
['en', 'fr', 'en']
True
QSSensor.unit_of_measurement
(self)
Return the unit the value is expressed in.
Return the unit the value is expressed in.
def unit_of_measurement(self): """Return the unit the value is expressed in.""" return self.unit
[ "def", "unit_of_measurement", "(", "self", ")", ":", "return", "self", ".", "unit" ]
[ 68, 4 ]
[ 70, 24 ]
python
en
['en', 'en', 'en']
True
Module.train_forward
(self, *inputs, **kwargs)
def train_forward(self, data, label, **kwargs): # this is a toy example for 1 output, 2 loss function output = None loss1 = torch.tensor(0.0) loss2 = torch.tensor(0.0) outputs = {'output': output, 'loss1': loss1, 'loss2': loss2} loss = loss1 + loss2 return outputs, loss
def train_forward(self, data, label, **kwargs): # this is a toy example for 1 output, 2 loss function
def train_forward(self, *inputs, **kwargs): """ def train_forward(self, data, label, **kwargs): # this is a toy example for 1 output, 2 loss function output = None loss1 = torch.tensor(0.0) loss2 = torch.tensor(0.0) outputs = {'output': output, 'loss1': loss1, 'loss2': loss2} loss = loss1 + loss2 return outputs, loss """ raise NotImplemented
[ "def", "train_forward", "(", "self", ",", "*", "inputs", ",", "*", "*", "kwargs", ")", ":", "raise", "NotImplemented" ]
[ 25, 4 ]
[ 41, 28 ]
python
en
['en', 'error', 'th']
False
Module.inference_forward
(self, *inputs, **kwargs)
def inference_forward(self, data, **kwargs): output = None outputs = {'output': output} return outputs
def inference_forward(self, data, **kwargs): output = None outputs = {'output': output} return outputs
def inference_forward(self, *inputs, **kwargs): """ def inference_forward(self, data, **kwargs): output = None outputs = {'output': output} return outputs """ raise NotImplemented
[ "def", "inference_forward", "(", "self", ",", "*", "inputs", ",", "*", "*", "kwargs", ")", ":", "raise", "NotImplemented" ]
[ 43, 4 ]
[ 50, 28 ]
python
en
['en', 'error', 'th']
False
AuxiliaryHead.__init__
(self, input_size, C, n_classes)
assuming input size 7x7 or 8x8
assuming input size 7x7 or 8x8
def __init__(self, input_size, C, n_classes): """ assuming input size 7x7 or 8x8 """ assert input_size in [7, 8] super().__init__() self.net = nn.Sequential( nn.ReLU(inplace=True), nn.AvgPool2d(5, stride=input_size - 5, padding=0, count_include_pad=False), # 2x2 out nn.Conv2d(C, 128, kernel_size=1, bias=False), nn.BatchNorm2d(128), nn.ReLU(inplace=True), nn.Conv2d(128, 768, kernel_size=2, bias=False), # 1x1 out nn.BatchNorm2d(768), nn.ReLU(inplace=True) ) self.linear = nn.Linear(768, n_classes)
[ "def", "__init__", "(", "self", ",", "input_size", ",", "C", ",", "n_classes", ")", ":", "assert", "input_size", "in", "[", "7", ",", "8", "]", "super", "(", ")", ".", "__init__", "(", ")", "self", ".", "net", "=", "nn", ".", "Sequential", "(", "nn", ".", "ReLU", "(", "inplace", "=", "True", ")", ",", "nn", ".", "AvgPool2d", "(", "5", ",", "stride", "=", "input_size", "-", "5", ",", "padding", "=", "0", ",", "count_include_pad", "=", "False", ")", ",", "# 2x2 out", "nn", ".", "Conv2d", "(", "C", ",", "128", ",", "kernel_size", "=", "1", ",", "bias", "=", "False", ")", ",", "nn", ".", "BatchNorm2d", "(", "128", ")", ",", "nn", ".", "ReLU", "(", "inplace", "=", "True", ")", ",", "nn", ".", "Conv2d", "(", "128", ",", "768", ",", "kernel_size", "=", "2", ",", "bias", "=", "False", ")", ",", "# 1x1 out", "nn", ".", "BatchNorm2d", "(", "768", ")", ",", "nn", ".", "ReLU", "(", "inplace", "=", "True", ")", ")", "self", ".", "linear", "=", "nn", ".", "Linear", "(", "768", ",", "n_classes", ")" ]
[ 15, 4 ]
[ 29, 47 ]
python
en
['en', 'su', 'en']
True
test_setup
(hass, requests_mock)
Test for successfully setting up the SleepIQ platform.
Test for successfully setting up the SleepIQ platform.
async def test_setup(hass, requests_mock): """Test for successfully setting up the SleepIQ platform.""" mock_responses(requests_mock) assert await async_setup_component(hass, "sleepiq", {"sleepiq": CONFIG}) device_mock = MagicMock() sleepiq.setup_platform(hass, CONFIG, device_mock, MagicMock()) devices = device_mock.call_args[0][0] assert 2 == len(devices) left_side = devices[1] assert "SleepNumber ILE Test1 SleepNumber" == left_side.name assert 40 == left_side.state right_side = devices[0] assert "SleepNumber ILE Test2 SleepNumber" == right_side.name assert 80 == right_side.state
[ "async", "def", "test_setup", "(", "hass", ",", "requests_mock", ")", ":", "mock_responses", "(", "requests_mock", ")", "assert", "await", "async_setup_component", "(", "hass", ",", "\"sleepiq\"", ",", "{", "\"sleepiq\"", ":", "CONFIG", "}", ")", "device_mock", "=", "MagicMock", "(", ")", "sleepiq", ".", "setup_platform", "(", "hass", ",", "CONFIG", ",", "device_mock", ",", "MagicMock", "(", ")", ")", "devices", "=", "device_mock", ".", "call_args", "[", "0", "]", "[", "0", "]", "assert", "2", "==", "len", "(", "devices", ")", "left_side", "=", "devices", "[", "1", "]", "assert", "\"SleepNumber ILE Test1 SleepNumber\"", "==", "left_side", ".", "name", "assert", "40", "==", "left_side", ".", "state", "right_side", "=", "devices", "[", "0", "]", "assert", "\"SleepNumber ILE Test2 SleepNumber\"", "==", "right_side", ".", "name", "assert", "80", "==", "right_side", ".", "state" ]
[ 10, 0 ]
[ 27, 33 ]
python
en
['en', 'en', 'en']
True
test_setup_sigle
(hass, requests_mock)
Test for successfully setting up the SleepIQ platform.
Test for successfully setting up the SleepIQ platform.
async def test_setup_sigle(hass, requests_mock): """Test for successfully setting up the SleepIQ platform.""" mock_responses(requests_mock, single=True) assert await async_setup_component(hass, "sleepiq", {"sleepiq": CONFIG}) device_mock = MagicMock() sleepiq.setup_platform(hass, CONFIG, device_mock, MagicMock()) devices = device_mock.call_args[0][0] assert 1 == len(devices) right_side = devices[0] assert "SleepNumber ILE Test1 SleepNumber" == right_side.name assert 40 == right_side.state
[ "async", "def", "test_setup_sigle", "(", "hass", ",", "requests_mock", ")", ":", "mock_responses", "(", "requests_mock", ",", "single", "=", "True", ")", "assert", "await", "async_setup_component", "(", "hass", ",", "\"sleepiq\"", ",", "{", "\"sleepiq\"", ":", "CONFIG", "}", ")", "device_mock", "=", "MagicMock", "(", ")", "sleepiq", ".", "setup_platform", "(", "hass", ",", "CONFIG", ",", "device_mock", ",", "MagicMock", "(", ")", ")", "devices", "=", "device_mock", ".", "call_args", "[", "0", "]", "[", "0", "]", "assert", "1", "==", "len", "(", "devices", ")", "right_side", "=", "devices", "[", "0", "]", "assert", "\"SleepNumber ILE Test1 SleepNumber\"", "==", "right_side", ".", "name", "assert", "40", "==", "right_side", ".", "state" ]
[ 30, 0 ]
[ 43, 33 ]
python
en
['en', 'en', 'en']
True
Node.__init__
(self, node_id, num_prev_nodes, channels, num_downsample_connect)
builtin Darts Node structure Parameters --- node_id: str num_prev_nodes: int the number of previous nodes in this cell channels: int output channels num_downsample_connect: int downsample the input node if this cell is reduction cell
builtin Darts Node structure
def __init__(self, node_id, num_prev_nodes, channels, num_downsample_connect): """ builtin Darts Node structure Parameters --- node_id: str num_prev_nodes: int the number of previous nodes in this cell channels: int output channels num_downsample_connect: int downsample the input node if this cell is reduction cell """ super().__init__() self.ops = nn.ModuleList() choice_keys = [] for i in range(num_prev_nodes): stride = 2 if i < num_downsample_connect else 1 choice_keys.append("{}_p{}".format(node_id, i)) self.ops.append( mutables.LayerChoice(OrderedDict([ ("maxpool", PoolBN('max', channels, 3, stride, 1, affine=False)), ("avgpool", PoolBN('avg', channels, 3, stride, 1, affine=False)), ("skipconnect", nn.Identity() if stride == 1 else FactorizedReduce(channels, channels, affine=False)), ("sepconv3x3", SepConv(channels, channels, 3, stride, 1, affine=False)), ("sepconv5x5", SepConv(channels, channels, 5, stride, 2, affine=False)), ("dilconv3x3", DilConv(channels, channels, 3, stride, 2, 2, affine=False)), ("dilconv5x5", DilConv(channels, channels, 5, stride, 4, 2, affine=False)) ]), key=choice_keys[-1])) self.drop_path = DropPath() self.input_switch = mutables.InputChoice(choose_from=choice_keys, n_chosen=2, key="{}_switch".format(node_id))
[ "def", "__init__", "(", "self", ",", "node_id", ",", "num_prev_nodes", ",", "channels", ",", "num_downsample_connect", ")", ":", "super", "(", ")", ".", "__init__", "(", ")", "self", ".", "ops", "=", "nn", ".", "ModuleList", "(", ")", "choice_keys", "=", "[", "]", "for", "i", "in", "range", "(", "num_prev_nodes", ")", ":", "stride", "=", "2", "if", "i", "<", "num_downsample_connect", "else", "1", "choice_keys", ".", "append", "(", "\"{}_p{}\"", ".", "format", "(", "node_id", ",", "i", ")", ")", "self", ".", "ops", ".", "append", "(", "mutables", ".", "LayerChoice", "(", "OrderedDict", "(", "[", "(", "\"maxpool\"", ",", "PoolBN", "(", "'max'", ",", "channels", ",", "3", ",", "stride", ",", "1", ",", "affine", "=", "False", ")", ")", ",", "(", "\"avgpool\"", ",", "PoolBN", "(", "'avg'", ",", "channels", ",", "3", ",", "stride", ",", "1", ",", "affine", "=", "False", ")", ")", ",", "(", "\"skipconnect\"", ",", "nn", ".", "Identity", "(", ")", "if", "stride", "==", "1", "else", "FactorizedReduce", "(", "channels", ",", "channels", ",", "affine", "=", "False", ")", ")", ",", "(", "\"sepconv3x3\"", ",", "SepConv", "(", "channels", ",", "channels", ",", "3", ",", "stride", ",", "1", ",", "affine", "=", "False", ")", ")", ",", "(", "\"sepconv5x5\"", ",", "SepConv", "(", "channels", ",", "channels", ",", "5", ",", "stride", ",", "2", ",", "affine", "=", "False", ")", ")", ",", "(", "\"dilconv3x3\"", ",", "DilConv", "(", "channels", ",", "channels", ",", "3", ",", "stride", ",", "2", ",", "2", ",", "affine", "=", "False", ")", ")", ",", "(", "\"dilconv5x5\"", ",", "DilConv", "(", "channels", ",", "channels", ",", "5", ",", "stride", ",", "4", ",", "2", ",", "affine", "=", "False", ")", ")", "]", ")", ",", "key", "=", "choice_keys", "[", "-", "1", "]", ")", ")", "self", ".", "drop_path", "=", "DropPath", "(", ")", "self", ".", "input_switch", "=", "mutables", ".", "InputChoice", "(", "choose_from", "=", "choice_keys", ",", "n_chosen", "=", "2", ",", "key", "=", "\"{}_switch\"", ".", "format", "(", "node_id", ")", ")" ]
[ 13, 4 ]
[ 45, 118 ]
python
en
['en', 'error', 'th']
False
DartsCell.forward
(self, pprev, prev)
Parameters --- pprev: torch.Tensor the output of the previous previous layer prev: torch.Tensor the output of the previous layer
Parameters --- pprev: torch.Tensor the output of the previous previous layer prev: torch.Tensor the output of the previous layer
def forward(self, pprev, prev): """ Parameters --- pprev: torch.Tensor the output of the previous previous layer prev: torch.Tensor the output of the previous layer """ tensors = [self.preproc0(pprev), self.preproc1(prev)] for node in self.mutable_ops: cur_tensor = node(tensors) tensors.append(cur_tensor) output = torch.cat(tensors[2:], dim=1) return output
[ "def", "forward", "(", "self", ",", "pprev", ",", "prev", ")", ":", "tensors", "=", "[", "self", ".", "preproc0", "(", "pprev", ")", ",", "self", ".", "preproc1", "(", "prev", ")", "]", "for", "node", "in", "self", ".", "mutable_ops", ":", "cur_tensor", "=", "node", "(", "tensors", ")", "tensors", ".", "append", "(", "cur_tensor", ")", "output", "=", "torch", ".", "cat", "(", "tensors", "[", "2", ":", "]", ",", "dim", "=", "1", ")", "return", "output" ]
[ 96, 4 ]
[ 111, 21 ]
python
en
['en', 'error', 'th']
False
async_setup_entry
(hass, config_entry, async_add_entities)
Set up the DoorBird camera platform.
Set up the DoorBird camera platform.
async def async_setup_entry(hass, config_entry, async_add_entities): """Set up the DoorBird camera platform.""" config_entry_id = config_entry.entry_id config_data = hass.data[DOMAIN][config_entry_id] doorstation = config_data[DOOR_STATION] doorstation_info = config_data[DOOR_STATION_INFO] device = doorstation.device async_add_entities( [ DoorBirdCamera( doorstation, doorstation_info, device.live_image_url, "live", f"{doorstation.name} Live", doorstation.doorstation_events, _LIVE_INTERVAL, device.rtsp_live_video_url, ), DoorBirdCamera( doorstation, doorstation_info, device.history_image_url(1, "doorbell"), "last_ring", f"{doorstation.name} Last Ring", [], _LAST_VISITOR_INTERVAL, ), DoorBirdCamera( doorstation, doorstation_info, device.history_image_url(1, "motionsensor"), "last_motion", f"{doorstation.name} Last Motion", [], _LAST_MOTION_INTERVAL, ), ] )
[ "async", "def", "async_setup_entry", "(", "hass", ",", "config_entry", ",", "async_add_entities", ")", ":", "config_entry_id", "=", "config_entry", ".", "entry_id", "config_data", "=", "hass", ".", "data", "[", "DOMAIN", "]", "[", "config_entry_id", "]", "doorstation", "=", "config_data", "[", "DOOR_STATION", "]", "doorstation_info", "=", "config_data", "[", "DOOR_STATION_INFO", "]", "device", "=", "doorstation", ".", "device", "async_add_entities", "(", "[", "DoorBirdCamera", "(", "doorstation", ",", "doorstation_info", ",", "device", ".", "live_image_url", ",", "\"live\"", ",", "f\"{doorstation.name} Live\"", ",", "doorstation", ".", "doorstation_events", ",", "_LIVE_INTERVAL", ",", "device", ".", "rtsp_live_video_url", ",", ")", ",", "DoorBirdCamera", "(", "doorstation", ",", "doorstation_info", ",", "device", ".", "history_image_url", "(", "1", ",", "\"doorbell\"", ")", ",", "\"last_ring\"", ",", "f\"{doorstation.name} Last Ring\"", ",", "[", "]", ",", "_LAST_VISITOR_INTERVAL", ",", ")", ",", "DoorBirdCamera", "(", "doorstation", ",", "doorstation_info", ",", "device", ".", "history_image_url", "(", "1", ",", "\"motionsensor\"", ")", ",", "\"last_motion\"", ",", "f\"{doorstation.name} Last Motion\"", ",", "[", "]", ",", "_LAST_MOTION_INTERVAL", ",", ")", ",", "]", ")" ]
[ 27, 0 ]
[ 66, 5 ]
python
en
['en', 'lv', 'en']
True
DoorBirdCamera.__init__
( self, doorstation, doorstation_info, url, camera_id, name, doorstation_events, interval=None, stream_url=None, )
Initialize the camera on a DoorBird device.
Initialize the camera on a DoorBird device.
def __init__( self, doorstation, doorstation_info, url, camera_id, name, doorstation_events, interval=None, stream_url=None, ): """Initialize the camera on a DoorBird device.""" super().__init__(doorstation, doorstation_info) self._url = url self._stream_url = stream_url self._name = name self._last_image = None self._supported_features = SUPPORT_STREAM if self._stream_url else 0 self._interval = interval or datetime.timedelta self._last_update = datetime.datetime.min self._unique_id = f"{self._mac_addr}_{camera_id}" self._doorstation_events = doorstation_events
[ "def", "__init__", "(", "self", ",", "doorstation", ",", "doorstation_info", ",", "url", ",", "camera_id", ",", "name", ",", "doorstation_events", ",", "interval", "=", "None", ",", "stream_url", "=", "None", ",", ")", ":", "super", "(", ")", ".", "__init__", "(", "doorstation", ",", "doorstation_info", ")", "self", ".", "_url", "=", "url", "self", ".", "_stream_url", "=", "stream_url", "self", ".", "_name", "=", "name", "self", ".", "_last_image", "=", "None", "self", ".", "_supported_features", "=", "SUPPORT_STREAM", "if", "self", ".", "_stream_url", "else", "0", "self", ".", "_interval", "=", "interval", "or", "datetime", ".", "timedelta", "self", ".", "_last_update", "=", "datetime", ".", "datetime", ".", "min", "self", ".", "_unique_id", "=", "f\"{self._mac_addr}_{camera_id}\"", "self", ".", "_doorstation_events", "=", "doorstation_events" ]
[ 72, 4 ]
[ 93, 53 ]
python
en
['en', 'en', 'en']
True
DoorBirdCamera.stream_source
(self)
Return the stream source.
Return the stream source.
async def stream_source(self): """Return the stream source.""" return self._stream_url
[ "async", "def", "stream_source", "(", "self", ")", ":", "return", "self", ".", "_stream_url" ]
[ 95, 4 ]
[ 97, 31 ]
python
en
['en', 'ig', 'en']
True
DoorBirdCamera.unique_id
(self)
Camera Unique id.
Camera Unique id.
def unique_id(self): """Camera Unique id.""" return self._unique_id
[ "def", "unique_id", "(", "self", ")", ":", "return", "self", ".", "_unique_id" ]
[ 100, 4 ]
[ 102, 30 ]
python
it
['fr', 'it', 'it']
True
DoorBirdCamera.supported_features
(self)
Return supported features.
Return supported features.
def supported_features(self): """Return supported features.""" return self._supported_features
[ "def", "supported_features", "(", "self", ")", ":", "return", "self", ".", "_supported_features" ]
[ 105, 4 ]
[ 107, 39 ]
python
en
['en', 'en', 'en']
True
DoorBirdCamera.name
(self)
Get the name of the camera.
Get the name of the camera.
def name(self): """Get the name of the camera.""" return self._name
[ "def", "name", "(", "self", ")", ":", "return", "self", ".", "_name" ]
[ 110, 4 ]
[ 112, 25 ]
python
en
['en', 'en', 'en']
True
DoorBirdCamera.async_camera_image
(self)
Pull a still image from the camera.
Pull a still image from the camera.
async def async_camera_image(self): """Pull a still image from the camera.""" now = dt_util.utcnow() if self._last_image and now - self._last_update < self._interval: return self._last_image try: websession = async_get_clientsession(self.hass) with async_timeout.timeout(_TIMEOUT): response = await websession.get(self._url) self._last_image = await response.read() self._last_update = now return self._last_image except asyncio.TimeoutError: _LOGGER.error("DoorBird %s: Camera image timed out", self._name) return self._last_image except aiohttp.ClientError as error: _LOGGER.error( "DoorBird %s: Error getting camera image: %s", self._name, error ) return self._last_image
[ "async", "def", "async_camera_image", "(", "self", ")", ":", "now", "=", "dt_util", ".", "utcnow", "(", ")", "if", "self", ".", "_last_image", "and", "now", "-", "self", ".", "_last_update", "<", "self", ".", "_interval", ":", "return", "self", ".", "_last_image", "try", ":", "websession", "=", "async_get_clientsession", "(", "self", ".", "hass", ")", "with", "async_timeout", ".", "timeout", "(", "_TIMEOUT", ")", ":", "response", "=", "await", "websession", ".", "get", "(", "self", ".", "_url", ")", "self", ".", "_last_image", "=", "await", "response", ".", "read", "(", ")", "self", ".", "_last_update", "=", "now", "return", "self", ".", "_last_image", "except", "asyncio", ".", "TimeoutError", ":", "_LOGGER", ".", "error", "(", "\"DoorBird %s: Camera image timed out\"", ",", "self", ".", "_name", ")", "return", "self", ".", "_last_image", "except", "aiohttp", ".", "ClientError", "as", "error", ":", "_LOGGER", ".", "error", "(", "\"DoorBird %s: Error getting camera image: %s\"", ",", "self", ".", "_name", ",", "error", ")", "return", "self", ".", "_last_image" ]
[ 114, 4 ]
[ 136, 35 ]
python
en
['en', 'en', 'en']
True
DoorBirdCamera.async_added_to_hass
(self)
Add callback after being added to hass. Registers entity_id map for the logbook
Add callback after being added to hass.
async def async_added_to_hass(self): """Add callback after being added to hass. Registers entity_id map for the logbook """ event_to_entity_id = self.hass.data[DOMAIN].setdefault( DOOR_STATION_EVENT_ENTITY_IDS, {} ) for event in self._doorstation_events: event_to_entity_id[event] = self.entity_id
[ "async", "def", "async_added_to_hass", "(", "self", ")", ":", "event_to_entity_id", "=", "self", ".", "hass", ".", "data", "[", "DOMAIN", "]", ".", "setdefault", "(", "DOOR_STATION_EVENT_ENTITY_IDS", ",", "{", "}", ")", "for", "event", "in", "self", ".", "_doorstation_events", ":", "event_to_entity_id", "[", "event", "]", "=", "self", ".", "entity_id" ]
[ 138, 4 ]
[ 147, 54 ]
python
en
['en', 'en', 'en']
True
DoorBirdCamera.will_remove_from_hass
(self)
Unregister entity_id map for the logbook.
Unregister entity_id map for the logbook.
async def will_remove_from_hass(self): """Unregister entity_id map for the logbook.""" event_to_entity_id = self.hass.data[DOMAIN][DOOR_STATION_EVENT_ENTITY_IDS] for event in self._doorstation_events: if event in event_to_entity_id: del event_to_entity_id[event]
[ "async", "def", "will_remove_from_hass", "(", "self", ")", ":", "event_to_entity_id", "=", "self", ".", "hass", ".", "data", "[", "DOMAIN", "]", "[", "DOOR_STATION_EVENT_ENTITY_IDS", "]", "for", "event", "in", "self", ".", "_doorstation_events", ":", "if", "event", "in", "event_to_entity_id", ":", "del", "event_to_entity_id", "[", "event", "]" ]
[ 149, 4 ]
[ 154, 45 ]
python
en
['en', 'en', 'en']
True
setup_scanner
(hass, config, see, discovery_info=None)
Set up device scanner.
Set up device scanner.
def setup_scanner(hass, config, see, discovery_info=None): """Set up device scanner.""" config = hass.data[DOMAIN]["config"] apis = hass.data[DOMAIN]["apis"] Life360Scanner(hass, config, see, apis) return True
[ "def", "setup_scanner", "(", "hass", ",", "config", ",", "see", ",", "discovery_info", "=", "None", ")", ":", "config", "=", "hass", ".", "data", "[", "DOMAIN", "]", "[", "\"config\"", "]", "apis", "=", "hass", ".", "data", "[", "DOMAIN", "]", "[", "\"apis\"", "]", "Life360Scanner", "(", "hass", ",", "config", ",", "see", ",", "apis", ")", "return", "True" ]
[ 88, 0 ]
[ 93, 15 ]
python
en
['en', 'da', 'en']
True
Life360Scanner.__init__
(self, hass, config, see, apis)
Initialize Life360Scanner.
Initialize Life360Scanner.
def __init__(self, hass, config, see, apis): """Initialize Life360Scanner.""" self._hass = hass self._see = see self._max_gps_accuracy = config.get(CONF_MAX_GPS_ACCURACY) self._max_update_wait = config.get(CONF_MAX_UPDATE_WAIT) self._prefix = config[CONF_PREFIX] self._circles_filter = config.get(CONF_CIRCLES) self._members_filter = config.get(CONF_MEMBERS) self._driving_speed = config.get(CONF_DRIVING_SPEED) self._show_as_state = config[CONF_SHOW_AS_STATE] self._apis = apis self._errs = {} self._error_threshold = config[CONF_ERROR_THRESHOLD] self._warning_threshold = config[CONF_WARNING_THRESHOLD] self._max_errs = self._error_threshold + 1 self._dev_data = {} self._circles_logged = set() self._members_logged = set() _dump_filter(self._circles_filter, "Circles") _dump_filter(self._members_filter, "device IDs", self._dev_id) self._started = dt_util.utcnow() self._update_life360() track_time_interval( self._hass, self._update_life360, config[CONF_SCAN_INTERVAL] )
[ "def", "__init__", "(", "self", ",", "hass", ",", "config", ",", "see", ",", "apis", ")", ":", "self", ".", "_hass", "=", "hass", "self", ".", "_see", "=", "see", "self", ".", "_max_gps_accuracy", "=", "config", ".", "get", "(", "CONF_MAX_GPS_ACCURACY", ")", "self", ".", "_max_update_wait", "=", "config", ".", "get", "(", "CONF_MAX_UPDATE_WAIT", ")", "self", ".", "_prefix", "=", "config", "[", "CONF_PREFIX", "]", "self", ".", "_circles_filter", "=", "config", ".", "get", "(", "CONF_CIRCLES", ")", "self", ".", "_members_filter", "=", "config", ".", "get", "(", "CONF_MEMBERS", ")", "self", ".", "_driving_speed", "=", "config", ".", "get", "(", "CONF_DRIVING_SPEED", ")", "self", ".", "_show_as_state", "=", "config", "[", "CONF_SHOW_AS_STATE", "]", "self", ".", "_apis", "=", "apis", "self", ".", "_errs", "=", "{", "}", "self", ".", "_error_threshold", "=", "config", "[", "CONF_ERROR_THRESHOLD", "]", "self", ".", "_warning_threshold", "=", "config", "[", "CONF_WARNING_THRESHOLD", "]", "self", ".", "_max_errs", "=", "self", ".", "_error_threshold", "+", "1", "self", ".", "_dev_data", "=", "{", "}", "self", ".", "_circles_logged", "=", "set", "(", ")", "self", ".", "_members_logged", "=", "set", "(", ")", "_dump_filter", "(", "self", ".", "_circles_filter", ",", "\"Circles\"", ")", "_dump_filter", "(", "self", ".", "_members_filter", ",", "\"device IDs\"", ",", "self", ".", "_dev_id", ")", "self", ".", "_started", "=", "dt_util", ".", "utcnow", "(", ")", "self", ".", "_update_life360", "(", ")", "track_time_interval", "(", "self", ".", "_hass", ",", "self", ".", "_update_life360", ",", "config", "[", "CONF_SCAN_INTERVAL", "]", ")" ]
[ 120, 4 ]
[ 147, 9 ]
python
en
['en', 'en', 'en']
False
async_setup_entry
(hass, entry, async_add_entities)
Set up Ambient PWS sensors based on a config entry.
Set up Ambient PWS sensors based on a config entry.
async def async_setup_entry(hass, entry, async_add_entities): """Set up Ambient PWS sensors based on a config entry.""" ambient = hass.data[DOMAIN][DATA_CLIENT][entry.entry_id] sensor_list = [] for mac_address, station in ambient.stations.items(): for condition in station[ATTR_MONITORED_CONDITIONS]: name, unit, kind, device_class = SENSOR_TYPES[condition] if kind == TYPE_SENSOR: sensor_list.append( AmbientWeatherSensor( ambient, mac_address, station[ATTR_NAME], condition, name, device_class, unit, ) ) async_add_entities(sensor_list, True)
[ "async", "def", "async_setup_entry", "(", "hass", ",", "entry", ",", "async_add_entities", ")", ":", "ambient", "=", "hass", ".", "data", "[", "DOMAIN", "]", "[", "DATA_CLIENT", "]", "[", "entry", ".", "entry_id", "]", "sensor_list", "=", "[", "]", "for", "mac_address", ",", "station", "in", "ambient", ".", "stations", ".", "items", "(", ")", ":", "for", "condition", "in", "station", "[", "ATTR_MONITORED_CONDITIONS", "]", ":", "name", ",", "unit", ",", "kind", ",", "device_class", "=", "SENSOR_TYPES", "[", "condition", "]", "if", "kind", "==", "TYPE_SENSOR", ":", "sensor_list", ".", "append", "(", "AmbientWeatherSensor", "(", "ambient", ",", "mac_address", ",", "station", "[", "ATTR_NAME", "]", ",", "condition", ",", "name", ",", "device_class", ",", "unit", ",", ")", ")", "async_add_entities", "(", "sensor_list", ",", "True", ")" ]
[ 19, 0 ]
[ 40, 41 ]
python
en
['en', 'en', 'en']
True
AmbientWeatherSensor.__init__
( self, ambient, mac_address, station_name, sensor_type, sensor_name, device_class, unit, )
Initialize the sensor.
Initialize the sensor.
def __init__( self, ambient, mac_address, station_name, sensor_type, sensor_name, device_class, unit, ): """Initialize the sensor.""" super().__init__( ambient, mac_address, station_name, sensor_type, sensor_name, device_class ) self._unit = unit
[ "def", "__init__", "(", "self", ",", "ambient", ",", "mac_address", ",", "station_name", ",", "sensor_type", ",", "sensor_name", ",", "device_class", ",", "unit", ",", ")", ":", "super", "(", ")", ".", "__init__", "(", "ambient", ",", "mac_address", ",", "station_name", ",", "sensor_type", ",", "sensor_name", ",", "device_class", ")", "self", ".", "_unit", "=", "unit" ]
[ 46, 4 ]
[ 61, 25 ]
python
en
['en', 'en', 'en']
True
AmbientWeatherSensor.state
(self)
Return the state of the sensor.
Return the state of the sensor.
def state(self): """Return the state of the sensor.""" return self._state
[ "def", "state", "(", "self", ")", ":", "return", "self", ".", "_state" ]
[ 64, 4 ]
[ 66, 26 ]
python
en
['en', 'en', 'en']
True
AmbientWeatherSensor.unit_of_measurement
(self)
Return the unit of measurement.
Return the unit of measurement.
def unit_of_measurement(self): """Return the unit of measurement.""" return self._unit
[ "def", "unit_of_measurement", "(", "self", ")", ":", "return", "self", ".", "_unit" ]
[ 69, 4 ]
[ 71, 25 ]
python
en
['en', 'la', 'en']
True
AmbientWeatherSensor.update_from_latest_data
(self)
Fetch new state data for the sensor.
Fetch new state data for the sensor.
def update_from_latest_data(self): """Fetch new state data for the sensor.""" if self._sensor_type == TYPE_SOLARRADIATION_LX: # If the user requests the solarradiation_lx sensor, use the # value of the solarradiation sensor and apply a very accurate # approximation of converting sunlight W/m^2 to lx: w_m2_brightness_val = self._ambient.stations[self._mac_address][ ATTR_LAST_DATA ].get(TYPE_SOLARRADIATION) if w_m2_brightness_val is None: self._state = None else: self._state = round(float(w_m2_brightness_val) / 0.0079) else: self._state = self._ambient.stations[self._mac_address][ATTR_LAST_DATA].get( self._sensor_type )
[ "def", "update_from_latest_data", "(", "self", ")", ":", "if", "self", ".", "_sensor_type", "==", "TYPE_SOLARRADIATION_LX", ":", "# If the user requests the solarradiation_lx sensor, use the", "# value of the solarradiation sensor and apply a very accurate", "# approximation of converting sunlight W/m^2 to lx:", "w_m2_brightness_val", "=", "self", ".", "_ambient", ".", "stations", "[", "self", ".", "_mac_address", "]", "[", "ATTR_LAST_DATA", "]", ".", "get", "(", "TYPE_SOLARRADIATION", ")", "if", "w_m2_brightness_val", "is", "None", ":", "self", ".", "_state", "=", "None", "else", ":", "self", ".", "_state", "=", "round", "(", "float", "(", "w_m2_brightness_val", ")", "/", "0.0079", ")", "else", ":", "self", ".", "_state", "=", "self", ".", "_ambient", ".", "stations", "[", "self", ".", "_mac_address", "]", "[", "ATTR_LAST_DATA", "]", ".", "get", "(", "self", ".", "_sensor_type", ")" ]
[ 74, 4 ]
[ 91, 13 ]
python
en
['en', 'en', 'en']
True
test_split_entity_id
()
Test split_entity_id.
Test split_entity_id.
def test_split_entity_id(): """Test split_entity_id.""" assert ha.split_entity_id("domain.object_id") == ["domain", "object_id"]
[ "def", "test_split_entity_id", "(", ")", ":", "assert", "ha", ".", "split_entity_id", "(", "\"domain.object_id\"", ")", "==", "[", "\"domain\"", ",", "\"object_id\"", "]" ]
[ 48, 0 ]
[ 50, 76 ]
python
en
['en', 'pl', 'en']
False
test_async_add_hass_job_schedule_callback
()
Test that we schedule coroutines and add jobs to the job pool.
Test that we schedule coroutines and add jobs to the job pool.
def test_async_add_hass_job_schedule_callback(): """Test that we schedule coroutines and add jobs to the job pool.""" hass = MagicMock() job = MagicMock() ha.HomeAssistant.async_add_hass_job(hass, ha.HassJob(ha.callback(job))) assert len(hass.loop.call_soon.mock_calls) == 1 assert len(hass.loop.create_task.mock_calls) == 0 assert len(hass.add_job.mock_calls) == 0
[ "def", "test_async_add_hass_job_schedule_callback", "(", ")", ":", "hass", "=", "MagicMock", "(", ")", "job", "=", "MagicMock", "(", ")", "ha", ".", "HomeAssistant", ".", "async_add_hass_job", "(", "hass", ",", "ha", ".", "HassJob", "(", "ha", ".", "callback", "(", "job", ")", ")", ")", "assert", "len", "(", "hass", ".", "loop", ".", "call_soon", ".", "mock_calls", ")", "==", "1", "assert", "len", "(", "hass", ".", "loop", ".", "create_task", ".", "mock_calls", ")", "==", "0", "assert", "len", "(", "hass", ".", "add_job", ".", "mock_calls", ")", "==", "0" ]
[ 53, 0 ]
[ 61, 44 ]
python
en
['en', 'en', 'en']
True
test_async_add_hass_job_schedule_partial_callback
()
Test that we schedule partial coros and add jobs to the job pool.
Test that we schedule partial coros and add jobs to the job pool.
def test_async_add_hass_job_schedule_partial_callback(): """Test that we schedule partial coros and add jobs to the job pool.""" hass = MagicMock() job = MagicMock() partial = functools.partial(ha.callback(job)) ha.HomeAssistant.async_add_hass_job(hass, ha.HassJob(partial)) assert len(hass.loop.call_soon.mock_calls) == 1 assert len(hass.loop.create_task.mock_calls) == 0 assert len(hass.add_job.mock_calls) == 0
[ "def", "test_async_add_hass_job_schedule_partial_callback", "(", ")", ":", "hass", "=", "MagicMock", "(", ")", "job", "=", "MagicMock", "(", ")", "partial", "=", "functools", ".", "partial", "(", "ha", ".", "callback", "(", "job", ")", ")", "ha", ".", "HomeAssistant", ".", "async_add_hass_job", "(", "hass", ",", "ha", ".", "HassJob", "(", "partial", ")", ")", "assert", "len", "(", "hass", ".", "loop", ".", "call_soon", ".", "mock_calls", ")", "==", "1", "assert", "len", "(", "hass", ".", "loop", ".", "create_task", ".", "mock_calls", ")", "==", "0", "assert", "len", "(", "hass", ".", "add_job", ".", "mock_calls", ")", "==", "0" ]
[ 64, 0 ]
[ 73, 44 ]
python
en
['en', 'en', 'en']
True
test_async_add_hass_job_schedule_coroutinefunction
(loop)
Test that we schedule coroutines and add jobs to the job pool.
Test that we schedule coroutines and add jobs to the job pool.
def test_async_add_hass_job_schedule_coroutinefunction(loop): """Test that we schedule coroutines and add jobs to the job pool.""" hass = MagicMock(loop=MagicMock(wraps=loop)) async def job(): pass ha.HomeAssistant.async_add_hass_job(hass, ha.HassJob(job)) assert len(hass.loop.call_soon.mock_calls) == 0 assert len(hass.loop.create_task.mock_calls) == 1 assert len(hass.add_job.mock_calls) == 0
[ "def", "test_async_add_hass_job_schedule_coroutinefunction", "(", "loop", ")", ":", "hass", "=", "MagicMock", "(", "loop", "=", "MagicMock", "(", "wraps", "=", "loop", ")", ")", "async", "def", "job", "(", ")", ":", "pass", "ha", ".", "HomeAssistant", ".", "async_add_hass_job", "(", "hass", ",", "ha", ".", "HassJob", "(", "job", ")", ")", "assert", "len", "(", "hass", ".", "loop", ".", "call_soon", ".", "mock_calls", ")", "==", "0", "assert", "len", "(", "hass", ".", "loop", ".", "create_task", ".", "mock_calls", ")", "==", "1", "assert", "len", "(", "hass", ".", "add_job", ".", "mock_calls", ")", "==", "0" ]
[ 76, 0 ]
[ 86, 44 ]
python
en
['en', 'en', 'en']
True
test_async_add_hass_job_schedule_partial_coroutinefunction
(loop)
Test that we schedule partial coros and add jobs to the job pool.
Test that we schedule partial coros and add jobs to the job pool.
def test_async_add_hass_job_schedule_partial_coroutinefunction(loop): """Test that we schedule partial coros and add jobs to the job pool.""" hass = MagicMock(loop=MagicMock(wraps=loop)) async def job(): pass partial = functools.partial(job) ha.HomeAssistant.async_add_hass_job(hass, ha.HassJob(partial)) assert len(hass.loop.call_soon.mock_calls) == 0 assert len(hass.loop.create_task.mock_calls) == 1 assert len(hass.add_job.mock_calls) == 0
[ "def", "test_async_add_hass_job_schedule_partial_coroutinefunction", "(", "loop", ")", ":", "hass", "=", "MagicMock", "(", "loop", "=", "MagicMock", "(", "wraps", "=", "loop", ")", ")", "async", "def", "job", "(", ")", ":", "pass", "partial", "=", "functools", ".", "partial", "(", "job", ")", "ha", ".", "HomeAssistant", ".", "async_add_hass_job", "(", "hass", ",", "ha", ".", "HassJob", "(", "partial", ")", ")", "assert", "len", "(", "hass", ".", "loop", ".", "call_soon", ".", "mock_calls", ")", "==", "0", "assert", "len", "(", "hass", ".", "loop", ".", "create_task", ".", "mock_calls", ")", "==", "1", "assert", "len", "(", "hass", ".", "add_job", ".", "mock_calls", ")", "==", "0" ]
[ 89, 0 ]
[ 101, 44 ]
python
en
['en', 'en', 'en']
True
test_async_add_job_add_hass_threaded_job_to_pool
()
Test that we schedule coroutines and add jobs to the job pool.
Test that we schedule coroutines and add jobs to the job pool.
def test_async_add_job_add_hass_threaded_job_to_pool(): """Test that we schedule coroutines and add jobs to the job pool.""" hass = MagicMock() def job(): pass ha.HomeAssistant.async_add_hass_job(hass, ha.HassJob(job)) assert len(hass.loop.call_soon.mock_calls) == 0 assert len(hass.loop.create_task.mock_calls) == 0 assert len(hass.loop.run_in_executor.mock_calls) == 1
[ "def", "test_async_add_job_add_hass_threaded_job_to_pool", "(", ")", ":", "hass", "=", "MagicMock", "(", ")", "def", "job", "(", ")", ":", "pass", "ha", ".", "HomeAssistant", ".", "async_add_hass_job", "(", "hass", ",", "ha", ".", "HassJob", "(", "job", ")", ")", "assert", "len", "(", "hass", ".", "loop", ".", "call_soon", ".", "mock_calls", ")", "==", "0", "assert", "len", "(", "hass", ".", "loop", ".", "create_task", ".", "mock_calls", ")", "==", "0", "assert", "len", "(", "hass", ".", "loop", ".", "run_in_executor", ".", "mock_calls", ")", "==", "1" ]
[ 104, 0 ]
[ 114, 57 ]
python
en
['en', 'en', 'en']
True
test_async_create_task_schedule_coroutine
(loop)
Test that we schedule coroutines and add jobs to the job pool.
Test that we schedule coroutines and add jobs to the job pool.
def test_async_create_task_schedule_coroutine(loop): """Test that we schedule coroutines and add jobs to the job pool.""" hass = MagicMock(loop=MagicMock(wraps=loop)) async def job(): pass ha.HomeAssistant.async_create_task(hass, job()) assert len(hass.loop.call_soon.mock_calls) == 0 assert len(hass.loop.create_task.mock_calls) == 1 assert len(hass.add_job.mock_calls) == 0
[ "def", "test_async_create_task_schedule_coroutine", "(", "loop", ")", ":", "hass", "=", "MagicMock", "(", "loop", "=", "MagicMock", "(", "wraps", "=", "loop", ")", ")", "async", "def", "job", "(", ")", ":", "pass", "ha", ".", "HomeAssistant", ".", "async_create_task", "(", "hass", ",", "job", "(", ")", ")", "assert", "len", "(", "hass", ".", "loop", ".", "call_soon", ".", "mock_calls", ")", "==", "0", "assert", "len", "(", "hass", ".", "loop", ".", "create_task", ".", "mock_calls", ")", "==", "1", "assert", "len", "(", "hass", ".", "add_job", ".", "mock_calls", ")", "==", "0" ]
[ 117, 0 ]
[ 127, 44 ]
python
en
['en', 'en', 'en']
True
test_async_run_hass_job_calls_callback
()
Test that the callback annotation is respected.
Test that the callback annotation is respected.
def test_async_run_hass_job_calls_callback(): """Test that the callback annotation is respected.""" hass = MagicMock() calls = [] def job(): calls.append(1) ha.HomeAssistant.async_run_hass_job(hass, ha.HassJob(ha.callback(job))) assert len(calls) == 1 assert len(hass.async_add_job.mock_calls) == 0
[ "def", "test_async_run_hass_job_calls_callback", "(", ")", ":", "hass", "=", "MagicMock", "(", ")", "calls", "=", "[", "]", "def", "job", "(", ")", ":", "calls", ".", "append", "(", "1", ")", "ha", ".", "HomeAssistant", ".", "async_run_hass_job", "(", "hass", ",", "ha", ".", "HassJob", "(", "ha", ".", "callback", "(", "job", ")", ")", ")", "assert", "len", "(", "calls", ")", "==", "1", "assert", "len", "(", "hass", ".", "async_add_job", ".", "mock_calls", ")", "==", "0" ]
[ 130, 0 ]
[ 140, 50 ]
python
en
['en', 'en', 'en']
True
test_async_run_hass_job_delegates_non_async
()
Test that the callback annotation is respected.
Test that the callback annotation is respected.
def test_async_run_hass_job_delegates_non_async(): """Test that the callback annotation is respected.""" hass = MagicMock() calls = [] def job(): calls.append(1) ha.HomeAssistant.async_run_hass_job(hass, ha.HassJob(job)) assert len(calls) == 0 assert len(hass.async_add_hass_job.mock_calls) == 1
[ "def", "test_async_run_hass_job_delegates_non_async", "(", ")", ":", "hass", "=", "MagicMock", "(", ")", "calls", "=", "[", "]", "def", "job", "(", ")", ":", "calls", ".", "append", "(", "1", ")", "ha", ".", "HomeAssistant", ".", "async_run_hass_job", "(", "hass", ",", "ha", ".", "HassJob", "(", "job", ")", ")", "assert", "len", "(", "calls", ")", "==", "0", "assert", "len", "(", "hass", ".", "async_add_hass_job", ".", "mock_calls", ")", "==", "1" ]
[ 143, 0 ]
[ 153, 55 ]
python
en
['en', 'en', 'en']
True
test_stage_shutdown
(hass)
Simulate a shutdown, test calling stuff.
Simulate a shutdown, test calling stuff.
async def test_stage_shutdown(hass): """Simulate a shutdown, test calling stuff.""" test_stop = async_capture_events(hass, EVENT_HOMEASSISTANT_STOP) test_final_write = async_capture_events(hass, EVENT_HOMEASSISTANT_FINAL_WRITE) test_close = async_capture_events(hass, EVENT_HOMEASSISTANT_CLOSE) test_all = async_capture_events(hass, MATCH_ALL) await hass.async_stop() assert len(test_stop) == 1 assert len(test_close) == 1 assert len(test_final_write) == 1 assert len(test_all) == 2
[ "async", "def", "test_stage_shutdown", "(", "hass", ")", ":", "test_stop", "=", "async_capture_events", "(", "hass", ",", "EVENT_HOMEASSISTANT_STOP", ")", "test_final_write", "=", "async_capture_events", "(", "hass", ",", "EVENT_HOMEASSISTANT_FINAL_WRITE", ")", "test_close", "=", "async_capture_events", "(", "hass", ",", "EVENT_HOMEASSISTANT_CLOSE", ")", "test_all", "=", "async_capture_events", "(", "hass", ",", "MATCH_ALL", ")", "await", "hass", ".", "async_stop", "(", ")", "assert", "len", "(", "test_stop", ")", "==", "1", "assert", "len", "(", "test_close", ")", "==", "1", "assert", "len", "(", "test_final_write", ")", "==", "1", "assert", "len", "(", "test_all", ")", "==", "2" ]
[ 156, 0 ]
[ 168, 29 ]
python
en
['en', 'co', 'en']
True
test_pending_sheduler
(hass)
Add a coro to pending tasks.
Add a coro to pending tasks.
async def test_pending_sheduler(hass): """Add a coro to pending tasks.""" call_count = [] async def test_coro(): """Test Coro.""" call_count.append("call") for _ in range(3): hass.async_add_job(test_coro()) await asyncio.wait(hass._pending_tasks) assert len(hass._pending_tasks) == 3 assert len(call_count) == 3
[ "async", "def", "test_pending_sheduler", "(", "hass", ")", ":", "call_count", "=", "[", "]", "async", "def", "test_coro", "(", ")", ":", "\"\"\"Test Coro.\"\"\"", "call_count", ".", "append", "(", "\"call\"", ")", "for", "_", "in", "range", "(", "3", ")", ":", "hass", ".", "async_add_job", "(", "test_coro", "(", ")", ")", "await", "asyncio", ".", "wait", "(", "hass", ".", "_pending_tasks", ")", "assert", "len", "(", "hass", ".", "_pending_tasks", ")", "==", "3", "assert", "len", "(", "call_count", ")", "==", "3" ]
[ 171, 0 ]
[ 185, 31 ]
python
en
['en', 'en', 'en']
True
test_async_add_job_pending_tasks_coro
(hass)
Add a coro to pending tasks.
Add a coro to pending tasks.
async def test_async_add_job_pending_tasks_coro(hass): """Add a coro to pending tasks.""" call_count = [] async def test_coro(): """Test Coro.""" call_count.append("call") for _ in range(2): hass.add_job(test_coro()) async def wait_finish_callback(): """Wait until all stuff is scheduled.""" await asyncio.sleep(0) await asyncio.sleep(0) await wait_finish_callback() assert len(hass._pending_tasks) == 2 await hass.async_block_till_done() assert len(call_count) == 2
[ "async", "def", "test_async_add_job_pending_tasks_coro", "(", "hass", ")", ":", "call_count", "=", "[", "]", "async", "def", "test_coro", "(", ")", ":", "\"\"\"Test Coro.\"\"\"", "call_count", ".", "append", "(", "\"call\"", ")", "for", "_", "in", "range", "(", "2", ")", ":", "hass", ".", "add_job", "(", "test_coro", "(", ")", ")", "async", "def", "wait_finish_callback", "(", ")", ":", "\"\"\"Wait until all stuff is scheduled.\"\"\"", "await", "asyncio", ".", "sleep", "(", "0", ")", "await", "asyncio", ".", "sleep", "(", "0", ")", "await", "wait_finish_callback", "(", ")", "assert", "len", "(", "hass", ".", "_pending_tasks", ")", "==", "2", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "call_count", ")", "==", "2" ]
[ 188, 0 ]
[ 208, 31 ]
python
en
['en', 'en', 'en']
True
test_async_add_job_pending_tasks_executor
(hass)
Run an executor in pending tasks.
Run an executor in pending tasks.
async def test_async_add_job_pending_tasks_executor(hass): """Run an executor in pending tasks.""" call_count = [] def test_executor(): """Test executor.""" call_count.append("call") async def wait_finish_callback(): """Wait until all stuff is scheduled.""" await asyncio.sleep(0) await asyncio.sleep(0) for _ in range(2): hass.async_add_job(test_executor) await wait_finish_callback() assert len(hass._pending_tasks) == 2 await hass.async_block_till_done() assert len(call_count) == 2
[ "async", "def", "test_async_add_job_pending_tasks_executor", "(", "hass", ")", ":", "call_count", "=", "[", "]", "def", "test_executor", "(", ")", ":", "\"\"\"Test executor.\"\"\"", "call_count", ".", "append", "(", "\"call\"", ")", "async", "def", "wait_finish_callback", "(", ")", ":", "\"\"\"Wait until all stuff is scheduled.\"\"\"", "await", "asyncio", ".", "sleep", "(", "0", ")", "await", "asyncio", ".", "sleep", "(", "0", ")", "for", "_", "in", "range", "(", "2", ")", ":", "hass", ".", "async_add_job", "(", "test_executor", ")", "await", "wait_finish_callback", "(", ")", "assert", "len", "(", "hass", ".", "_pending_tasks", ")", "==", "2", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "call_count", ")", "==", "2" ]
[ 211, 0 ]
[ 231, 31 ]
python
en
['en', 'gl', 'en']
True
test_async_add_job_pending_tasks_callback
(hass)
Run a callback in pending tasks.
Run a callback in pending tasks.
async def test_async_add_job_pending_tasks_callback(hass): """Run a callback in pending tasks.""" call_count = [] @ha.callback def test_callback(): """Test callback.""" call_count.append("call") async def wait_finish_callback(): """Wait until all stuff is scheduled.""" await asyncio.sleep(0) await asyncio.sleep(0) for _ in range(2): hass.async_add_job(test_callback) await wait_finish_callback() await hass.async_block_till_done() assert len(hass._pending_tasks) == 0 assert len(call_count) == 2
[ "async", "def", "test_async_add_job_pending_tasks_callback", "(", "hass", ")", ":", "call_count", "=", "[", "]", "@", "ha", ".", "callback", "def", "test_callback", "(", ")", ":", "\"\"\"Test callback.\"\"\"", "call_count", ".", "append", "(", "\"call\"", ")", "async", "def", "wait_finish_callback", "(", ")", ":", "\"\"\"Wait until all stuff is scheduled.\"\"\"", "await", "asyncio", ".", "sleep", "(", "0", ")", "await", "asyncio", ".", "sleep", "(", "0", ")", "for", "_", "in", "range", "(", "2", ")", ":", "hass", ".", "async_add_job", "(", "test_callback", ")", "await", "wait_finish_callback", "(", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "hass", ".", "_pending_tasks", ")", "==", "0", "assert", "len", "(", "call_count", ")", "==", "2" ]
[ 234, 0 ]
[ 256, 31 ]
python
id
['id', 'id', 'en']
True
test_add_job_with_none
(hass)
Try to add a job with None as function.
Try to add a job with None as function.
async def test_add_job_with_none(hass): """Try to add a job with None as function.""" with pytest.raises(ValueError): hass.async_add_job(None, "test_arg")
[ "async", "def", "test_add_job_with_none", "(", "hass", ")", ":", "with", "pytest", ".", "raises", "(", "ValueError", ")", ":", "hass", ".", "async_add_job", "(", "None", ",", "\"test_arg\"", ")" ]
[ 259, 0 ]
[ 262, 44 ]
python
en
['en', 'en', 'en']
True
test_event_eq
()
Test events.
Test events.
def test_event_eq(): """Test events.""" now = dt_util.utcnow() data = {"some": "attr"} context = ha.Context() event1, event2 = [ ha.Event("some_type", data, time_fired=now, context=context) for _ in range(2) ] assert event1 == event2
[ "def", "test_event_eq", "(", ")", ":", "now", "=", "dt_util", ".", "utcnow", "(", ")", "data", "=", "{", "\"some\"", ":", "\"attr\"", "}", "context", "=", "ha", ".", "Context", "(", ")", "event1", ",", "event2", "=", "[", "ha", ".", "Event", "(", "\"some_type\"", ",", "data", ",", "time_fired", "=", "now", ",", "context", "=", "context", ")", "for", "_", "in", "range", "(", "2", ")", "]", "assert", "event1", "==", "event2" ]
[ 265, 0 ]
[ 274, 27 ]
python
en
['de', 'en', 'en']
False
test_event_repr
()
Test that Event repr method works.
Test that Event repr method works.
def test_event_repr(): """Test that Event repr method works.""" assert str(ha.Event("TestEvent")) == "<Event TestEvent[L]>" assert ( str(ha.Event("TestEvent", {"beer": "nice"}, ha.EventOrigin.remote)) == "<Event TestEvent[R]: beer=nice>" )
[ "def", "test_event_repr", "(", ")", ":", "assert", "str", "(", "ha", ".", "Event", "(", "\"TestEvent\"", ")", ")", "==", "\"<Event TestEvent[L]>\"", "assert", "(", "str", "(", "ha", ".", "Event", "(", "\"TestEvent\"", ",", "{", "\"beer\"", ":", "\"nice\"", "}", ",", "ha", ".", "EventOrigin", ".", "remote", ")", ")", "==", "\"<Event TestEvent[R]: beer=nice>\"", ")" ]
[ 277, 0 ]
[ 284, 5 ]
python
en
['en', 'en', 'en']
True
test_event_as_dict
()
Test an Event as dictionary.
Test an Event as dictionary.
def test_event_as_dict(): """Test an Event as dictionary.""" event_type = "some_type" now = dt_util.utcnow() data = {"some": "attr"} event = ha.Event(event_type, data, ha.EventOrigin.local, now) expected = { "event_type": event_type, "data": data, "origin": "LOCAL", "time_fired": now.isoformat(), "context": { "id": event.context.id, "parent_id": None, "user_id": event.context.user_id, }, } assert event.as_dict() == expected # 2nd time to verify cache assert event.as_dict() == expected
[ "def", "test_event_as_dict", "(", ")", ":", "event_type", "=", "\"some_type\"", "now", "=", "dt_util", ".", "utcnow", "(", ")", "data", "=", "{", "\"some\"", ":", "\"attr\"", "}", "event", "=", "ha", ".", "Event", "(", "event_type", ",", "data", ",", "ha", ".", "EventOrigin", ".", "local", ",", "now", ")", "expected", "=", "{", "\"event_type\"", ":", "event_type", ",", "\"data\"", ":", "data", ",", "\"origin\"", ":", "\"LOCAL\"", ",", "\"time_fired\"", ":", "now", ".", "isoformat", "(", ")", ",", "\"context\"", ":", "{", "\"id\"", ":", "event", ".", "context", ".", "id", ",", "\"parent_id\"", ":", "None", ",", "\"user_id\"", ":", "event", ".", "context", ".", "user_id", ",", "}", ",", "}", "assert", "event", ".", "as_dict", "(", ")", "==", "expected", "# 2nd time to verify cache", "assert", "event", ".", "as_dict", "(", ")", "==", "expected" ]
[ 287, 0 ]
[ 307, 38 ]
python
en
['en', 'en', 'en']
True
test_state_as_dict
()
Test a State as dictionary.
Test a State as dictionary.
def test_state_as_dict(): """Test a State as dictionary.""" last_time = datetime(1984, 12, 8, 12, 0, 0) state = ha.State( "happy.happy", "on", {"pig": "dog"}, last_updated=last_time, last_changed=last_time, ) expected = { "context": { "id": state.context.id, "parent_id": None, "user_id": state.context.user_id, }, "entity_id": "happy.happy", "attributes": {"pig": "dog"}, "last_changed": last_time.isoformat(), "last_updated": last_time.isoformat(), "state": "on", } assert state.as_dict() == expected # 2nd time to verify cache assert state.as_dict() == expected assert state.as_dict() is state.as_dict()
[ "def", "test_state_as_dict", "(", ")", ":", "last_time", "=", "datetime", "(", "1984", ",", "12", ",", "8", ",", "12", ",", "0", ",", "0", ")", "state", "=", "ha", ".", "State", "(", "\"happy.happy\"", ",", "\"on\"", ",", "{", "\"pig\"", ":", "\"dog\"", "}", ",", "last_updated", "=", "last_time", ",", "last_changed", "=", "last_time", ",", ")", "expected", "=", "{", "\"context\"", ":", "{", "\"id\"", ":", "state", ".", "context", ".", "id", ",", "\"parent_id\"", ":", "None", ",", "\"user_id\"", ":", "state", ".", "context", ".", "user_id", ",", "}", ",", "\"entity_id\"", ":", "\"happy.happy\"", ",", "\"attributes\"", ":", "{", "\"pig\"", ":", "\"dog\"", "}", ",", "\"last_changed\"", ":", "last_time", ".", "isoformat", "(", ")", ",", "\"last_updated\"", ":", "last_time", ".", "isoformat", "(", ")", ",", "\"state\"", ":", "\"on\"", ",", "}", "assert", "state", ".", "as_dict", "(", ")", "==", "expected", "# 2nd time to verify cache", "assert", "state", ".", "as_dict", "(", ")", "==", "expected", "assert", "state", ".", "as_dict", "(", ")", "is", "state", ".", "as_dict", "(", ")" ]
[ 310, 0 ]
[ 335, 45 ]
python
en
['pt', 'en', 'en']
True
test_eventbus_add_remove_listener
(hass)
Test remove_listener method.
Test remove_listener method.
async def test_eventbus_add_remove_listener(hass): """Test remove_listener method.""" old_count = len(hass.bus.async_listeners()) def listener(_): pass unsub = hass.bus.async_listen("test", listener) assert old_count + 1 == len(hass.bus.async_listeners()) # Remove listener unsub() assert old_count == len(hass.bus.async_listeners()) # Should do nothing now unsub()
[ "async", "def", "test_eventbus_add_remove_listener", "(", "hass", ")", ":", "old_count", "=", "len", "(", "hass", ".", "bus", ".", "async_listeners", "(", ")", ")", "def", "listener", "(", "_", ")", ":", "pass", "unsub", "=", "hass", ".", "bus", ".", "async_listen", "(", "\"test\"", ",", "listener", ")", "assert", "old_count", "+", "1", "==", "len", "(", "hass", ".", "bus", ".", "async_listeners", "(", ")", ")", "# Remove listener", "unsub", "(", ")", "assert", "old_count", "==", "len", "(", "hass", ".", "bus", ".", "async_listeners", "(", ")", ")", "# Should do nothing now", "unsub", "(", ")" ]
[ 338, 0 ]
[ 354, 11 ]
python
en
['en', 'et', 'en']
True
test_eventbus_unsubscribe_listener
(hass)
Test unsubscribe listener from returned function.
Test unsubscribe listener from returned function.
async def test_eventbus_unsubscribe_listener(hass): """Test unsubscribe listener from returned function.""" calls = [] @ha.callback def listener(event): """Mock listener.""" calls.append(event) unsub = hass.bus.async_listen("test", listener) hass.bus.async_fire("test") await hass.async_block_till_done() assert len(calls) == 1 unsub() hass.bus.async_fire("event") await hass.async_block_till_done() assert len(calls) == 1
[ "async", "def", "test_eventbus_unsubscribe_listener", "(", "hass", ")", ":", "calls", "=", "[", "]", "@", "ha", ".", "callback", "def", "listener", "(", "event", ")", ":", "\"\"\"Mock listener.\"\"\"", "calls", ".", "append", "(", "event", ")", "unsub", "=", "hass", ".", "bus", ".", "async_listen", "(", "\"test\"", ",", "listener", ")", "hass", ".", "bus", ".", "async_fire", "(", "\"test\"", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "calls", ")", "==", "1", "unsub", "(", ")", "hass", ".", "bus", ".", "async_fire", "(", "\"event\"", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "calls", ")", "==", "1" ]
[ 357, 0 ]
[ 378, 26 ]
python
en
['en', 'en', 'en']
True
test_eventbus_listen_once_event_with_callback
(hass)
Test listen_once_event method.
Test listen_once_event method.
async def test_eventbus_listen_once_event_with_callback(hass): """Test listen_once_event method.""" runs = [] @ha.callback def event_handler(event): runs.append(event) hass.bus.async_listen_once("test_event", event_handler) hass.bus.async_fire("test_event") # Second time it should not increase runs hass.bus.async_fire("test_event") await hass.async_block_till_done() assert len(runs) == 1
[ "async", "def", "test_eventbus_listen_once_event_with_callback", "(", "hass", ")", ":", "runs", "=", "[", "]", "@", "ha", ".", "callback", "def", "event_handler", "(", "event", ")", ":", "runs", ".", "append", "(", "event", ")", "hass", ".", "bus", ".", "async_listen_once", "(", "\"test_event\"", ",", "event_handler", ")", "hass", ".", "bus", ".", "async_fire", "(", "\"test_event\"", ")", "# Second time it should not increase runs", "hass", ".", "bus", ".", "async_fire", "(", "\"test_event\"", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "runs", ")", "==", "1" ]
[ 381, 0 ]
[ 396, 25 ]
python
en
['en', 'da', 'en']
True
test_eventbus_listen_once_event_with_coroutine
(hass)
Test listen_once_event method.
Test listen_once_event method.
async def test_eventbus_listen_once_event_with_coroutine(hass): """Test listen_once_event method.""" runs = [] async def event_handler(event): runs.append(event) hass.bus.async_listen_once("test_event", event_handler) hass.bus.async_fire("test_event") # Second time it should not increase runs hass.bus.async_fire("test_event") await hass.async_block_till_done() assert len(runs) == 1
[ "async", "def", "test_eventbus_listen_once_event_with_coroutine", "(", "hass", ")", ":", "runs", "=", "[", "]", "async", "def", "event_handler", "(", "event", ")", ":", "runs", ".", "append", "(", "event", ")", "hass", ".", "bus", ".", "async_listen_once", "(", "\"test_event\"", ",", "event_handler", ")", "hass", ".", "bus", ".", "async_fire", "(", "\"test_event\"", ")", "# Second time it should not increase runs", "hass", ".", "bus", ".", "async_fire", "(", "\"test_event\"", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "runs", ")", "==", "1" ]
[ 399, 0 ]
[ 413, 25 ]
python
en
['en', 'da', 'en']
True
test_eventbus_listen_once_event_with_thread
(hass)
Test listen_once_event method.
Test listen_once_event method.
async def test_eventbus_listen_once_event_with_thread(hass): """Test listen_once_event method.""" runs = [] def event_handler(event): runs.append(event) hass.bus.async_listen_once("test_event", event_handler) hass.bus.async_fire("test_event") # Second time it should not increase runs hass.bus.async_fire("test_event") await hass.async_block_till_done() assert len(runs) == 1
[ "async", "def", "test_eventbus_listen_once_event_with_thread", "(", "hass", ")", ":", "runs", "=", "[", "]", "def", "event_handler", "(", "event", ")", ":", "runs", ".", "append", "(", "event", ")", "hass", ".", "bus", ".", "async_listen_once", "(", "\"test_event\"", ",", "event_handler", ")", "hass", ".", "bus", ".", "async_fire", "(", "\"test_event\"", ")", "# Second time it should not increase runs", "hass", ".", "bus", ".", "async_fire", "(", "\"test_event\"", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "runs", ")", "==", "1" ]
[ 416, 0 ]
[ 430, 25 ]
python
en
['en', 'da', 'en']
True
test_eventbus_thread_event_listener
(hass)
Test thread event listener.
Test thread event listener.
async def test_eventbus_thread_event_listener(hass): """Test thread event listener.""" thread_calls = [] def thread_listener(event): thread_calls.append(event) hass.bus.async_listen("test_thread", thread_listener) hass.bus.async_fire("test_thread") await hass.async_block_till_done() assert len(thread_calls) == 1
[ "async", "def", "test_eventbus_thread_event_listener", "(", "hass", ")", ":", "thread_calls", "=", "[", "]", "def", "thread_listener", "(", "event", ")", ":", "thread_calls", ".", "append", "(", "event", ")", "hass", ".", "bus", ".", "async_listen", "(", "\"test_thread\"", ",", "thread_listener", ")", "hass", ".", "bus", ".", "async_fire", "(", "\"test_thread\"", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "thread_calls", ")", "==", "1" ]
[ 433, 0 ]
[ 443, 33 ]
python
en
['en', 'de', 'en']
True
test_eventbus_callback_event_listener
(hass)
Test callback event listener.
Test callback event listener.
async def test_eventbus_callback_event_listener(hass): """Test callback event listener.""" callback_calls = [] @ha.callback def callback_listener(event): callback_calls.append(event) hass.bus.async_listen("test_callback", callback_listener) hass.bus.async_fire("test_callback") await hass.async_block_till_done() assert len(callback_calls) == 1
[ "async", "def", "test_eventbus_callback_event_listener", "(", "hass", ")", ":", "callback_calls", "=", "[", "]", "@", "ha", ".", "callback", "def", "callback_listener", "(", "event", ")", ":", "callback_calls", ".", "append", "(", "event", ")", "hass", ".", "bus", ".", "async_listen", "(", "\"test_callback\"", ",", "callback_listener", ")", "hass", ".", "bus", ".", "async_fire", "(", "\"test_callback\"", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "callback_calls", ")", "==", "1" ]
[ 446, 0 ]
[ 457, 35 ]
python
en
['fr', 'et', 'en']
False
test_eventbus_coroutine_event_listener
(hass)
Test coroutine event listener.
Test coroutine event listener.
async def test_eventbus_coroutine_event_listener(hass): """Test coroutine event listener.""" coroutine_calls = [] async def coroutine_listener(event): coroutine_calls.append(event) hass.bus.async_listen("test_coroutine", coroutine_listener) hass.bus.async_fire("test_coroutine") await hass.async_block_till_done() assert len(coroutine_calls) == 1
[ "async", "def", "test_eventbus_coroutine_event_listener", "(", "hass", ")", ":", "coroutine_calls", "=", "[", "]", "async", "def", "coroutine_listener", "(", "event", ")", ":", "coroutine_calls", ".", "append", "(", "event", ")", "hass", ".", "bus", ".", "async_listen", "(", "\"test_coroutine\"", ",", "coroutine_listener", ")", "hass", ".", "bus", ".", "async_fire", "(", "\"test_coroutine\"", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "coroutine_calls", ")", "==", "1" ]
[ 460, 0 ]
[ 470, 36 ]
python
de
['fr', 'de', 'pt']
False
test_state_init
()
Test state.init.
Test state.init.
def test_state_init(): """Test state.init.""" with pytest.raises(InvalidEntityFormatError): ha.State("invalid_entity_format", "test_state") with pytest.raises(InvalidStateError): ha.State("domain.long_state", "t" * 256)
[ "def", "test_state_init", "(", ")", ":", "with", "pytest", ".", "raises", "(", "InvalidEntityFormatError", ")", ":", "ha", ".", "State", "(", "\"invalid_entity_format\"", ",", "\"test_state\"", ")", "with", "pytest", ".", "raises", "(", "InvalidStateError", ")", ":", "ha", ".", "State", "(", "\"domain.long_state\"", ",", "\"t\"", "*", "256", ")" ]
[ 473, 0 ]
[ 479, 48 ]
python
en
['en', 'en', 'en']
False
test_state_domain
()
Test domain.
Test domain.
def test_state_domain(): """Test domain.""" state = ha.State("some_domain.hello", "world") assert state.domain == "some_domain"
[ "def", "test_state_domain", "(", ")", ":", "state", "=", "ha", ".", "State", "(", "\"some_domain.hello\"", ",", "\"world\"", ")", "assert", "state", ".", "domain", "==", "\"some_domain\"" ]
[ 482, 0 ]
[ 485, 40 ]
python
fr
['fr', 'fr', 'en']
False
test_state_object_id
()
Test object ID.
Test object ID.
def test_state_object_id(): """Test object ID.""" state = ha.State("domain.hello", "world") assert state.object_id == "hello"
[ "def", "test_state_object_id", "(", ")", ":", "state", "=", "ha", ".", "State", "(", "\"domain.hello\"", ",", "\"world\"", ")", "assert", "state", ".", "object_id", "==", "\"hello\"" ]
[ 488, 0 ]
[ 491, 37 ]
python
en
['en', 'mt', 'en']
True
test_state_name_if_no_friendly_name_attr
()
Test if there is no friendly name.
Test if there is no friendly name.
def test_state_name_if_no_friendly_name_attr(): """Test if there is no friendly name.""" state = ha.State("domain.hello_world", "world") assert state.name == "hello world"
[ "def", "test_state_name_if_no_friendly_name_attr", "(", ")", ":", "state", "=", "ha", ".", "State", "(", "\"domain.hello_world\"", ",", "\"world\"", ")", "assert", "state", ".", "name", "==", "\"hello world\"" ]
[ 494, 0 ]
[ 497, 38 ]
python
en
['en', 'en', 'en']
True
test_state_name_if_friendly_name_attr
()
Test if there is a friendly name.
Test if there is a friendly name.
def test_state_name_if_friendly_name_attr(): """Test if there is a friendly name.""" name = "Some Unique Name" state = ha.State("domain.hello_world", "world", {ATTR_FRIENDLY_NAME: name}) assert state.name == name
[ "def", "test_state_name_if_friendly_name_attr", "(", ")", ":", "name", "=", "\"Some Unique Name\"", "state", "=", "ha", ".", "State", "(", "\"domain.hello_world\"", ",", "\"world\"", ",", "{", "ATTR_FRIENDLY_NAME", ":", "name", "}", ")", "assert", "state", ".", "name", "==", "name" ]
[ 500, 0 ]
[ 504, 29 ]
python
en
['en', 'en', 'en']
True
test_state_dict_conversion
()
Test conversion of dict.
Test conversion of dict.
def test_state_dict_conversion(): """Test conversion of dict.""" state = ha.State("domain.hello", "world", {"some": "attr"}) assert state == ha.State.from_dict(state.as_dict())
[ "def", "test_state_dict_conversion", "(", ")", ":", "state", "=", "ha", ".", "State", "(", "\"domain.hello\"", ",", "\"world\"", ",", "{", "\"some\"", ":", "\"attr\"", "}", ")", "assert", "state", "==", "ha", ".", "State", ".", "from_dict", "(", "state", ".", "as_dict", "(", ")", ")" ]
[ 507, 0 ]
[ 510, 55 ]
python
en
['en', 'en', 'en']
True
test_state_dict_conversion_with_wrong_data
()
Test conversion with wrong data.
Test conversion with wrong data.
def test_state_dict_conversion_with_wrong_data(): """Test conversion with wrong data.""" assert ha.State.from_dict(None) is None assert ha.State.from_dict({"state": "yes"}) is None assert ha.State.from_dict({"entity_id": "yes"}) is None # Make sure invalid context data doesn't crash wrong_context = ha.State.from_dict( { "entity_id": "light.kitchen", "state": "on", "context": {"id": "123", "non-existing": "crash"}, } ) assert wrong_context is not None assert wrong_context.context.id == "123"
[ "def", "test_state_dict_conversion_with_wrong_data", "(", ")", ":", "assert", "ha", ".", "State", ".", "from_dict", "(", "None", ")", "is", "None", "assert", "ha", ".", "State", ".", "from_dict", "(", "{", "\"state\"", ":", "\"yes\"", "}", ")", "is", "None", "assert", "ha", ".", "State", ".", "from_dict", "(", "{", "\"entity_id\"", ":", "\"yes\"", "}", ")", "is", "None", "# Make sure invalid context data doesn't crash", "wrong_context", "=", "ha", ".", "State", ".", "from_dict", "(", "{", "\"entity_id\"", ":", "\"light.kitchen\"", ",", "\"state\"", ":", "\"on\"", ",", "\"context\"", ":", "{", "\"id\"", ":", "\"123\"", ",", "\"non-existing\"", ":", "\"crash\"", "}", ",", "}", ")", "assert", "wrong_context", "is", "not", "None", "assert", "wrong_context", ".", "context", ".", "id", "==", "\"123\"" ]
[ 513, 0 ]
[ 527, 44 ]
python
en
['en', 'en', 'en']
True
test_state_repr
()
Test state.repr.
Test state.repr.
def test_state_repr(): """Test state.repr.""" assert ( str(ha.State("happy.happy", "on", last_changed=datetime(1984, 12, 8, 12, 0, 0))) == "<state happy.happy=on @ 1984-12-08T12:00:00+00:00>" ) assert ( str( ha.State( "happy.happy", "on", {"brightness": 144}, datetime(1984, 12, 8, 12, 0, 0), ) ) == "<state happy.happy=on; brightness=144 @ " "1984-12-08T12:00:00+00:00>" )
[ "def", "test_state_repr", "(", ")", ":", "assert", "(", "str", "(", "ha", ".", "State", "(", "\"happy.happy\"", ",", "\"on\"", ",", "last_changed", "=", "datetime", "(", "1984", ",", "12", ",", "8", ",", "12", ",", "0", ",", "0", ")", ")", ")", "==", "\"<state happy.happy=on @ 1984-12-08T12:00:00+00:00>\"", ")", "assert", "(", "str", "(", "ha", ".", "State", "(", "\"happy.happy\"", ",", "\"on\"", ",", "{", "\"brightness\"", ":", "144", "}", ",", "datetime", "(", "1984", ",", "12", ",", "8", ",", "12", ",", "0", ",", "0", ")", ",", ")", ")", "==", "\"<state happy.happy=on; brightness=144 @ \"", "\"1984-12-08T12:00:00+00:00>\"", ")" ]
[ 530, 0 ]
[ 548, 5 ]
python
en
['en', 'en', 'en']
False
test_statemachine_is_state
(hass)
Test is_state method.
Test is_state method.
async def test_statemachine_is_state(hass): """Test is_state method.""" hass.states.async_set("light.bowl", "on", {}) assert hass.states.is_state("light.Bowl", "on") assert not hass.states.is_state("light.Bowl", "off") assert not hass.states.is_state("light.Non_existing", "on")
[ "async", "def", "test_statemachine_is_state", "(", "hass", ")", ":", "hass", ".", "states", ".", "async_set", "(", "\"light.bowl\"", ",", "\"on\"", ",", "{", "}", ")", "assert", "hass", ".", "states", ".", "is_state", "(", "\"light.Bowl\"", ",", "\"on\"", ")", "assert", "not", "hass", ".", "states", ".", "is_state", "(", "\"light.Bowl\"", ",", "\"off\"", ")", "assert", "not", "hass", ".", "states", ".", "is_state", "(", "\"light.Non_existing\"", ",", "\"on\"", ")" ]
[ 551, 0 ]
[ 556, 63 ]
python
en
['en', 'en', 'en']
True
test_statemachine_entity_ids
(hass)
Test get_entity_ids method.
Test get_entity_ids method.
async def test_statemachine_entity_ids(hass): """Test get_entity_ids method.""" hass.states.async_set("light.bowl", "on", {}) hass.states.async_set("SWITCH.AC", "off", {}) ent_ids = hass.states.async_entity_ids() assert len(ent_ids) == 2 assert "light.bowl" in ent_ids assert "switch.ac" in ent_ids ent_ids = hass.states.async_entity_ids("light") assert len(ent_ids) == 1 assert "light.bowl" in ent_ids states = sorted(state.entity_id for state in hass.states.async_all()) assert states == ["light.bowl", "switch.ac"]
[ "async", "def", "test_statemachine_entity_ids", "(", "hass", ")", ":", "hass", ".", "states", ".", "async_set", "(", "\"light.bowl\"", ",", "\"on\"", ",", "{", "}", ")", "hass", ".", "states", ".", "async_set", "(", "\"SWITCH.AC\"", ",", "\"off\"", ",", "{", "}", ")", "ent_ids", "=", "hass", ".", "states", ".", "async_entity_ids", "(", ")", "assert", "len", "(", "ent_ids", ")", "==", "2", "assert", "\"light.bowl\"", "in", "ent_ids", "assert", "\"switch.ac\"", "in", "ent_ids", "ent_ids", "=", "hass", ".", "states", ".", "async_entity_ids", "(", "\"light\"", ")", "assert", "len", "(", "ent_ids", ")", "==", "1", "assert", "\"light.bowl\"", "in", "ent_ids", "states", "=", "sorted", "(", "state", ".", "entity_id", "for", "state", "in", "hass", ".", "states", ".", "async_all", "(", ")", ")", "assert", "states", "==", "[", "\"light.bowl\"", ",", "\"switch.ac\"", "]" ]
[ 559, 0 ]
[ 573, 48 ]
python
da
['nl', 'da', 'en']
False
test_statemachine_remove
(hass)
Test remove method.
Test remove method.
async def test_statemachine_remove(hass): """Test remove method.""" hass.states.async_set("light.bowl", "on", {}) events = async_capture_events(hass, EVENT_STATE_CHANGED) assert "light.bowl" in hass.states.async_entity_ids() assert hass.states.async_remove("light.bowl") await hass.async_block_till_done() assert "light.bowl" not in hass.states.async_entity_ids() assert len(events) == 1 assert events[0].data.get("entity_id") == "light.bowl" assert events[0].data.get("old_state") is not None assert events[0].data["old_state"].entity_id == "light.bowl" assert events[0].data.get("new_state") is None # If it does not exist, we should get False assert not hass.states.async_remove("light.Bowl") await hass.async_block_till_done() assert len(events) == 1
[ "async", "def", "test_statemachine_remove", "(", "hass", ")", ":", "hass", ".", "states", ".", "async_set", "(", "\"light.bowl\"", ",", "\"on\"", ",", "{", "}", ")", "events", "=", "async_capture_events", "(", "hass", ",", "EVENT_STATE_CHANGED", ")", "assert", "\"light.bowl\"", "in", "hass", ".", "states", ".", "async_entity_ids", "(", ")", "assert", "hass", ".", "states", ".", "async_remove", "(", "\"light.bowl\"", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "\"light.bowl\"", "not", "in", "hass", ".", "states", ".", "async_entity_ids", "(", ")", "assert", "len", "(", "events", ")", "==", "1", "assert", "events", "[", "0", "]", ".", "data", ".", "get", "(", "\"entity_id\"", ")", "==", "\"light.bowl\"", "assert", "events", "[", "0", "]", ".", "data", ".", "get", "(", "\"old_state\"", ")", "is", "not", "None", "assert", "events", "[", "0", "]", ".", "data", "[", "\"old_state\"", "]", ".", "entity_id", "==", "\"light.bowl\"", "assert", "events", "[", "0", "]", ".", "data", ".", "get", "(", "\"new_state\"", ")", "is", "None", "# If it does not exist, we should get False", "assert", "not", "hass", ".", "states", ".", "async_remove", "(", "\"light.Bowl\"", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "events", ")", "==", "1" ]
[ 576, 0 ]
[ 595, 27 ]
python
en
['en', 'sr', 'en']
True
test_statemachine_case_insensitivty
(hass)
Test insensitivty.
Test insensitivty.
async def test_statemachine_case_insensitivty(hass): """Test insensitivty.""" events = async_capture_events(hass, EVENT_STATE_CHANGED) hass.states.async_set("light.BOWL", "off") await hass.async_block_till_done() assert hass.states.is_state("light.bowl", "off") assert len(events) == 1
[ "async", "def", "test_statemachine_case_insensitivty", "(", "hass", ")", ":", "events", "=", "async_capture_events", "(", "hass", ",", "EVENT_STATE_CHANGED", ")", "hass", ".", "states", ".", "async_set", "(", "\"light.BOWL\"", ",", "\"off\"", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "hass", ".", "states", ".", "is_state", "(", "\"light.bowl\"", ",", "\"off\"", ")", "assert", "len", "(", "events", ")", "==", "1" ]
[ 598, 0 ]
[ 606, 27 ]
python
en
['en', 'de', 'en']
False
test_statemachine_last_changed_not_updated_on_same_state
(hass)
Test to not update the existing, same state.
Test to not update the existing, same state.
async def test_statemachine_last_changed_not_updated_on_same_state(hass): """Test to not update the existing, same state.""" hass.states.async_set("light.bowl", "on", {}) state = hass.states.get("light.Bowl") future = dt_util.utcnow() + timedelta(hours=10) with patch("homeassistant.util.dt.utcnow", return_value=future): hass.states.async_set("light.Bowl", "on", {"attr": "triggers_change"}) await hass.async_block_till_done() state2 = hass.states.get("light.Bowl") assert state2 is not None assert state.last_changed == state2.last_changed
[ "async", "def", "test_statemachine_last_changed_not_updated_on_same_state", "(", "hass", ")", ":", "hass", ".", "states", ".", "async_set", "(", "\"light.bowl\"", ",", "\"on\"", ",", "{", "}", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "\"light.Bowl\"", ")", "future", "=", "dt_util", ".", "utcnow", "(", ")", "+", "timedelta", "(", "hours", "=", "10", ")", "with", "patch", "(", "\"homeassistant.util.dt.utcnow\"", ",", "return_value", "=", "future", ")", ":", "hass", ".", "states", ".", "async_set", "(", "\"light.Bowl\"", ",", "\"on\"", ",", "{", "\"attr\"", ":", "\"triggers_change\"", "}", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "state2", "=", "hass", ".", "states", ".", "get", "(", "\"light.Bowl\"", ")", "assert", "state2", "is", "not", "None", "assert", "state", ".", "last_changed", "==", "state2", ".", "last_changed" ]
[ 609, 0 ]
[ 622, 52 ]
python
en
['en', 'en', 'en']
True