Search is not available for this dataset
identifier
stringlengths 1
155
| parameters
stringlengths 2
6.09k
| docstring
stringlengths 11
63.4k
| docstring_summary
stringlengths 0
63.4k
| function
stringlengths 29
99.8k
| function_tokens
sequence | start_point
sequence | end_point
sequence | language
stringclasses 1
value | docstring_language
stringlengths 2
7
| docstring_language_predictions
stringlengths 18
23
| is_langid_reliable
stringclasses 2
values |
---|---|---|---|---|---|---|---|---|---|---|---|
_id | (value: str) | Coerce id by removing '-'. | Coerce id by removing '-'. | def _id(value: str) -> str:
"""Coerce id by removing '-'."""
return value.replace("-", "") | [
"def",
"_id",
"(",
"value",
":",
"str",
")",
"->",
"str",
":",
"return",
"value",
".",
"replace",
"(",
"\"-\"",
",",
"\"\"",
")"
] | [
31,
0
] | [
33,
33
] | python | en | ['en', 'en', 'en'] | True |
_validate_test_mode | (obj: Dict) | Validate that id is provided outside of test mode. | Validate that id is provided outside of test mode. | def _validate_test_mode(obj: Dict) -> Dict:
"""Validate that id is provided outside of test mode."""
if ATTR_ID not in obj and obj[ATTR_TRIGGER] != "test":
raise vol.Invalid("Location id not specified")
return obj | [
"def",
"_validate_test_mode",
"(",
"obj",
":",
"Dict",
")",
"->",
"Dict",
":",
"if",
"ATTR_ID",
"not",
"in",
"obj",
"and",
"obj",
"[",
"ATTR_TRIGGER",
"]",
"!=",
"\"test\"",
":",
"raise",
"vol",
".",
"Invalid",
"(",
"\"Location id not specified\"",
")",
"return",
"obj"
] | [
36,
0
] | [
40,
14
] | python | en | ['en', 'en', 'en'] | True |
async_setup | (hass, hass_config) | Set up the Locative component. | Set up the Locative component. | async def async_setup(hass, hass_config):
"""Set up the Locative component."""
hass.data[DOMAIN] = {"devices": set(), "unsub_device_tracker": {}}
return True | [
"async",
"def",
"async_setup",
"(",
"hass",
",",
"hass_config",
")",
":",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"=",
"{",
"\"devices\"",
":",
"set",
"(",
")",
",",
"\"unsub_device_tracker\"",
":",
"{",
"}",
"}",
"return",
"True"
] | [
58,
0
] | [
61,
15
] | python | en | ['en', 'en', 'en'] | True |
handle_webhook | (hass, webhook_id, request) | Handle incoming webhook from Locative. | Handle incoming webhook from Locative. | async def handle_webhook(hass, webhook_id, request):
"""Handle incoming webhook from Locative."""
try:
data = WEBHOOK_SCHEMA(dict(await request.post()))
except vol.MultipleInvalid as error:
return web.Response(text=error.error_message, status=HTTP_UNPROCESSABLE_ENTITY)
device = data[ATTR_DEVICE_ID]
location_name = data.get(ATTR_ID, data[ATTR_TRIGGER]).lower()
direction = data[ATTR_TRIGGER]
gps_location = (data[ATTR_LATITUDE], data[ATTR_LONGITUDE])
if direction == "enter":
async_dispatcher_send(hass, TRACKER_UPDATE, device, gps_location, location_name)
return web.Response(text=f"Setting location to {location_name}", status=HTTP_OK)
if direction == "exit":
current_state = hass.states.get(f"{DEVICE_TRACKER}.{device}")
if current_state is None or current_state.state == location_name:
location_name = STATE_NOT_HOME
async_dispatcher_send(
hass, TRACKER_UPDATE, device, gps_location, location_name
)
return web.Response(text="Setting location to not home", status=HTTP_OK)
# Ignore the message if it is telling us to exit a zone that we
# aren't currently in. This occurs when a zone is entered
# before the previous zone was exited. The enter message will
# be sent first, then the exit message will be sent second.
return web.Response(
text=f"Ignoring exit from {location_name} (already in {current_state})",
status=HTTP_OK,
)
if direction == "test":
# In the app, a test message can be sent. Just return something to
# the user to let them know that it works.
return web.Response(text="Received test message.", status=HTTP_OK)
_LOGGER.error("Received unidentified message from Locative: %s", direction)
return web.Response(
text=f"Received unidentified message: {direction}",
status=HTTP_UNPROCESSABLE_ENTITY,
) | [
"async",
"def",
"handle_webhook",
"(",
"hass",
",",
"webhook_id",
",",
"request",
")",
":",
"try",
":",
"data",
"=",
"WEBHOOK_SCHEMA",
"(",
"dict",
"(",
"await",
"request",
".",
"post",
"(",
")",
")",
")",
"except",
"vol",
".",
"MultipleInvalid",
"as",
"error",
":",
"return",
"web",
".",
"Response",
"(",
"text",
"=",
"error",
".",
"error_message",
",",
"status",
"=",
"HTTP_UNPROCESSABLE_ENTITY",
")",
"device",
"=",
"data",
"[",
"ATTR_DEVICE_ID",
"]",
"location_name",
"=",
"data",
".",
"get",
"(",
"ATTR_ID",
",",
"data",
"[",
"ATTR_TRIGGER",
"]",
")",
".",
"lower",
"(",
")",
"direction",
"=",
"data",
"[",
"ATTR_TRIGGER",
"]",
"gps_location",
"=",
"(",
"data",
"[",
"ATTR_LATITUDE",
"]",
",",
"data",
"[",
"ATTR_LONGITUDE",
"]",
")",
"if",
"direction",
"==",
"\"enter\"",
":",
"async_dispatcher_send",
"(",
"hass",
",",
"TRACKER_UPDATE",
",",
"device",
",",
"gps_location",
",",
"location_name",
")",
"return",
"web",
".",
"Response",
"(",
"text",
"=",
"f\"Setting location to {location_name}\"",
",",
"status",
"=",
"HTTP_OK",
")",
"if",
"direction",
"==",
"\"exit\"",
":",
"current_state",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"f\"{DEVICE_TRACKER}.{device}\"",
")",
"if",
"current_state",
"is",
"None",
"or",
"current_state",
".",
"state",
"==",
"location_name",
":",
"location_name",
"=",
"STATE_NOT_HOME",
"async_dispatcher_send",
"(",
"hass",
",",
"TRACKER_UPDATE",
",",
"device",
",",
"gps_location",
",",
"location_name",
")",
"return",
"web",
".",
"Response",
"(",
"text",
"=",
"\"Setting location to not home\"",
",",
"status",
"=",
"HTTP_OK",
")",
"# Ignore the message if it is telling us to exit a zone that we",
"# aren't currently in. This occurs when a zone is entered",
"# before the previous zone was exited. The enter message will",
"# be sent first, then the exit message will be sent second.",
"return",
"web",
".",
"Response",
"(",
"text",
"=",
"f\"Ignoring exit from {location_name} (already in {current_state})\"",
",",
"status",
"=",
"HTTP_OK",
",",
")",
"if",
"direction",
"==",
"\"test\"",
":",
"# In the app, a test message can be sent. Just return something to",
"# the user to let them know that it works.",
"return",
"web",
".",
"Response",
"(",
"text",
"=",
"\"Received test message.\"",
",",
"status",
"=",
"HTTP_OK",
")",
"_LOGGER",
".",
"error",
"(",
"\"Received unidentified message from Locative: %s\"",
",",
"direction",
")",
"return",
"web",
".",
"Response",
"(",
"text",
"=",
"f\"Received unidentified message: {direction}\"",
",",
"status",
"=",
"HTTP_UNPROCESSABLE_ENTITY",
",",
")"
] | [
64,
0
] | [
108,
5
] | python | en | ['en', 'en', 'en'] | True |
async_setup_entry | (hass, entry) | Configure based on config entry. | Configure based on config entry. | async def async_setup_entry(hass, entry):
"""Configure based on config entry."""
hass.components.webhook.async_register(
DOMAIN, "Locative", entry.data[CONF_WEBHOOK_ID], handle_webhook
)
hass.async_create_task(
hass.config_entries.async_forward_entry_setup(entry, DEVICE_TRACKER)
)
return True | [
"async",
"def",
"async_setup_entry",
"(",
"hass",
",",
"entry",
")",
":",
"hass",
".",
"components",
".",
"webhook",
".",
"async_register",
"(",
"DOMAIN",
",",
"\"Locative\"",
",",
"entry",
".",
"data",
"[",
"CONF_WEBHOOK_ID",
"]",
",",
"handle_webhook",
")",
"hass",
".",
"async_create_task",
"(",
"hass",
".",
"config_entries",
".",
"async_forward_entry_setup",
"(",
"entry",
",",
"DEVICE_TRACKER",
")",
")",
"return",
"True"
] | [
111,
0
] | [
120,
15
] | python | en | ['en', 'en', 'en'] | True |
async_unload_entry | (hass, entry) | Unload a config entry. | Unload a config entry. | async def async_unload_entry(hass, entry):
"""Unload a config entry."""
hass.components.webhook.async_unregister(entry.data[CONF_WEBHOOK_ID])
hass.data[DOMAIN]["unsub_device_tracker"].pop(entry.entry_id)()
return await hass.config_entries.async_forward_entry_unload(entry, DEVICE_TRACKER) | [
"async",
"def",
"async_unload_entry",
"(",
"hass",
",",
"entry",
")",
":",
"hass",
".",
"components",
".",
"webhook",
".",
"async_unregister",
"(",
"entry",
".",
"data",
"[",
"CONF_WEBHOOK_ID",
"]",
")",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"\"unsub_device_tracker\"",
"]",
".",
"pop",
"(",
"entry",
".",
"entry_id",
")",
"(",
")",
"return",
"await",
"hass",
".",
"config_entries",
".",
"async_forward_entry_unload",
"(",
"entry",
",",
"DEVICE_TRACKER",
")"
] | [
123,
0
] | [
127,
86
] | python | en | ['en', 'es', 'en'] | True |
HueEvent.__init__ | (self, sensor, name, bridge, primary_sensor=None) | Register callback that will be used for signals. | Register callback that will be used for signals. | def __init__(self, sensor, name, bridge, primary_sensor=None):
"""Register callback that will be used for signals."""
super().__init__(sensor, name, bridge, primary_sensor)
self.device_registry_id = None
self.event_id = slugify(self.sensor.name)
# Use the aiohue sensor 'state' dict to detect new remote presses
self._last_state = dict(self.sensor.state)
# Register callback in coordinator and add job to remove it on bridge reset.
self.bridge.reset_jobs.append(
self.bridge.sensor_manager.coordinator.async_add_listener(
self.async_update_callback
)
)
_LOGGER.debug("Hue event created: %s", self.event_id) | [
"def",
"__init__",
"(",
"self",
",",
"sensor",
",",
"name",
",",
"bridge",
",",
"primary_sensor",
"=",
"None",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"sensor",
",",
"name",
",",
"bridge",
",",
"primary_sensor",
")",
"self",
".",
"device_registry_id",
"=",
"None",
"self",
".",
"event_id",
"=",
"slugify",
"(",
"self",
".",
"sensor",
".",
"name",
")",
"# Use the aiohue sensor 'state' dict to detect new remote presses",
"self",
".",
"_last_state",
"=",
"dict",
"(",
"self",
".",
"sensor",
".",
"state",
")",
"# Register callback in coordinator and add job to remove it on bridge reset.",
"self",
".",
"bridge",
".",
"reset_jobs",
".",
"append",
"(",
"self",
".",
"bridge",
".",
"sensor_manager",
".",
"coordinator",
".",
"async_add_listener",
"(",
"self",
".",
"async_update_callback",
")",
")",
"_LOGGER",
".",
"debug",
"(",
"\"Hue event created: %s\"",
",",
"self",
".",
"event_id",
")"
] | [
26,
4
] | [
41,
61
] | python | en | ['en', 'en', 'en'] | True |
HueEvent.async_update_callback | (self) | Fire the event if reason is that state is updated. | Fire the event if reason is that state is updated. | def async_update_callback(self):
"""Fire the event if reason is that state is updated."""
if self.sensor.state == self._last_state:
return
# Extract the press code as state
if hasattr(self.sensor, "rotaryevent"):
state = self.sensor.rotaryevent
else:
state = self.sensor.buttonevent
self._last_state = dict(self.sensor.state)
# Fire event
data = {
CONF_ID: self.event_id,
CONF_UNIQUE_ID: self.unique_id,
CONF_EVENT: state,
CONF_LAST_UPDATED: self.sensor.lastupdated,
}
self.bridge.hass.bus.async_fire(CONF_HUE_EVENT, data) | [
"def",
"async_update_callback",
"(",
"self",
")",
":",
"if",
"self",
".",
"sensor",
".",
"state",
"==",
"self",
".",
"_last_state",
":",
"return",
"# Extract the press code as state",
"if",
"hasattr",
"(",
"self",
".",
"sensor",
",",
"\"rotaryevent\"",
")",
":",
"state",
"=",
"self",
".",
"sensor",
".",
"rotaryevent",
"else",
":",
"state",
"=",
"self",
".",
"sensor",
".",
"buttonevent",
"self",
".",
"_last_state",
"=",
"dict",
"(",
"self",
".",
"sensor",
".",
"state",
")",
"# Fire event",
"data",
"=",
"{",
"CONF_ID",
":",
"self",
".",
"event_id",
",",
"CONF_UNIQUE_ID",
":",
"self",
".",
"unique_id",
",",
"CONF_EVENT",
":",
"state",
",",
"CONF_LAST_UPDATED",
":",
"self",
".",
"sensor",
".",
"lastupdated",
",",
"}",
"self",
".",
"bridge",
".",
"hass",
".",
"bus",
".",
"async_fire",
"(",
"CONF_HUE_EVENT",
",",
"data",
")"
] | [
44,
4
] | [
64,
61
] | python | en | ['en', 'en', 'en'] | True |
HueEvent.async_update_device_registry | (self) | Update device registry. | Update device registry. | async def async_update_device_registry(self):
"""Update device registry."""
device_registry = (
await self.bridge.hass.helpers.device_registry.async_get_registry()
)
entry = device_registry.async_get_or_create(
config_entry_id=self.bridge.config_entry.entry_id, **self.device_info
)
self.device_registry_id = entry.id
_LOGGER.debug(
"Event registry with entry_id: %s and device_id: %s",
self.device_registry_id,
self.device_id,
) | [
"async",
"def",
"async_update_device_registry",
"(",
"self",
")",
":",
"device_registry",
"=",
"(",
"await",
"self",
".",
"bridge",
".",
"hass",
".",
"helpers",
".",
"device_registry",
".",
"async_get_registry",
"(",
")",
")",
"entry",
"=",
"device_registry",
".",
"async_get_or_create",
"(",
"config_entry_id",
"=",
"self",
".",
"bridge",
".",
"config_entry",
".",
"entry_id",
",",
"*",
"*",
"self",
".",
"device_info",
")",
"self",
".",
"device_registry_id",
"=",
"entry",
".",
"id",
"_LOGGER",
".",
"debug",
"(",
"\"Event registry with entry_id: %s and device_id: %s\"",
",",
"self",
".",
"device_registry_id",
",",
"self",
".",
"device_id",
",",
")"
] | [
66,
4
] | [
80,
9
] | python | en | ['fr', 'fy', 'en'] | False |
async_setup_entry | (
hass: HomeAssistantType,
entry: ConfigEntry,
async_add_entities: Callable[[list], None],
) | Set up the ISY994 switch platform. | Set up the ISY994 switch platform. | async def async_setup_entry(
hass: HomeAssistantType,
entry: ConfigEntry,
async_add_entities: Callable[[list], None],
) -> bool:
"""Set up the ISY994 switch platform."""
hass_isy_data = hass.data[ISY994_DOMAIN][entry.entry_id]
devices = []
for node in hass_isy_data[ISY994_NODES][SWITCH]:
devices.append(ISYSwitchEntity(node))
for name, status, actions in hass_isy_data[ISY994_PROGRAMS][SWITCH]:
devices.append(ISYSwitchProgramEntity(name, status, actions))
await migrate_old_unique_ids(hass, SWITCH, devices)
async_add_entities(devices) | [
"async",
"def",
"async_setup_entry",
"(",
"hass",
":",
"HomeAssistantType",
",",
"entry",
":",
"ConfigEntry",
",",
"async_add_entities",
":",
"Callable",
"[",
"[",
"list",
"]",
",",
"None",
"]",
",",
")",
"->",
"bool",
":",
"hass_isy_data",
"=",
"hass",
".",
"data",
"[",
"ISY994_DOMAIN",
"]",
"[",
"entry",
".",
"entry_id",
"]",
"devices",
"=",
"[",
"]",
"for",
"node",
"in",
"hass_isy_data",
"[",
"ISY994_NODES",
"]",
"[",
"SWITCH",
"]",
":",
"devices",
".",
"append",
"(",
"ISYSwitchEntity",
"(",
"node",
")",
")",
"for",
"name",
",",
"status",
",",
"actions",
"in",
"hass_isy_data",
"[",
"ISY994_PROGRAMS",
"]",
"[",
"SWITCH",
"]",
":",
"devices",
".",
"append",
"(",
"ISYSwitchProgramEntity",
"(",
"name",
",",
"status",
",",
"actions",
")",
")",
"await",
"migrate_old_unique_ids",
"(",
"hass",
",",
"SWITCH",
",",
"devices",
")",
"async_add_entities",
"(",
"devices",
")"
] | [
14,
0
] | [
29,
31
] | python | en | ['en', 'en', 'en'] | True |
ISYSwitchEntity.is_on | (self) | Get whether the ISY994 device is in the on state. | Get whether the ISY994 device is in the on state. | def is_on(self) -> bool:
"""Get whether the ISY994 device is in the on state."""
if self._node.status == ISY_VALUE_UNKNOWN:
return None
return bool(self._node.status) | [
"def",
"is_on",
"(",
"self",
")",
"->",
"bool",
":",
"if",
"self",
".",
"_node",
".",
"status",
"==",
"ISY_VALUE_UNKNOWN",
":",
"return",
"None",
"return",
"bool",
"(",
"self",
".",
"_node",
".",
"status",
")"
] | [
36,
4
] | [
40,
38
] | python | en | ['en', 'en', 'en'] | True |
ISYSwitchEntity.turn_off | (self, **kwargs) | Send the turn off command to the ISY994 switch. | Send the turn off command to the ISY994 switch. | def turn_off(self, **kwargs) -> None:
"""Send the turn off command to the ISY994 switch."""
if not self._node.turn_off():
_LOGGER.debug("Unable to turn off switch") | [
"def",
"turn_off",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
"->",
"None",
":",
"if",
"not",
"self",
".",
"_node",
".",
"turn_off",
"(",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Unable to turn off switch\"",
")"
] | [
42,
4
] | [
45,
54
] | python | en | ['en', 'en', 'en'] | True |
ISYSwitchEntity.turn_on | (self, **kwargs) | Send the turn on command to the ISY994 switch. | Send the turn on command to the ISY994 switch. | def turn_on(self, **kwargs) -> None:
"""Send the turn on command to the ISY994 switch."""
if not self._node.turn_on():
_LOGGER.debug("Unable to turn on switch") | [
"def",
"turn_on",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
"->",
"None",
":",
"if",
"not",
"self",
".",
"_node",
".",
"turn_on",
"(",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Unable to turn on switch\"",
")"
] | [
47,
4
] | [
50,
53
] | python | en | ['en', 'en', 'en'] | True |
ISYSwitchEntity.icon | (self) | Get the icon for groups. | Get the icon for groups. | def icon(self) -> str:
"""Get the icon for groups."""
if hasattr(self._node, "protocol") and self._node.protocol == PROTO_GROUP:
return "mdi:google-circles-communities" # Matches isy scene icon
return super().icon | [
"def",
"icon",
"(",
"self",
")",
"->",
"str",
":",
"if",
"hasattr",
"(",
"self",
".",
"_node",
",",
"\"protocol\"",
")",
"and",
"self",
".",
"_node",
".",
"protocol",
"==",
"PROTO_GROUP",
":",
"return",
"\"mdi:google-circles-communities\"",
"# Matches isy scene icon",
"return",
"super",
"(",
")",
".",
"icon"
] | [
53,
4
] | [
57,
27
] | python | en | ['en', 'en', 'en'] | True |
ISYSwitchProgramEntity.is_on | (self) | Get whether the ISY994 switch program is on. | Get whether the ISY994 switch program is on. | def is_on(self) -> bool:
"""Get whether the ISY994 switch program is on."""
return bool(self._node.status) | [
"def",
"is_on",
"(",
"self",
")",
"->",
"bool",
":",
"return",
"bool",
"(",
"self",
".",
"_node",
".",
"status",
")"
] | [
64,
4
] | [
66,
38
] | python | en | ['en', 'en', 'en'] | True |
ISYSwitchProgramEntity.turn_on | (self, **kwargs) | Send the turn on command to the ISY994 switch program. | Send the turn on command to the ISY994 switch program. | def turn_on(self, **kwargs) -> None:
"""Send the turn on command to the ISY994 switch program."""
if not self._actions.run_then():
_LOGGER.error("Unable to turn on switch") | [
"def",
"turn_on",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
"->",
"None",
":",
"if",
"not",
"self",
".",
"_actions",
".",
"run_then",
"(",
")",
":",
"_LOGGER",
".",
"error",
"(",
"\"Unable to turn on switch\"",
")"
] | [
68,
4
] | [
71,
53
] | python | en | ['en', 'en', 'en'] | True |
ISYSwitchProgramEntity.turn_off | (self, **kwargs) | Send the turn off command to the ISY994 switch program. | Send the turn off command to the ISY994 switch program. | def turn_off(self, **kwargs) -> None:
"""Send the turn off command to the ISY994 switch program."""
if not self._actions.run_else():
_LOGGER.error("Unable to turn off switch") | [
"def",
"turn_off",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
"->",
"None",
":",
"if",
"not",
"self",
".",
"_actions",
".",
"run_else",
"(",
")",
":",
"_LOGGER",
".",
"error",
"(",
"\"Unable to turn off switch\"",
")"
] | [
73,
4
] | [
76,
54
] | python | en | ['en', 'en', 'en'] | True |
ISYSwitchProgramEntity.icon | (self) | Get the icon for programs. | Get the icon for programs. | def icon(self) -> str:
"""Get the icon for programs."""
return "mdi:script-text-outline" | [
"def",
"icon",
"(",
"self",
")",
"->",
"str",
":",
"return",
"\"mdi:script-text-outline\""
] | [
79,
4
] | [
81,
40
] | python | en | ['en', 'en', 'en'] | True |
init_integration | (
hass, forecast=False, unsupported_icon=False
) | Set up the AccuWeather integration in Home Assistant. | Set up the AccuWeather integration in Home Assistant. | async def init_integration(
hass, forecast=False, unsupported_icon=False
) -> MockConfigEntry:
"""Set up the AccuWeather integration in Home Assistant."""
options = {}
if forecast:
options["forecast"] = True
entry = MockConfigEntry(
domain=DOMAIN,
title="Home",
unique_id="0123456",
data={
"api_key": "32-character-string-1234567890qw",
"latitude": 55.55,
"longitude": 122.12,
"name": "Home",
},
options=options,
)
current = json.loads(load_fixture("accuweather/current_conditions_data.json"))
forecast = json.loads(load_fixture("accuweather/forecast_data.json"))
if unsupported_icon:
current["WeatherIcon"] = 999
with patch(
"homeassistant.components.accuweather.AccuWeather.async_get_current_conditions",
return_value=current,
), patch(
"homeassistant.components.accuweather.AccuWeather.async_get_forecast",
return_value=forecast,
):
entry.add_to_hass(hass)
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
return entry | [
"async",
"def",
"init_integration",
"(",
"hass",
",",
"forecast",
"=",
"False",
",",
"unsupported_icon",
"=",
"False",
")",
"->",
"MockConfigEntry",
":",
"options",
"=",
"{",
"}",
"if",
"forecast",
":",
"options",
"[",
"\"forecast\"",
"]",
"=",
"True",
"entry",
"=",
"MockConfigEntry",
"(",
"domain",
"=",
"DOMAIN",
",",
"title",
"=",
"\"Home\"",
",",
"unique_id",
"=",
"\"0123456\"",
",",
"data",
"=",
"{",
"\"api_key\"",
":",
"\"32-character-string-1234567890qw\"",
",",
"\"latitude\"",
":",
"55.55",
",",
"\"longitude\"",
":",
"122.12",
",",
"\"name\"",
":",
"\"Home\"",
",",
"}",
",",
"options",
"=",
"options",
",",
")",
"current",
"=",
"json",
".",
"loads",
"(",
"load_fixture",
"(",
"\"accuweather/current_conditions_data.json\"",
")",
")",
"forecast",
"=",
"json",
".",
"loads",
"(",
"load_fixture",
"(",
"\"accuweather/forecast_data.json\"",
")",
")",
"if",
"unsupported_icon",
":",
"current",
"[",
"\"WeatherIcon\"",
"]",
"=",
"999",
"with",
"patch",
"(",
"\"homeassistant.components.accuweather.AccuWeather.async_get_current_conditions\"",
",",
"return_value",
"=",
"current",
",",
")",
",",
"patch",
"(",
"\"homeassistant.components.accuweather.AccuWeather.async_get_forecast\"",
",",
"return_value",
"=",
"forecast",
",",
")",
":",
"entry",
".",
"add_to_hass",
"(",
"hass",
")",
"await",
"hass",
".",
"config_entries",
".",
"async_setup",
"(",
"entry",
".",
"entry_id",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"return",
"entry"
] | [
9,
0
] | [
47,
16
] | python | en | ['en', 'en', 'en'] | True |
setup_platform | (hass, config, add_entities, discovery_info=None) | Set up the Verisure lock platform. | Set up the Verisure lock platform. | def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Verisure lock platform."""
locks = []
if int(hub.config.get(CONF_LOCKS, 1)):
hub.update_overview()
locks.extend(
[
VerisureDoorlock(device_label)
for device_label in hub.get("$.doorLockStatusList[*].deviceLabel")
]
)
add_entities(locks) | [
"def",
"setup_platform",
"(",
"hass",
",",
"config",
",",
"add_entities",
",",
"discovery_info",
"=",
"None",
")",
":",
"locks",
"=",
"[",
"]",
"if",
"int",
"(",
"hub",
".",
"config",
".",
"get",
"(",
"CONF_LOCKS",
",",
"1",
")",
")",
":",
"hub",
".",
"update_overview",
"(",
")",
"locks",
".",
"extend",
"(",
"[",
"VerisureDoorlock",
"(",
"device_label",
")",
"for",
"device_label",
"in",
"hub",
".",
"get",
"(",
"\"$.doorLockStatusList[*].deviceLabel\"",
")",
"]",
")",
"add_entities",
"(",
"locks",
")"
] | [
12,
0
] | [
24,
23
] | python | en | ['en', 'lv', 'en'] | True |
VerisureDoorlock.__init__ | (self, device_label) | Initialize the Verisure lock. | Initialize the Verisure lock. | def __init__(self, device_label):
"""Initialize the Verisure lock."""
self._device_label = device_label
self._state = None
self._digits = hub.config.get(CONF_CODE_DIGITS)
self._changed_by = None
self._change_timestamp = 0
self._default_lock_code = hub.config.get(CONF_DEFAULT_LOCK_CODE) | [
"def",
"__init__",
"(",
"self",
",",
"device_label",
")",
":",
"self",
".",
"_device_label",
"=",
"device_label",
"self",
".",
"_state",
"=",
"None",
"self",
".",
"_digits",
"=",
"hub",
".",
"config",
".",
"get",
"(",
"CONF_CODE_DIGITS",
")",
"self",
".",
"_changed_by",
"=",
"None",
"self",
".",
"_change_timestamp",
"=",
"0",
"self",
".",
"_default_lock_code",
"=",
"hub",
".",
"config",
".",
"get",
"(",
"CONF_DEFAULT_LOCK_CODE",
")"
] | [
30,
4
] | [
37,
72
] | python | en | ['en', 'co', 'en'] | True |
VerisureDoorlock.name | (self) | Return the name of the lock. | Return the name of the lock. | def name(self):
"""Return the name of the lock."""
return hub.get_first(
"$.doorLockStatusList[?(@.deviceLabel=='%s')].area", self._device_label
) | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"hub",
".",
"get_first",
"(",
"\"$.doorLockStatusList[?(@.deviceLabel=='%s')].area\"",
",",
"self",
".",
"_device_label",
")"
] | [
40,
4
] | [
44,
9
] | python | en | ['en', 'en', 'en'] | True |
VerisureDoorlock.state | (self) | Return the state of the lock. | Return the state of the lock. | def state(self):
"""Return the state of the lock."""
return self._state | [
"def",
"state",
"(",
"self",
")",
":",
"return",
"self",
".",
"_state"
] | [
47,
4
] | [
49,
26
] | python | en | ['en', 'en', 'en'] | True |
VerisureDoorlock.available | (self) | Return True if entity is available. | Return True if entity is available. | def available(self):
"""Return True if entity is available."""
return (
hub.get_first(
"$.doorLockStatusList[?(@.deviceLabel=='%s')]", self._device_label
)
is not None
) | [
"def",
"available",
"(",
"self",
")",
":",
"return",
"(",
"hub",
".",
"get_first",
"(",
"\"$.doorLockStatusList[?(@.deviceLabel=='%s')]\"",
",",
"self",
".",
"_device_label",
")",
"is",
"not",
"None",
")"
] | [
52,
4
] | [
59,
9
] | python | en | ['en', 'en', 'en'] | True |
VerisureDoorlock.changed_by | (self) | Last change triggered by. | Last change triggered by. | def changed_by(self):
"""Last change triggered by."""
return self._changed_by | [
"def",
"changed_by",
"(",
"self",
")",
":",
"return",
"self",
".",
"_changed_by"
] | [
62,
4
] | [
64,
31
] | python | en | ['en', 'en', 'en'] | True |
VerisureDoorlock.code_format | (self) | Return the required six digit code. | Return the required six digit code. | def code_format(self):
"""Return the required six digit code."""
return "^\\d{%s}$" % self._digits | [
"def",
"code_format",
"(",
"self",
")",
":",
"return",
"\"^\\\\d{%s}$\"",
"%",
"self",
".",
"_digits"
] | [
67,
4
] | [
69,
41
] | python | en | ['en', 'en', 'en'] | True |
VerisureDoorlock.update | (self) | Update lock status. | Update lock status. | def update(self):
"""Update lock status."""
if monotonic() - self._change_timestamp < 10:
return
hub.update_overview()
status = hub.get_first(
"$.doorLockStatusList[?(@.deviceLabel=='%s')].lockedState",
self._device_label,
)
if status == "UNLOCKED":
self._state = STATE_UNLOCKED
elif status == "LOCKED":
self._state = STATE_LOCKED
elif status != "PENDING":
_LOGGER.error("Unknown lock state %s", status)
self._changed_by = hub.get_first(
"$.doorLockStatusList[?(@.deviceLabel=='%s')].userString",
self._device_label,
) | [
"def",
"update",
"(",
"self",
")",
":",
"if",
"monotonic",
"(",
")",
"-",
"self",
".",
"_change_timestamp",
"<",
"10",
":",
"return",
"hub",
".",
"update_overview",
"(",
")",
"status",
"=",
"hub",
".",
"get_first",
"(",
"\"$.doorLockStatusList[?(@.deviceLabel=='%s')].lockedState\"",
",",
"self",
".",
"_device_label",
",",
")",
"if",
"status",
"==",
"\"UNLOCKED\"",
":",
"self",
".",
"_state",
"=",
"STATE_UNLOCKED",
"elif",
"status",
"==",
"\"LOCKED\"",
":",
"self",
".",
"_state",
"=",
"STATE_LOCKED",
"elif",
"status",
"!=",
"\"PENDING\"",
":",
"_LOGGER",
".",
"error",
"(",
"\"Unknown lock state %s\"",
",",
"status",
")",
"self",
".",
"_changed_by",
"=",
"hub",
".",
"get_first",
"(",
"\"$.doorLockStatusList[?(@.deviceLabel=='%s')].userString\"",
",",
"self",
".",
"_device_label",
",",
")"
] | [
71,
4
] | [
89,
9
] | python | en | ['es', 'la', 'en'] | False |
VerisureDoorlock.is_locked | (self) | Return true if lock is locked. | Return true if lock is locked. | def is_locked(self):
"""Return true if lock is locked."""
return self._state == STATE_LOCKED | [
"def",
"is_locked",
"(",
"self",
")",
":",
"return",
"self",
".",
"_state",
"==",
"STATE_LOCKED"
] | [
92,
4
] | [
94,
42
] | python | en | ['en', 'mt', 'en'] | True |
VerisureDoorlock.unlock | (self, **kwargs) | Send unlock command. | Send unlock command. | def unlock(self, **kwargs):
"""Send unlock command."""
if self._state is None:
return
code = kwargs.get(ATTR_CODE, self._default_lock_code)
if code is None:
_LOGGER.error("Code required but none provided")
return
self.set_lock_state(code, STATE_UNLOCKED) | [
"def",
"unlock",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"_state",
"is",
"None",
":",
"return",
"code",
"=",
"kwargs",
".",
"get",
"(",
"ATTR_CODE",
",",
"self",
".",
"_default_lock_code",
")",
"if",
"code",
"is",
"None",
":",
"_LOGGER",
".",
"error",
"(",
"\"Code required but none provided\"",
")",
"return",
"self",
".",
"set_lock_state",
"(",
"code",
",",
"STATE_UNLOCKED",
")"
] | [
96,
4
] | [
106,
49
] | python | en | ['en', 'zh', 'en'] | True |
VerisureDoorlock.lock | (self, **kwargs) | Send lock command. | Send lock command. | def lock(self, **kwargs):
"""Send lock command."""
if self._state == STATE_LOCKED:
return
code = kwargs.get(ATTR_CODE, self._default_lock_code)
if code is None:
_LOGGER.error("Code required but none provided")
return
self.set_lock_state(code, STATE_LOCKED) | [
"def",
"lock",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"_state",
"==",
"STATE_LOCKED",
":",
"return",
"code",
"=",
"kwargs",
".",
"get",
"(",
"ATTR_CODE",
",",
"self",
".",
"_default_lock_code",
")",
"if",
"code",
"is",
"None",
":",
"_LOGGER",
".",
"error",
"(",
"\"Code required but none provided\"",
")",
"return",
"self",
".",
"set_lock_state",
"(",
"code",
",",
"STATE_LOCKED",
")"
] | [
108,
4
] | [
118,
47
] | python | en | ['en', 'zh', 'en'] | True |
VerisureDoorlock.set_lock_state | (self, code, state) | Send set lock state command. | Send set lock state command. | def set_lock_state(self, code, state):
"""Send set lock state command."""
lock_state = "lock" if state == STATE_LOCKED else "unlock"
transaction_id = hub.session.set_lock_state(
code, self._device_label, lock_state
)["doorLockStateChangeTransactionId"]
_LOGGER.debug("Verisure doorlock %s", state)
transaction = {}
attempts = 0
while "result" not in transaction:
transaction = hub.session.get_lock_state_transaction(transaction_id)
attempts += 1
if attempts == 30:
break
if attempts > 1:
sleep(0.5)
if transaction["result"] == "OK":
self._state = state
self._change_timestamp = monotonic() | [
"def",
"set_lock_state",
"(",
"self",
",",
"code",
",",
"state",
")",
":",
"lock_state",
"=",
"\"lock\"",
"if",
"state",
"==",
"STATE_LOCKED",
"else",
"\"unlock\"",
"transaction_id",
"=",
"hub",
".",
"session",
".",
"set_lock_state",
"(",
"code",
",",
"self",
".",
"_device_label",
",",
"lock_state",
")",
"[",
"\"doorLockStateChangeTransactionId\"",
"]",
"_LOGGER",
".",
"debug",
"(",
"\"Verisure doorlock %s\"",
",",
"state",
")",
"transaction",
"=",
"{",
"}",
"attempts",
"=",
"0",
"while",
"\"result\"",
"not",
"in",
"transaction",
":",
"transaction",
"=",
"hub",
".",
"session",
".",
"get_lock_state_transaction",
"(",
"transaction_id",
")",
"attempts",
"+=",
"1",
"if",
"attempts",
"==",
"30",
":",
"break",
"if",
"attempts",
">",
"1",
":",
"sleep",
"(",
"0.5",
")",
"if",
"transaction",
"[",
"\"result\"",
"]",
"==",
"\"OK\"",
":",
"self",
".",
"_state",
"=",
"state",
"self",
".",
"_change_timestamp",
"=",
"monotonic",
"(",
")"
] | [
120,
4
] | [
138,
48
] | python | en | ['en', 'en', 'en'] | True |
test_async_setup_entry | (hass) | Test a successful setup entry. | Test a successful setup entry. | async def test_async_setup_entry(hass):
"""Test a successful setup entry."""
await init_integration(hass)
state = hass.states.get("air_quality.home")
assert state is not None
assert state.state != STATE_UNAVAILABLE
assert state.state == "14" | [
"async",
"def",
"test_async_setup_entry",
"(",
"hass",
")",
":",
"await",
"init_integration",
"(",
"hass",
")",
"state",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"\"air_quality.home\"",
")",
"assert",
"state",
"is",
"not",
"None",
"assert",
"state",
".",
"state",
"!=",
"STATE_UNAVAILABLE",
"assert",
"state",
".",
"state",
"==",
"\"14\""
] | [
17,
0
] | [
24,
30
] | python | en | ['en', 'en', 'en'] | True |
test_config_not_ready | (hass) | Test for setup failure if connection to Airly is missing. | Test for setup failure if connection to Airly is missing. | async def test_config_not_ready(hass):
"""Test for setup failure if connection to Airly is missing."""
entry = MockConfigEntry(
domain=DOMAIN,
title="Home",
unique_id="55.55-122.12",
data={
"api_key": "foo",
"latitude": 55.55,
"longitude": 122.12,
"name": "Home",
},
)
with patch("airly._private._RequestsHandler.get", side_effect=ConnectionError()):
entry.add_to_hass(hass)
await hass.config_entries.async_setup(entry.entry_id)
assert entry.state == ENTRY_STATE_SETUP_RETRY | [
"async",
"def",
"test_config_not_ready",
"(",
"hass",
")",
":",
"entry",
"=",
"MockConfigEntry",
"(",
"domain",
"=",
"DOMAIN",
",",
"title",
"=",
"\"Home\"",
",",
"unique_id",
"=",
"\"55.55-122.12\"",
",",
"data",
"=",
"{",
"\"api_key\"",
":",
"\"foo\"",
",",
"\"latitude\"",
":",
"55.55",
",",
"\"longitude\"",
":",
"122.12",
",",
"\"name\"",
":",
"\"Home\"",
",",
"}",
",",
")",
"with",
"patch",
"(",
"\"airly._private._RequestsHandler.get\"",
",",
"side_effect",
"=",
"ConnectionError",
"(",
")",
")",
":",
"entry",
".",
"add_to_hass",
"(",
"hass",
")",
"await",
"hass",
".",
"config_entries",
".",
"async_setup",
"(",
"entry",
".",
"entry_id",
")",
"assert",
"entry",
".",
"state",
"==",
"ENTRY_STATE_SETUP_RETRY"
] | [
27,
0
] | [
44,
53
] | python | en | ['en', 'en', 'en'] | True |
test_config_without_unique_id | (hass) | Test for setup entry without unique_id. | Test for setup entry without unique_id. | async def test_config_without_unique_id(hass):
"""Test for setup entry without unique_id."""
entry = MockConfigEntry(
domain=DOMAIN,
title="Home",
data={
"api_key": "foo",
"latitude": 55.55,
"longitude": 122.12,
"name": "Home",
},
)
with patch(
"airly._private._RequestsHandler.get",
return_value=json.loads(load_fixture("airly_valid_station.json")),
):
entry.add_to_hass(hass)
await hass.config_entries.async_setup(entry.entry_id)
assert entry.state == ENTRY_STATE_LOADED
assert entry.unique_id == "55.55-122.12" | [
"async",
"def",
"test_config_without_unique_id",
"(",
"hass",
")",
":",
"entry",
"=",
"MockConfigEntry",
"(",
"domain",
"=",
"DOMAIN",
",",
"title",
"=",
"\"Home\"",
",",
"data",
"=",
"{",
"\"api_key\"",
":",
"\"foo\"",
",",
"\"latitude\"",
":",
"55.55",
",",
"\"longitude\"",
":",
"122.12",
",",
"\"name\"",
":",
"\"Home\"",
",",
"}",
",",
")",
"with",
"patch",
"(",
"\"airly._private._RequestsHandler.get\"",
",",
"return_value",
"=",
"json",
".",
"loads",
"(",
"load_fixture",
"(",
"\"airly_valid_station.json\"",
")",
")",
",",
")",
":",
"entry",
".",
"add_to_hass",
"(",
"hass",
")",
"await",
"hass",
".",
"config_entries",
".",
"async_setup",
"(",
"entry",
".",
"entry_id",
")",
"assert",
"entry",
".",
"state",
"==",
"ENTRY_STATE_LOADED",
"assert",
"entry",
".",
"unique_id",
"==",
"\"55.55-122.12\""
] | [
47,
0
] | [
67,
48
] | python | en | ['en', 'en', 'en'] | True |
test_config_with_turned_off_station | (hass) | Test for setup entry for a turned off measuring station. | Test for setup entry for a turned off measuring station. | async def test_config_with_turned_off_station(hass):
"""Test for setup entry for a turned off measuring station."""
entry = MockConfigEntry(
domain=DOMAIN,
title="Home",
unique_id="55.55-122.12",
data={
"api_key": "foo",
"latitude": 55.55,
"longitude": 122.12,
"name": "Home",
},
)
with patch(
"airly._private._RequestsHandler.get",
return_value=json.loads(load_fixture("airly_no_station.json")),
):
entry.add_to_hass(hass)
await hass.config_entries.async_setup(entry.entry_id)
assert entry.state == ENTRY_STATE_SETUP_RETRY | [
"async",
"def",
"test_config_with_turned_off_station",
"(",
"hass",
")",
":",
"entry",
"=",
"MockConfigEntry",
"(",
"domain",
"=",
"DOMAIN",
",",
"title",
"=",
"\"Home\"",
",",
"unique_id",
"=",
"\"55.55-122.12\"",
",",
"data",
"=",
"{",
"\"api_key\"",
":",
"\"foo\"",
",",
"\"latitude\"",
":",
"55.55",
",",
"\"longitude\"",
":",
"122.12",
",",
"\"name\"",
":",
"\"Home\"",
",",
"}",
",",
")",
"with",
"patch",
"(",
"\"airly._private._RequestsHandler.get\"",
",",
"return_value",
"=",
"json",
".",
"loads",
"(",
"load_fixture",
"(",
"\"airly_no_station.json\"",
")",
")",
",",
")",
":",
"entry",
".",
"add_to_hass",
"(",
"hass",
")",
"await",
"hass",
".",
"config_entries",
".",
"async_setup",
"(",
"entry",
".",
"entry_id",
")",
"assert",
"entry",
".",
"state",
"==",
"ENTRY_STATE_SETUP_RETRY"
] | [
70,
0
] | [
90,
53
] | python | en | ['en', 'da', 'en'] | True |
test_update_interval | (hass) | Test correct update interval when the number of configured instances changes. | Test correct update interval when the number of configured instances changes. | async def test_update_interval(hass):
"""Test correct update interval when the number of configured instances changes."""
entry = await init_integration(hass)
assert len(hass.config_entries.async_entries(DOMAIN)) == 1
assert entry.state == ENTRY_STATE_LOADED
for instance in hass.data[DOMAIN].values():
assert instance.update_interval == timedelta(minutes=15)
entry = MockConfigEntry(
domain=DOMAIN,
title="Work",
unique_id="66.66-111.11",
data={
"api_key": "foo",
"latitude": 66.66,
"longitude": 111.11,
"name": "Work",
},
)
with patch(
"airly._private._RequestsHandler.get",
return_value=json.loads(load_fixture("airly_valid_station.json")),
):
entry.add_to_hass(hass)
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
assert len(hass.config_entries.async_entries(DOMAIN)) == 2
assert entry.state == ENTRY_STATE_LOADED
for instance in hass.data[DOMAIN].values():
assert instance.update_interval == timedelta(minutes=30) | [
"async",
"def",
"test_update_interval",
"(",
"hass",
")",
":",
"entry",
"=",
"await",
"init_integration",
"(",
"hass",
")",
"assert",
"len",
"(",
"hass",
".",
"config_entries",
".",
"async_entries",
"(",
"DOMAIN",
")",
")",
"==",
"1",
"assert",
"entry",
".",
"state",
"==",
"ENTRY_STATE_LOADED",
"for",
"instance",
"in",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
".",
"values",
"(",
")",
":",
"assert",
"instance",
".",
"update_interval",
"==",
"timedelta",
"(",
"minutes",
"=",
"15",
")",
"entry",
"=",
"MockConfigEntry",
"(",
"domain",
"=",
"DOMAIN",
",",
"title",
"=",
"\"Work\"",
",",
"unique_id",
"=",
"\"66.66-111.11\"",
",",
"data",
"=",
"{",
"\"api_key\"",
":",
"\"foo\"",
",",
"\"latitude\"",
":",
"66.66",
",",
"\"longitude\"",
":",
"111.11",
",",
"\"name\"",
":",
"\"Work\"",
",",
"}",
",",
")",
"with",
"patch",
"(",
"\"airly._private._RequestsHandler.get\"",
",",
"return_value",
"=",
"json",
".",
"loads",
"(",
"load_fixture",
"(",
"\"airly_valid_station.json\"",
")",
")",
",",
")",
":",
"entry",
".",
"add_to_hass",
"(",
"hass",
")",
"await",
"hass",
".",
"config_entries",
".",
"async_setup",
"(",
"entry",
".",
"entry_id",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"len",
"(",
"hass",
".",
"config_entries",
".",
"async_entries",
"(",
"DOMAIN",
")",
")",
"==",
"2",
"assert",
"entry",
".",
"state",
"==",
"ENTRY_STATE_LOADED",
"for",
"instance",
"in",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
".",
"values",
"(",
")",
":",
"assert",
"instance",
".",
"update_interval",
"==",
"timedelta",
"(",
"minutes",
"=",
"30",
")"
] | [
93,
0
] | [
125,
64
] | python | en | ['en', 'en', 'en'] | True |
test_unload_entry | (hass) | Test successful unload of entry. | Test successful unload of entry. | async def test_unload_entry(hass):
"""Test successful unload of entry."""
entry = await init_integration(hass)
assert len(hass.config_entries.async_entries(DOMAIN)) == 1
assert entry.state == ENTRY_STATE_LOADED
assert await hass.config_entries.async_unload(entry.entry_id)
await hass.async_block_till_done()
assert entry.state == ENTRY_STATE_NOT_LOADED
assert not hass.data.get(DOMAIN) | [
"async",
"def",
"test_unload_entry",
"(",
"hass",
")",
":",
"entry",
"=",
"await",
"init_integration",
"(",
"hass",
")",
"assert",
"len",
"(",
"hass",
".",
"config_entries",
".",
"async_entries",
"(",
"DOMAIN",
")",
")",
"==",
"1",
"assert",
"entry",
".",
"state",
"==",
"ENTRY_STATE_LOADED",
"assert",
"await",
"hass",
".",
"config_entries",
".",
"async_unload",
"(",
"entry",
".",
"entry_id",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"entry",
".",
"state",
"==",
"ENTRY_STATE_NOT_LOADED",
"assert",
"not",
"hass",
".",
"data",
".",
"get",
"(",
"DOMAIN",
")"
] | [
128,
0
] | [
139,
36
] | python | en | ['en', 'en', 'en'] | True |
async_get_handler | (hass, config, discovery_info=None) | Set up the Asterix CDR platform. | Set up the Asterix CDR platform. | async def async_get_handler(hass, config, discovery_info=None):
"""Set up the Asterix CDR platform."""
return AsteriskCDR(hass, MAILBOX_NAME) | [
"async",
"def",
"async_get_handler",
"(",
"hass",
",",
"config",
",",
"discovery_info",
"=",
"None",
")",
":",
"return",
"AsteriskCDR",
"(",
"hass",
",",
"MAILBOX_NAME",
")"
] | [
15,
0
] | [
17,
42
] | python | en | ['en', 'da', 'en'] | True |
AsteriskCDR.__init__ | (self, hass, name) | Initialize Asterisk CDR. | Initialize Asterisk CDR. | def __init__(self, hass, name):
"""Initialize Asterisk CDR."""
super().__init__(hass, name)
self.cdr = []
async_dispatcher_connect(self.hass, SIGNAL_CDR_UPDATE, self._update_callback) | [
"def",
"__init__",
"(",
"self",
",",
"hass",
",",
"name",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"hass",
",",
"name",
")",
"self",
".",
"cdr",
"=",
"[",
"]",
"async_dispatcher_connect",
"(",
"self",
".",
"hass",
",",
"SIGNAL_CDR_UPDATE",
",",
"self",
".",
"_update_callback",
")"
] | [
23,
4
] | [
27,
85
] | python | da | ['da', 'en', 'it'] | False |
AsteriskCDR._update_callback | (self, msg) | Update the message count in HA, if needed. | Update the message count in HA, if needed. | def _update_callback(self, msg):
"""Update the message count in HA, if needed."""
self._build_message()
self.async_update() | [
"def",
"_update_callback",
"(",
"self",
",",
"msg",
")",
":",
"self",
".",
"_build_message",
"(",
")",
"self",
".",
"async_update",
"(",
")"
] | [
30,
4
] | [
33,
27
] | python | en | ['en', 'en', 'en'] | True |
AsteriskCDR._build_message | (self) | Build message structure. | Build message structure. | def _build_message(self):
"""Build message structure."""
cdr = []
for entry in self.hass.data[ASTERISK_DOMAIN].cdr:
timestamp = datetime.datetime.strptime(
entry["time"], "%Y-%m-%d %H:%M:%S"
).timestamp()
info = {
"origtime": timestamp,
"callerid": entry["callerid"],
"duration": entry["duration"],
}
sha = hashlib.sha256(str(entry).encode("utf-8")).hexdigest()
msg = (
f"Destination: {entry['dest']}\n"
f"Application: {entry['application']}\n "
f"Context: {entry['context']}"
)
cdr.append({"info": info, "sha": sha, "text": msg})
self.cdr = cdr | [
"def",
"_build_message",
"(",
"self",
")",
":",
"cdr",
"=",
"[",
"]",
"for",
"entry",
"in",
"self",
".",
"hass",
".",
"data",
"[",
"ASTERISK_DOMAIN",
"]",
".",
"cdr",
":",
"timestamp",
"=",
"datetime",
".",
"datetime",
".",
"strptime",
"(",
"entry",
"[",
"\"time\"",
"]",
",",
"\"%Y-%m-%d %H:%M:%S\"",
")",
".",
"timestamp",
"(",
")",
"info",
"=",
"{",
"\"origtime\"",
":",
"timestamp",
",",
"\"callerid\"",
":",
"entry",
"[",
"\"callerid\"",
"]",
",",
"\"duration\"",
":",
"entry",
"[",
"\"duration\"",
"]",
",",
"}",
"sha",
"=",
"hashlib",
".",
"sha256",
"(",
"str",
"(",
"entry",
")",
".",
"encode",
"(",
"\"utf-8\"",
")",
")",
".",
"hexdigest",
"(",
")",
"msg",
"=",
"(",
"f\"Destination: {entry['dest']}\\n\"",
"f\"Application: {entry['application']}\\n \"",
"f\"Context: {entry['context']}\"",
")",
"cdr",
".",
"append",
"(",
"{",
"\"info\"",
":",
"info",
",",
"\"sha\"",
":",
"sha",
",",
"\"text\"",
":",
"msg",
"}",
")",
"self",
".",
"cdr",
"=",
"cdr"
] | [
35,
4
] | [
54,
22
] | python | en | ['en', 'fr', 'en'] | True |
AsteriskCDR.async_get_messages | (self) | Return a list of the current messages. | Return a list of the current messages. | async def async_get_messages(self):
"""Return a list of the current messages."""
if not self.cdr:
self._build_message()
return self.cdr | [
"async",
"def",
"async_get_messages",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"cdr",
":",
"self",
".",
"_build_message",
"(",
")",
"return",
"self",
".",
"cdr"
] | [
56,
4
] | [
60,
23
] | python | en | ['en', 'en', 'en'] | True |
gather_system_health_info | (hass, hass_ws_client) | Gather all info. | Gather all info. | async def gather_system_health_info(hass, hass_ws_client):
"""Gather all info."""
client = await hass_ws_client(hass)
resp = await client.send_json({"id": 6, "type": "system_health/info"})
# Confirm subscription
resp = await client.receive_json()
assert resp["success"]
data = {}
# Get initial data
resp = await client.receive_json()
assert resp["event"]["type"] == "initial"
data = resp["event"]["data"]
while True:
resp = await client.receive_json()
event = resp["event"]
if event["type"] == "finish":
break
assert event["type"] == "update"
if event["success"]:
data[event["domain"]]["info"][event["key"]] = event["data"]
else:
data[event["domain"]]["info"][event["key"]] = event["error"]
return data | [
"async",
"def",
"gather_system_health_info",
"(",
"hass",
",",
"hass_ws_client",
")",
":",
"client",
"=",
"await",
"hass_ws_client",
"(",
"hass",
")",
"resp",
"=",
"await",
"client",
".",
"send_json",
"(",
"{",
"\"id\"",
":",
"6",
",",
"\"type\"",
":",
"\"system_health/info\"",
"}",
")",
"# Confirm subscription",
"resp",
"=",
"await",
"client",
".",
"receive_json",
"(",
")",
"assert",
"resp",
"[",
"\"success\"",
"]",
"data",
"=",
"{",
"}",
"# Get initial data",
"resp",
"=",
"await",
"client",
".",
"receive_json",
"(",
")",
"assert",
"resp",
"[",
"\"event\"",
"]",
"[",
"\"type\"",
"]",
"==",
"\"initial\"",
"data",
"=",
"resp",
"[",
"\"event\"",
"]",
"[",
"\"data\"",
"]",
"while",
"True",
":",
"resp",
"=",
"await",
"client",
".",
"receive_json",
"(",
")",
"event",
"=",
"resp",
"[",
"\"event\"",
"]",
"if",
"event",
"[",
"\"type\"",
"]",
"==",
"\"finish\"",
":",
"break",
"assert",
"event",
"[",
"\"type\"",
"]",
"==",
"\"update\"",
"if",
"event",
"[",
"\"success\"",
"]",
":",
"data",
"[",
"event",
"[",
"\"domain\"",
"]",
"]",
"[",
"\"info\"",
"]",
"[",
"event",
"[",
"\"key\"",
"]",
"]",
"=",
"event",
"[",
"\"data\"",
"]",
"else",
":",
"data",
"[",
"event",
"[",
"\"domain\"",
"]",
"]",
"[",
"\"info\"",
"]",
"[",
"event",
"[",
"\"key\"",
"]",
"]",
"=",
"event",
"[",
"\"error\"",
"]",
"return",
"data"
] | [
12,
0
] | [
43,
15
] | python | en | ['en', 'en', 'en'] | True |
test_info_endpoint_return_info | (hass, hass_ws_client) | Test that the info endpoint works. | Test that the info endpoint works. | async def test_info_endpoint_return_info(hass, hass_ws_client):
"""Test that the info endpoint works."""
assert await async_setup_component(hass, "homeassistant", {})
with patch(
"homeassistant.components.homeassistant.system_health.system_health_info",
return_value={"hello": True},
):
assert await async_setup_component(hass, "system_health", {})
data = await gather_system_health_info(hass, hass_ws_client)
assert len(data) == 1
data = data["homeassistant"]
assert data == {"info": {"hello": True}} | [
"async",
"def",
"test_info_endpoint_return_info",
"(",
"hass",
",",
"hass_ws_client",
")",
":",
"assert",
"await",
"async_setup_component",
"(",
"hass",
",",
"\"homeassistant\"",
",",
"{",
"}",
")",
"with",
"patch",
"(",
"\"homeassistant.components.homeassistant.system_health.system_health_info\"",
",",
"return_value",
"=",
"{",
"\"hello\"",
":",
"True",
"}",
",",
")",
":",
"assert",
"await",
"async_setup_component",
"(",
"hass",
",",
"\"system_health\"",
",",
"{",
"}",
")",
"data",
"=",
"await",
"gather_system_health_info",
"(",
"hass",
",",
"hass_ws_client",
")",
"assert",
"len",
"(",
"data",
")",
"==",
"1",
"data",
"=",
"data",
"[",
"\"homeassistant\"",
"]",
"assert",
"data",
"==",
"{",
"\"info\"",
":",
"{",
"\"hello\"",
":",
"True",
"}",
"}"
] | [
46,
0
] | [
60,
44
] | python | en | ['en', 'en', 'en'] | True |
test_info_endpoint_register_callback | (hass, hass_ws_client) | Test that the info endpoint allows registering callbacks. | Test that the info endpoint allows registering callbacks. | async def test_info_endpoint_register_callback(hass, hass_ws_client):
"""Test that the info endpoint allows registering callbacks."""
async def mock_info(hass):
return {"storage": "YAML"}
hass.components.system_health.async_register_info("lovelace", mock_info)
assert await async_setup_component(hass, "system_health", {})
data = await gather_system_health_info(hass, hass_ws_client)
assert len(data) == 1
data = data["lovelace"]
assert data == {"info": {"storage": "YAML"}}
# Test our test helper works
assert await get_system_health_info(hass, "lovelace") == {"storage": "YAML"} | [
"async",
"def",
"test_info_endpoint_register_callback",
"(",
"hass",
",",
"hass_ws_client",
")",
":",
"async",
"def",
"mock_info",
"(",
"hass",
")",
":",
"return",
"{",
"\"storage\"",
":",
"\"YAML\"",
"}",
"hass",
".",
"components",
".",
"system_health",
".",
"async_register_info",
"(",
"\"lovelace\"",
",",
"mock_info",
")",
"assert",
"await",
"async_setup_component",
"(",
"hass",
",",
"\"system_health\"",
",",
"{",
"}",
")",
"data",
"=",
"await",
"gather_system_health_info",
"(",
"hass",
",",
"hass_ws_client",
")",
"assert",
"len",
"(",
"data",
")",
"==",
"1",
"data",
"=",
"data",
"[",
"\"lovelace\"",
"]",
"assert",
"data",
"==",
"{",
"\"info\"",
":",
"{",
"\"storage\"",
":",
"\"YAML\"",
"}",
"}",
"# Test our test helper works",
"assert",
"await",
"get_system_health_info",
"(",
"hass",
",",
"\"lovelace\"",
")",
"==",
"{",
"\"storage\"",
":",
"\"YAML\"",
"}"
] | [
63,
0
] | [
78,
80
] | python | en | ['en', 'en', 'en'] | True |
test_info_endpoint_register_callback_timeout | (hass, hass_ws_client) | Test that the info endpoint timing out. | Test that the info endpoint timing out. | async def test_info_endpoint_register_callback_timeout(hass, hass_ws_client):
"""Test that the info endpoint timing out."""
async def mock_info(hass):
raise asyncio.TimeoutError
hass.components.system_health.async_register_info("lovelace", mock_info)
assert await async_setup_component(hass, "system_health", {})
data = await gather_system_health_info(hass, hass_ws_client)
assert len(data) == 1
data = data["lovelace"]
assert data == {"info": {"error": {"type": "failed", "error": "timeout"}}} | [
"async",
"def",
"test_info_endpoint_register_callback_timeout",
"(",
"hass",
",",
"hass_ws_client",
")",
":",
"async",
"def",
"mock_info",
"(",
"hass",
")",
":",
"raise",
"asyncio",
".",
"TimeoutError",
"hass",
".",
"components",
".",
"system_health",
".",
"async_register_info",
"(",
"\"lovelace\"",
",",
"mock_info",
")",
"assert",
"await",
"async_setup_component",
"(",
"hass",
",",
"\"system_health\"",
",",
"{",
"}",
")",
"data",
"=",
"await",
"gather_system_health_info",
"(",
"hass",
",",
"hass_ws_client",
")",
"assert",
"len",
"(",
"data",
")",
"==",
"1",
"data",
"=",
"data",
"[",
"\"lovelace\"",
"]",
"assert",
"data",
"==",
"{",
"\"info\"",
":",
"{",
"\"error\"",
":",
"{",
"\"type\"",
":",
"\"failed\"",
",",
"\"error\"",
":",
"\"timeout\"",
"}",
"}",
"}"
] | [
81,
0
] | [
93,
78
] | python | en | ['en', 'en', 'en'] | True |
test_info_endpoint_register_callback_exc | (hass, hass_ws_client) | Test that the info endpoint requires auth. | Test that the info endpoint requires auth. | async def test_info_endpoint_register_callback_exc(hass, hass_ws_client):
"""Test that the info endpoint requires auth."""
async def mock_info(hass):
raise Exception("TEST ERROR")
hass.components.system_health.async_register_info("lovelace", mock_info)
assert await async_setup_component(hass, "system_health", {})
data = await gather_system_health_info(hass, hass_ws_client)
assert len(data) == 1
data = data["lovelace"]
assert data == {"info": {"error": {"type": "failed", "error": "unknown"}}} | [
"async",
"def",
"test_info_endpoint_register_callback_exc",
"(",
"hass",
",",
"hass_ws_client",
")",
":",
"async",
"def",
"mock_info",
"(",
"hass",
")",
":",
"raise",
"Exception",
"(",
"\"TEST ERROR\"",
")",
"hass",
".",
"components",
".",
"system_health",
".",
"async_register_info",
"(",
"\"lovelace\"",
",",
"mock_info",
")",
"assert",
"await",
"async_setup_component",
"(",
"hass",
",",
"\"system_health\"",
",",
"{",
"}",
")",
"data",
"=",
"await",
"gather_system_health_info",
"(",
"hass",
",",
"hass_ws_client",
")",
"assert",
"len",
"(",
"data",
")",
"==",
"1",
"data",
"=",
"data",
"[",
"\"lovelace\"",
"]",
"assert",
"data",
"==",
"{",
"\"info\"",
":",
"{",
"\"error\"",
":",
"{",
"\"type\"",
":",
"\"failed\"",
",",
"\"error\"",
":",
"\"unknown\"",
"}",
"}",
"}"
] | [
96,
0
] | [
108,
78
] | python | en | ['en', 'en', 'en'] | True |
test_platform_loading | (hass, hass_ws_client, aioclient_mock) | Test registering via platform. | Test registering via platform. | async def test_platform_loading(hass, hass_ws_client, aioclient_mock):
"""Test registering via platform."""
aioclient_mock.get("http://example.com/status", text="")
aioclient_mock.get("http://example.com/status_fail", exc=ClientError)
hass.config.components.add("fake_integration")
mock_platform(
hass,
"fake_integration.system_health",
Mock(
async_register=lambda hass, register: register.async_register_info(
AsyncMock(
return_value={
"hello": "info",
"server_reachable": system_health.async_check_can_reach_url(
hass, "http://example.com/status"
),
"server_fail_reachable": system_health.async_check_can_reach_url(
hass,
"http://example.com/status_fail",
more_info="http://more-info-url.com",
),
"async_crash": AsyncMock(side_effect=ValueError)(),
}
),
"/config/fake_integration",
)
),
)
assert await async_setup_component(hass, "system_health", {})
data = await gather_system_health_info(hass, hass_ws_client)
assert data["fake_integration"] == {
"info": {
"hello": "info",
"server_reachable": "ok",
"server_fail_reachable": {
"type": "failed",
"error": "unreachable",
"more_info": "http://more-info-url.com",
},
"async_crash": {
"type": "failed",
"error": "unknown",
},
},
"manage_url": "/config/fake_integration",
} | [
"async",
"def",
"test_platform_loading",
"(",
"hass",
",",
"hass_ws_client",
",",
"aioclient_mock",
")",
":",
"aioclient_mock",
".",
"get",
"(",
"\"http://example.com/status\"",
",",
"text",
"=",
"\"\"",
")",
"aioclient_mock",
".",
"get",
"(",
"\"http://example.com/status_fail\"",
",",
"exc",
"=",
"ClientError",
")",
"hass",
".",
"config",
".",
"components",
".",
"add",
"(",
"\"fake_integration\"",
")",
"mock_platform",
"(",
"hass",
",",
"\"fake_integration.system_health\"",
",",
"Mock",
"(",
"async_register",
"=",
"lambda",
"hass",
",",
"register",
":",
"register",
".",
"async_register_info",
"(",
"AsyncMock",
"(",
"return_value",
"=",
"{",
"\"hello\"",
":",
"\"info\"",
",",
"\"server_reachable\"",
":",
"system_health",
".",
"async_check_can_reach_url",
"(",
"hass",
",",
"\"http://example.com/status\"",
")",
",",
"\"server_fail_reachable\"",
":",
"system_health",
".",
"async_check_can_reach_url",
"(",
"hass",
",",
"\"http://example.com/status_fail\"",
",",
"more_info",
"=",
"\"http://more-info-url.com\"",
",",
")",
",",
"\"async_crash\"",
":",
"AsyncMock",
"(",
"side_effect",
"=",
"ValueError",
")",
"(",
")",
",",
"}",
")",
",",
"\"/config/fake_integration\"",
",",
")",
")",
",",
")",
"assert",
"await",
"async_setup_component",
"(",
"hass",
",",
"\"system_health\"",
",",
"{",
"}",
")",
"data",
"=",
"await",
"gather_system_health_info",
"(",
"hass",
",",
"hass_ws_client",
")",
"assert",
"data",
"[",
"\"fake_integration\"",
"]",
"==",
"{",
"\"info\"",
":",
"{",
"\"hello\"",
":",
"\"info\"",
",",
"\"server_reachable\"",
":",
"\"ok\"",
",",
"\"server_fail_reachable\"",
":",
"{",
"\"type\"",
":",
"\"failed\"",
",",
"\"error\"",
":",
"\"unreachable\"",
",",
"\"more_info\"",
":",
"\"http://more-info-url.com\"",
",",
"}",
",",
"\"async_crash\"",
":",
"{",
"\"type\"",
":",
"\"failed\"",
",",
"\"error\"",
":",
"\"unknown\"",
",",
"}",
",",
"}",
",",
"\"manage_url\"",
":",
"\"/config/fake_integration\"",
",",
"}"
] | [
111,
0
] | [
158,
5
] | python | da | ['nl', 'da', 'en'] | False |
mock_handler | (request) | Return the real IP as text. | Return the real IP as text. | async def mock_handler(request):
"""Return the real IP as text."""
return web.Response(text=request.remote) | [
"async",
"def",
"mock_handler",
"(",
"request",
")",
":",
"return",
"web",
".",
"Response",
"(",
"text",
"=",
"request",
".",
"remote",
")"
] | [
10,
0
] | [
12,
44
] | python | en | ['en', 'en', 'en'] | True |
test_x_forwarded_for_without_trusted_proxy | (aiohttp_client, caplog) | Test that we get the IP from the transport. | Test that we get the IP from the transport. | async def test_x_forwarded_for_without_trusted_proxy(aiohttp_client, caplog):
"""Test that we get the IP from the transport."""
async def handler(request):
url = mock_api_client.make_url("/")
assert request.host == f"{url.host}:{url.port}"
assert request.scheme == "http"
assert not request.secure
assert request.remote == "127.0.0.1"
return web.Response()
app = web.Application()
app.router.add_get("/", handler)
async_setup_forwarded(app, [])
mock_api_client = await aiohttp_client(app)
resp = await mock_api_client.get("/", headers={X_FORWARDED_FOR: "255.255.255.255"})
assert resp.status == 200
assert (
"Received X-Forwarded-For header from untrusted proxy 127.0.0.1, headers not processed"
in caplog.text
) | [
"async",
"def",
"test_x_forwarded_for_without_trusted_proxy",
"(",
"aiohttp_client",
",",
"caplog",
")",
":",
"async",
"def",
"handler",
"(",
"request",
")",
":",
"url",
"=",
"mock_api_client",
".",
"make_url",
"(",
"\"/\"",
")",
"assert",
"request",
".",
"host",
"==",
"f\"{url.host}:{url.port}\"",
"assert",
"request",
".",
"scheme",
"==",
"\"http\"",
"assert",
"not",
"request",
".",
"secure",
"assert",
"request",
".",
"remote",
"==",
"\"127.0.0.1\"",
"return",
"web",
".",
"Response",
"(",
")",
"app",
"=",
"web",
".",
"Application",
"(",
")",
"app",
".",
"router",
".",
"add_get",
"(",
"\"/\"",
",",
"handler",
")",
"async_setup_forwarded",
"(",
"app",
",",
"[",
"]",
")",
"mock_api_client",
"=",
"await",
"aiohttp_client",
"(",
"app",
")",
"resp",
"=",
"await",
"mock_api_client",
".",
"get",
"(",
"\"/\"",
",",
"headers",
"=",
"{",
"X_FORWARDED_FOR",
":",
"\"255.255.255.255\"",
"}",
")",
"assert",
"resp",
".",
"status",
"==",
"200",
"assert",
"(",
"\"Received X-Forwarded-For header from untrusted proxy 127.0.0.1, headers not processed\"",
"in",
"caplog",
".",
"text",
")"
] | [
15,
0
] | [
39,
5
] | python | en | ['en', 'en', 'en'] | True |
test_x_forwarded_for_with_trusted_proxy | (
trusted_proxies, x_forwarded_for, remote, aiohttp_client
) | Test that we get the IP from the forwarded for header. | Test that we get the IP from the forwarded for header. | async def test_x_forwarded_for_with_trusted_proxy(
trusted_proxies, x_forwarded_for, remote, aiohttp_client
):
"""Test that we get the IP from the forwarded for header."""
async def handler(request):
url = mock_api_client.make_url("/")
assert request.host == f"{url.host}:{url.port}"
assert request.scheme == "http"
assert not request.secure
assert request.remote == remote
return web.Response()
app = web.Application()
app.router.add_get("/", handler)
async_setup_forwarded(
app, [ip_network(trusted_proxy) for trusted_proxy in trusted_proxies]
)
mock_api_client = await aiohttp_client(app)
resp = await mock_api_client.get("/", headers={X_FORWARDED_FOR: x_forwarded_for})
assert resp.status == 200 | [
"async",
"def",
"test_x_forwarded_for_with_trusted_proxy",
"(",
"trusted_proxies",
",",
"x_forwarded_for",
",",
"remote",
",",
"aiohttp_client",
")",
":",
"async",
"def",
"handler",
"(",
"request",
")",
":",
"url",
"=",
"mock_api_client",
".",
"make_url",
"(",
"\"/\"",
")",
"assert",
"request",
".",
"host",
"==",
"f\"{url.host}:{url.port}\"",
"assert",
"request",
".",
"scheme",
"==",
"\"http\"",
"assert",
"not",
"request",
".",
"secure",
"assert",
"request",
".",
"remote",
"==",
"remote",
"return",
"web",
".",
"Response",
"(",
")",
"app",
"=",
"web",
".",
"Application",
"(",
")",
"app",
".",
"router",
".",
"add_get",
"(",
"\"/\"",
",",
"handler",
")",
"async_setup_forwarded",
"(",
"app",
",",
"[",
"ip_network",
"(",
"trusted_proxy",
")",
"for",
"trusted_proxy",
"in",
"trusted_proxies",
"]",
")",
"mock_api_client",
"=",
"await",
"aiohttp_client",
"(",
"app",
")",
"resp",
"=",
"await",
"mock_api_client",
".",
"get",
"(",
"\"/\"",
",",
"headers",
"=",
"{",
"X_FORWARDED_FOR",
":",
"x_forwarded_for",
"}",
")",
"assert",
"resp",
".",
"status",
"==",
"200"
] | [
59,
0
] | [
82,
29
] | python | en | ['en', 'en', 'en'] | True |
test_x_forwarded_for_with_untrusted_proxy | (aiohttp_client) | Test that we get the IP from transport with untrusted proxy. | Test that we get the IP from transport with untrusted proxy. | async def test_x_forwarded_for_with_untrusted_proxy(aiohttp_client):
"""Test that we get the IP from transport with untrusted proxy."""
async def handler(request):
url = mock_api_client.make_url("/")
assert request.host == f"{url.host}:{url.port}"
assert request.scheme == "http"
assert not request.secure
assert request.remote == "127.0.0.1"
return web.Response()
app = web.Application()
app.router.add_get("/", handler)
async_setup_forwarded(app, [ip_network("1.1.1.1")])
mock_api_client = await aiohttp_client(app)
resp = await mock_api_client.get("/", headers={X_FORWARDED_FOR: "255.255.255.255"})
assert resp.status == 200 | [
"async",
"def",
"test_x_forwarded_for_with_untrusted_proxy",
"(",
"aiohttp_client",
")",
":",
"async",
"def",
"handler",
"(",
"request",
")",
":",
"url",
"=",
"mock_api_client",
".",
"make_url",
"(",
"\"/\"",
")",
"assert",
"request",
".",
"host",
"==",
"f\"{url.host}:{url.port}\"",
"assert",
"request",
".",
"scheme",
"==",
"\"http\"",
"assert",
"not",
"request",
".",
"secure",
"assert",
"request",
".",
"remote",
"==",
"\"127.0.0.1\"",
"return",
"web",
".",
"Response",
"(",
")",
"app",
"=",
"web",
".",
"Application",
"(",
")",
"app",
".",
"router",
".",
"add_get",
"(",
"\"/\"",
",",
"handler",
")",
"async_setup_forwarded",
"(",
"app",
",",
"[",
"ip_network",
"(",
"\"1.1.1.1\"",
")",
"]",
")",
"mock_api_client",
"=",
"await",
"aiohttp_client",
"(",
"app",
")",
"resp",
"=",
"await",
"mock_api_client",
".",
"get",
"(",
"\"/\"",
",",
"headers",
"=",
"{",
"X_FORWARDED_FOR",
":",
"\"255.255.255.255\"",
"}",
")",
"assert",
"resp",
".",
"status",
"==",
"200"
] | [
85,
0
] | [
104,
29
] | python | en | ['en', 'en', 'en'] | True |
test_x_forwarded_for_with_spoofed_header | (aiohttp_client) | Test that we get the IP from the transport with a spoofed header. | Test that we get the IP from the transport with a spoofed header. | async def test_x_forwarded_for_with_spoofed_header(aiohttp_client):
"""Test that we get the IP from the transport with a spoofed header."""
async def handler(request):
url = mock_api_client.make_url("/")
assert request.host == f"{url.host}:{url.port}"
assert request.scheme == "http"
assert not request.secure
assert request.remote == "255.255.255.255"
return web.Response()
app = web.Application()
app.router.add_get("/", handler)
async_setup_forwarded(app, [ip_network("127.0.0.1")])
mock_api_client = await aiohttp_client(app)
resp = await mock_api_client.get(
"/", headers={X_FORWARDED_FOR: "222.222.222.222, 255.255.255.255"}
)
assert resp.status == 200 | [
"async",
"def",
"test_x_forwarded_for_with_spoofed_header",
"(",
"aiohttp_client",
")",
":",
"async",
"def",
"handler",
"(",
"request",
")",
":",
"url",
"=",
"mock_api_client",
".",
"make_url",
"(",
"\"/\"",
")",
"assert",
"request",
".",
"host",
"==",
"f\"{url.host}:{url.port}\"",
"assert",
"request",
".",
"scheme",
"==",
"\"http\"",
"assert",
"not",
"request",
".",
"secure",
"assert",
"request",
".",
"remote",
"==",
"\"255.255.255.255\"",
"return",
"web",
".",
"Response",
"(",
")",
"app",
"=",
"web",
".",
"Application",
"(",
")",
"app",
".",
"router",
".",
"add_get",
"(",
"\"/\"",
",",
"handler",
")",
"async_setup_forwarded",
"(",
"app",
",",
"[",
"ip_network",
"(",
"\"127.0.0.1\"",
")",
"]",
")",
"mock_api_client",
"=",
"await",
"aiohttp_client",
"(",
"app",
")",
"resp",
"=",
"await",
"mock_api_client",
".",
"get",
"(",
"\"/\"",
",",
"headers",
"=",
"{",
"X_FORWARDED_FOR",
":",
"\"222.222.222.222, 255.255.255.255\"",
"}",
")",
"assert",
"resp",
".",
"status",
"==",
"200"
] | [
107,
0
] | [
128,
29
] | python | en | ['en', 'en', 'en'] | True |
test_x_forwarded_for_with_malformed_header | (
x_forwarded_for, aiohttp_client, caplog
) | Test that we get a HTTP 400 bad request with a malformed header. | Test that we get a HTTP 400 bad request with a malformed header. | async def test_x_forwarded_for_with_malformed_header(
x_forwarded_for, aiohttp_client, caplog
):
"""Test that we get a HTTP 400 bad request with a malformed header."""
app = web.Application()
app.router.add_get("/", mock_handler)
async_setup_forwarded(app, [ip_network("127.0.0.1")])
mock_api_client = await aiohttp_client(app)
resp = await mock_api_client.get("/", headers={X_FORWARDED_FOR: x_forwarded_for})
assert resp.status == 400
assert "Invalid IP address in X-Forwarded-For" in caplog.text | [
"async",
"def",
"test_x_forwarded_for_with_malformed_header",
"(",
"x_forwarded_for",
",",
"aiohttp_client",
",",
"caplog",
")",
":",
"app",
"=",
"web",
".",
"Application",
"(",
")",
"app",
".",
"router",
".",
"add_get",
"(",
"\"/\"",
",",
"mock_handler",
")",
"async_setup_forwarded",
"(",
"app",
",",
"[",
"ip_network",
"(",
"\"127.0.0.1\"",
")",
"]",
")",
"mock_api_client",
"=",
"await",
"aiohttp_client",
"(",
"app",
")",
"resp",
"=",
"await",
"mock_api_client",
".",
"get",
"(",
"\"/\"",
",",
"headers",
"=",
"{",
"X_FORWARDED_FOR",
":",
"x_forwarded_for",
"}",
")",
"assert",
"resp",
".",
"status",
"==",
"400",
"assert",
"\"Invalid IP address in X-Forwarded-For\"",
"in",
"caplog",
".",
"text"
] | [
144,
0
] | [
157,
65
] | python | en | ['en', 'en', 'en'] | True |
test_x_forwarded_for_with_multiple_headers | (aiohttp_client, caplog) | Test that we get a HTTP 400 bad request with multiple headers. | Test that we get a HTTP 400 bad request with multiple headers. | async def test_x_forwarded_for_with_multiple_headers(aiohttp_client, caplog):
"""Test that we get a HTTP 400 bad request with multiple headers."""
app = web.Application()
app.router.add_get("/", mock_handler)
async_setup_forwarded(app, [ip_network("127.0.0.1")])
mock_api_client = await aiohttp_client(app)
resp = await mock_api_client.get(
"/",
headers=[
(X_FORWARDED_FOR, "222.222.222.222"),
(X_FORWARDED_FOR, "123.123.123.123"),
],
)
assert resp.status == 400
assert "Too many headers for X-Forwarded-For" in caplog.text | [
"async",
"def",
"test_x_forwarded_for_with_multiple_headers",
"(",
"aiohttp_client",
",",
"caplog",
")",
":",
"app",
"=",
"web",
".",
"Application",
"(",
")",
"app",
".",
"router",
".",
"add_get",
"(",
"\"/\"",
",",
"mock_handler",
")",
"async_setup_forwarded",
"(",
"app",
",",
"[",
"ip_network",
"(",
"\"127.0.0.1\"",
")",
"]",
")",
"mock_api_client",
"=",
"await",
"aiohttp_client",
"(",
"app",
")",
"resp",
"=",
"await",
"mock_api_client",
".",
"get",
"(",
"\"/\"",
",",
"headers",
"=",
"[",
"(",
"X_FORWARDED_FOR",
",",
"\"222.222.222.222\"",
")",
",",
"(",
"X_FORWARDED_FOR",
",",
"\"123.123.123.123\"",
")",
",",
"]",
",",
")",
"assert",
"resp",
".",
"status",
"==",
"400",
"assert",
"\"Too many headers for X-Forwarded-For\"",
"in",
"caplog",
".",
"text"
] | [
160,
0
] | [
177,
64
] | python | en | ['en', 'en', 'en'] | True |
test_x_forwarded_proto_without_trusted_proxy | (aiohttp_client) | Test that proto header is ignored when untrusted. | Test that proto header is ignored when untrusted. | async def test_x_forwarded_proto_without_trusted_proxy(aiohttp_client):
"""Test that proto header is ignored when untrusted."""
async def handler(request):
url = mock_api_client.make_url("/")
assert request.host == f"{url.host}:{url.port}"
assert request.scheme == "http"
assert not request.secure
assert request.remote == "127.0.0.1"
return web.Response()
app = web.Application()
app.router.add_get("/", handler)
async_setup_forwarded(app, [])
mock_api_client = await aiohttp_client(app)
resp = await mock_api_client.get(
"/", headers={X_FORWARDED_FOR: "255.255.255.255", X_FORWARDED_PROTO: "https"}
)
assert resp.status == 200 | [
"async",
"def",
"test_x_forwarded_proto_without_trusted_proxy",
"(",
"aiohttp_client",
")",
":",
"async",
"def",
"handler",
"(",
"request",
")",
":",
"url",
"=",
"mock_api_client",
".",
"make_url",
"(",
"\"/\"",
")",
"assert",
"request",
".",
"host",
"==",
"f\"{url.host}:{url.port}\"",
"assert",
"request",
".",
"scheme",
"==",
"\"http\"",
"assert",
"not",
"request",
".",
"secure",
"assert",
"request",
".",
"remote",
"==",
"\"127.0.0.1\"",
"return",
"web",
".",
"Response",
"(",
")",
"app",
"=",
"web",
".",
"Application",
"(",
")",
"app",
".",
"router",
".",
"add_get",
"(",
"\"/\"",
",",
"handler",
")",
"async_setup_forwarded",
"(",
"app",
",",
"[",
"]",
")",
"mock_api_client",
"=",
"await",
"aiohttp_client",
"(",
"app",
")",
"resp",
"=",
"await",
"mock_api_client",
".",
"get",
"(",
"\"/\"",
",",
"headers",
"=",
"{",
"X_FORWARDED_FOR",
":",
"\"255.255.255.255\"",
",",
"X_FORWARDED_PROTO",
":",
"\"https\"",
"}",
")",
"assert",
"resp",
".",
"status",
"==",
"200"
] | [
180,
0
] | [
202,
29
] | python | en | ['en', 'en', 'en'] | True |
test_x_forwarded_proto_with_trusted_proxy | (
x_forwarded_for, remote, x_forwarded_proto, secure, aiohttp_client
) | Test that we get the proto header if proxy is trusted. | Test that we get the proto header if proxy is trusted. | async def test_x_forwarded_proto_with_trusted_proxy(
x_forwarded_for, remote, x_forwarded_proto, secure, aiohttp_client
):
"""Test that we get the proto header if proxy is trusted."""
async def handler(request):
assert request.remote == remote
assert request.scheme == ("https" if secure else "http")
assert request.secure == secure
return web.Response()
app = web.Application()
app.router.add_get("/", handler)
async_setup_forwarded(app, [ip_network("127.0.0.0/24")])
mock_api_client = await aiohttp_client(app)
resp = await mock_api_client.get(
"/",
headers={
X_FORWARDED_FOR: x_forwarded_for,
X_FORWARDED_PROTO: x_forwarded_proto,
},
)
assert resp.status == 200 | [
"async",
"def",
"test_x_forwarded_proto_with_trusted_proxy",
"(",
"x_forwarded_for",
",",
"remote",
",",
"x_forwarded_proto",
",",
"secure",
",",
"aiohttp_client",
")",
":",
"async",
"def",
"handler",
"(",
"request",
")",
":",
"assert",
"request",
".",
"remote",
"==",
"remote",
"assert",
"request",
".",
"scheme",
"==",
"(",
"\"https\"",
"if",
"secure",
"else",
"\"http\"",
")",
"assert",
"request",
".",
"secure",
"==",
"secure",
"return",
"web",
".",
"Response",
"(",
")",
"app",
"=",
"web",
".",
"Application",
"(",
")",
"app",
".",
"router",
".",
"add_get",
"(",
"\"/\"",
",",
"handler",
")",
"async_setup_forwarded",
"(",
"app",
",",
"[",
"ip_network",
"(",
"\"127.0.0.0/24\"",
")",
"]",
")",
"mock_api_client",
"=",
"await",
"aiohttp_client",
"(",
"app",
")",
"resp",
"=",
"await",
"mock_api_client",
".",
"get",
"(",
"\"/\"",
",",
"headers",
"=",
"{",
"X_FORWARDED_FOR",
":",
"x_forwarded_for",
",",
"X_FORWARDED_PROTO",
":",
"x_forwarded_proto",
",",
"}",
",",
")",
"assert",
"resp",
".",
"status",
"==",
"200"
] | [
233,
0
] | [
258,
29
] | python | en | ['en', 'en', 'en'] | True |
test_x_forwarded_proto_with_trusted_proxy_multiple_for | (aiohttp_client) | Test that we get the proto with 1 element in the proto, multiple in the for. | Test that we get the proto with 1 element in the proto, multiple in the for. | async def test_x_forwarded_proto_with_trusted_proxy_multiple_for(aiohttp_client):
"""Test that we get the proto with 1 element in the proto, multiple in the for."""
async def handler(request):
url = mock_api_client.make_url("/")
assert request.host == f"{url.host}:{url.port}"
assert request.scheme == "https"
assert request.secure
assert request.remote == "255.255.255.255"
return web.Response()
app = web.Application()
app.router.add_get("/", handler)
async_setup_forwarded(app, [ip_network("127.0.0.0/24")])
mock_api_client = await aiohttp_client(app)
resp = await mock_api_client.get(
"/",
headers={
X_FORWARDED_FOR: "255.255.255.255, 127.0.0.1, 127.0.0.2",
X_FORWARDED_PROTO: "https",
},
)
assert resp.status == 200 | [
"async",
"def",
"test_x_forwarded_proto_with_trusted_proxy_multiple_for",
"(",
"aiohttp_client",
")",
":",
"async",
"def",
"handler",
"(",
"request",
")",
":",
"url",
"=",
"mock_api_client",
".",
"make_url",
"(",
"\"/\"",
")",
"assert",
"request",
".",
"host",
"==",
"f\"{url.host}:{url.port}\"",
"assert",
"request",
".",
"scheme",
"==",
"\"https\"",
"assert",
"request",
".",
"secure",
"assert",
"request",
".",
"remote",
"==",
"\"255.255.255.255\"",
"return",
"web",
".",
"Response",
"(",
")",
"app",
"=",
"web",
".",
"Application",
"(",
")",
"app",
".",
"router",
".",
"add_get",
"(",
"\"/\"",
",",
"handler",
")",
"async_setup_forwarded",
"(",
"app",
",",
"[",
"ip_network",
"(",
"\"127.0.0.0/24\"",
")",
"]",
")",
"mock_api_client",
"=",
"await",
"aiohttp_client",
"(",
"app",
")",
"resp",
"=",
"await",
"mock_api_client",
".",
"get",
"(",
"\"/\"",
",",
"headers",
"=",
"{",
"X_FORWARDED_FOR",
":",
"\"255.255.255.255, 127.0.0.1, 127.0.0.2\"",
",",
"X_FORWARDED_PROTO",
":",
"\"https\"",
",",
"}",
",",
")",
"assert",
"resp",
".",
"status",
"==",
"200"
] | [
261,
0
] | [
286,
29
] | python | en | ['en', 'en', 'en'] | True |
test_x_forwarded_proto_not_processed_without_for | (aiohttp_client) | Test that proto header isn't processed without a for header. | Test that proto header isn't processed without a for header. | async def test_x_forwarded_proto_not_processed_without_for(aiohttp_client):
"""Test that proto header isn't processed without a for header."""
async def handler(request):
url = mock_api_client.make_url("/")
assert request.host == f"{url.host}:{url.port}"
assert request.scheme == "http"
assert not request.secure
assert request.remote == "127.0.0.1"
return web.Response()
app = web.Application()
app.router.add_get("/", handler)
async_setup_forwarded(app, [ip_network("127.0.0.1")])
mock_api_client = await aiohttp_client(app)
resp = await mock_api_client.get("/", headers={X_FORWARDED_PROTO: "https"})
assert resp.status == 200 | [
"async",
"def",
"test_x_forwarded_proto_not_processed_without_for",
"(",
"aiohttp_client",
")",
":",
"async",
"def",
"handler",
"(",
"request",
")",
":",
"url",
"=",
"mock_api_client",
".",
"make_url",
"(",
"\"/\"",
")",
"assert",
"request",
".",
"host",
"==",
"f\"{url.host}:{url.port}\"",
"assert",
"request",
".",
"scheme",
"==",
"\"http\"",
"assert",
"not",
"request",
".",
"secure",
"assert",
"request",
".",
"remote",
"==",
"\"127.0.0.1\"",
"return",
"web",
".",
"Response",
"(",
")",
"app",
"=",
"web",
".",
"Application",
"(",
")",
"app",
".",
"router",
".",
"add_get",
"(",
"\"/\"",
",",
"handler",
")",
"async_setup_forwarded",
"(",
"app",
",",
"[",
"ip_network",
"(",
"\"127.0.0.1\"",
")",
"]",
")",
"mock_api_client",
"=",
"await",
"aiohttp_client",
"(",
"app",
")",
"resp",
"=",
"await",
"mock_api_client",
".",
"get",
"(",
"\"/\"",
",",
"headers",
"=",
"{",
"X_FORWARDED_PROTO",
":",
"\"https\"",
"}",
")",
"assert",
"resp",
".",
"status",
"==",
"200"
] | [
289,
0
] | [
308,
29
] | python | en | ['en', 'en', 'en'] | True |
test_x_forwarded_proto_with_multiple_headers | (aiohttp_client, caplog) | Test that we get a HTTP 400 bad request with multiple headers. | Test that we get a HTTP 400 bad request with multiple headers. | async def test_x_forwarded_proto_with_multiple_headers(aiohttp_client, caplog):
"""Test that we get a HTTP 400 bad request with multiple headers."""
app = web.Application()
app.router.add_get("/", mock_handler)
async_setup_forwarded(app, [ip_network("127.0.0.1")])
mock_api_client = await aiohttp_client(app)
resp = await mock_api_client.get(
"/",
headers=[
(X_FORWARDED_FOR, "222.222.222.222"),
(X_FORWARDED_PROTO, "https"),
(X_FORWARDED_PROTO, "http"),
],
)
assert resp.status == 400
assert "Too many headers for X-Forward-Proto" in caplog.text | [
"async",
"def",
"test_x_forwarded_proto_with_multiple_headers",
"(",
"aiohttp_client",
",",
"caplog",
")",
":",
"app",
"=",
"web",
".",
"Application",
"(",
")",
"app",
".",
"router",
".",
"add_get",
"(",
"\"/\"",
",",
"mock_handler",
")",
"async_setup_forwarded",
"(",
"app",
",",
"[",
"ip_network",
"(",
"\"127.0.0.1\"",
")",
"]",
")",
"mock_api_client",
"=",
"await",
"aiohttp_client",
"(",
"app",
")",
"resp",
"=",
"await",
"mock_api_client",
".",
"get",
"(",
"\"/\"",
",",
"headers",
"=",
"[",
"(",
"X_FORWARDED_FOR",
",",
"\"222.222.222.222\"",
")",
",",
"(",
"X_FORWARDED_PROTO",
",",
"\"https\"",
")",
",",
"(",
"X_FORWARDED_PROTO",
",",
"\"http\"",
")",
",",
"]",
",",
")",
"assert",
"resp",
".",
"status",
"==",
"400",
"assert",
"\"Too many headers for X-Forward-Proto\"",
"in",
"caplog",
".",
"text"
] | [
311,
0
] | [
328,
64
] | python | en | ['en', 'en', 'en'] | True |
test_x_forwarded_proto_empty_element | (
x_forwarded_proto, aiohttp_client, caplog
) | Test that we get a HTTP 400 bad request with empty proto. | Test that we get a HTTP 400 bad request with empty proto. | async def test_x_forwarded_proto_empty_element(
x_forwarded_proto, aiohttp_client, caplog
):
"""Test that we get a HTTP 400 bad request with empty proto."""
app = web.Application()
app.router.add_get("/", mock_handler)
async_setup_forwarded(app, [ip_network("127.0.0.1")])
mock_api_client = await aiohttp_client(app)
resp = await mock_api_client.get(
"/",
headers={X_FORWARDED_FOR: "1.1.1.1", X_FORWARDED_PROTO: x_forwarded_proto},
)
assert resp.status == 400
assert "Empty item received in X-Forward-Proto header" in caplog.text | [
"async",
"def",
"test_x_forwarded_proto_empty_element",
"(",
"x_forwarded_proto",
",",
"aiohttp_client",
",",
"caplog",
")",
":",
"app",
"=",
"web",
".",
"Application",
"(",
")",
"app",
".",
"router",
".",
"add_get",
"(",
"\"/\"",
",",
"mock_handler",
")",
"async_setup_forwarded",
"(",
"app",
",",
"[",
"ip_network",
"(",
"\"127.0.0.1\"",
")",
"]",
")",
"mock_api_client",
"=",
"await",
"aiohttp_client",
"(",
"app",
")",
"resp",
"=",
"await",
"mock_api_client",
".",
"get",
"(",
"\"/\"",
",",
"headers",
"=",
"{",
"X_FORWARDED_FOR",
":",
"\"1.1.1.1\"",
",",
"X_FORWARDED_PROTO",
":",
"x_forwarded_proto",
"}",
",",
")",
"assert",
"resp",
".",
"status",
"==",
"400",
"assert",
"\"Empty item received in X-Forward-Proto header\"",
"in",
"caplog",
".",
"text"
] | [
335,
0
] | [
350,
73
] | python | en | ['en', 'en', 'en'] | True |
test_x_forwarded_proto_incorrect_number_of_elements | (
x_forwarded_for, x_forwarded_proto, expected, got, aiohttp_client, caplog
) | Test that we get a HTTP 400 bad request with incorrect number of elements. | Test that we get a HTTP 400 bad request with incorrect number of elements. | async def test_x_forwarded_proto_incorrect_number_of_elements(
x_forwarded_for, x_forwarded_proto, expected, got, aiohttp_client, caplog
):
"""Test that we get a HTTP 400 bad request with incorrect number of elements."""
app = web.Application()
app.router.add_get("/", mock_handler)
async_setup_forwarded(app, [ip_network("127.0.0.1")])
mock_api_client = await aiohttp_client(app)
resp = await mock_api_client.get(
"/",
headers={
X_FORWARDED_FOR: x_forwarded_for,
X_FORWARDED_PROTO: x_forwarded_proto,
},
)
assert resp.status == 400
assert (
f"Incorrect number of elements in X-Forward-Proto. Expected 1 or {expected}, got {got}"
in caplog.text
) | [
"async",
"def",
"test_x_forwarded_proto_incorrect_number_of_elements",
"(",
"x_forwarded_for",
",",
"x_forwarded_proto",
",",
"expected",
",",
"got",
",",
"aiohttp_client",
",",
"caplog",
")",
":",
"app",
"=",
"web",
".",
"Application",
"(",
")",
"app",
".",
"router",
".",
"add_get",
"(",
"\"/\"",
",",
"mock_handler",
")",
"async_setup_forwarded",
"(",
"app",
",",
"[",
"ip_network",
"(",
"\"127.0.0.1\"",
")",
"]",
")",
"mock_api_client",
"=",
"await",
"aiohttp_client",
"(",
"app",
")",
"resp",
"=",
"await",
"mock_api_client",
".",
"get",
"(",
"\"/\"",
",",
"headers",
"=",
"{",
"X_FORWARDED_FOR",
":",
"x_forwarded_for",
",",
"X_FORWARDED_PROTO",
":",
"x_forwarded_proto",
",",
"}",
",",
")",
"assert",
"resp",
".",
"status",
"==",
"400",
"assert",
"(",
"f\"Incorrect number of elements in X-Forward-Proto. Expected 1 or {expected}, got {got}\"",
"in",
"caplog",
".",
"text",
")"
] | [
360,
0
] | [
381,
5
] | python | en | ['en', 'en', 'en'] | True |
test_x_forwarded_host_without_trusted_proxy | (aiohttp_client) | Test that host header is ignored when untrusted. | Test that host header is ignored when untrusted. | async def test_x_forwarded_host_without_trusted_proxy(aiohttp_client):
"""Test that host header is ignored when untrusted."""
async def handler(request):
url = mock_api_client.make_url("/")
assert request.host == f"{url.host}:{url.port}"
assert request.scheme == "http"
assert not request.secure
assert request.remote == "127.0.0.1"
return web.Response()
app = web.Application()
app.router.add_get("/", handler)
async_setup_forwarded(app, [])
mock_api_client = await aiohttp_client(app)
resp = await mock_api_client.get(
"/",
headers={X_FORWARDED_FOR: "255.255.255.255", X_FORWARDED_HOST: "example.com"},
)
assert resp.status == 200 | [
"async",
"def",
"test_x_forwarded_host_without_trusted_proxy",
"(",
"aiohttp_client",
")",
":",
"async",
"def",
"handler",
"(",
"request",
")",
":",
"url",
"=",
"mock_api_client",
".",
"make_url",
"(",
"\"/\"",
")",
"assert",
"request",
".",
"host",
"==",
"f\"{url.host}:{url.port}\"",
"assert",
"request",
".",
"scheme",
"==",
"\"http\"",
"assert",
"not",
"request",
".",
"secure",
"assert",
"request",
".",
"remote",
"==",
"\"127.0.0.1\"",
"return",
"web",
".",
"Response",
"(",
")",
"app",
"=",
"web",
".",
"Application",
"(",
")",
"app",
".",
"router",
".",
"add_get",
"(",
"\"/\"",
",",
"handler",
")",
"async_setup_forwarded",
"(",
"app",
",",
"[",
"]",
")",
"mock_api_client",
"=",
"await",
"aiohttp_client",
"(",
"app",
")",
"resp",
"=",
"await",
"mock_api_client",
".",
"get",
"(",
"\"/\"",
",",
"headers",
"=",
"{",
"X_FORWARDED_FOR",
":",
"\"255.255.255.255\"",
",",
"X_FORWARDED_HOST",
":",
"\"example.com\"",
"}",
",",
")",
"assert",
"resp",
".",
"status",
"==",
"200"
] | [
384,
0
] | [
407,
29
] | python | en | ['en', 'en', 'en'] | True |
test_x_forwarded_host_with_trusted_proxy | (aiohttp_client) | Test that we get the host header if proxy is trusted. | Test that we get the host header if proxy is trusted. | async def test_x_forwarded_host_with_trusted_proxy(aiohttp_client):
"""Test that we get the host header if proxy is trusted."""
async def handler(request):
assert request.host == "example.com"
assert request.scheme == "http"
assert not request.secure
assert request.remote == "255.255.255.255"
return web.Response()
app = web.Application()
app.router.add_get("/", handler)
async_setup_forwarded(app, [ip_network("127.0.0.1")])
mock_api_client = await aiohttp_client(app)
resp = await mock_api_client.get(
"/",
headers={X_FORWARDED_FOR: "255.255.255.255", X_FORWARDED_HOST: "example.com"},
)
assert resp.status == 200 | [
"async",
"def",
"test_x_forwarded_host_with_trusted_proxy",
"(",
"aiohttp_client",
")",
":",
"async",
"def",
"handler",
"(",
"request",
")",
":",
"assert",
"request",
".",
"host",
"==",
"\"example.com\"",
"assert",
"request",
".",
"scheme",
"==",
"\"http\"",
"assert",
"not",
"request",
".",
"secure",
"assert",
"request",
".",
"remote",
"==",
"\"255.255.255.255\"",
"return",
"web",
".",
"Response",
"(",
")",
"app",
"=",
"web",
".",
"Application",
"(",
")",
"app",
".",
"router",
".",
"add_get",
"(",
"\"/\"",
",",
"handler",
")",
"async_setup_forwarded",
"(",
"app",
",",
"[",
"ip_network",
"(",
"\"127.0.0.1\"",
")",
"]",
")",
"mock_api_client",
"=",
"await",
"aiohttp_client",
"(",
"app",
")",
"resp",
"=",
"await",
"mock_api_client",
".",
"get",
"(",
"\"/\"",
",",
"headers",
"=",
"{",
"X_FORWARDED_FOR",
":",
"\"255.255.255.255\"",
",",
"X_FORWARDED_HOST",
":",
"\"example.com\"",
"}",
",",
")",
"assert",
"resp",
".",
"status",
"==",
"200"
] | [
410,
0
] | [
431,
29
] | python | en | ['en', 'en', 'en'] | True |
test_x_forwarded_host_not_processed_without_for | (aiohttp_client) | Test that host header isn't processed without a for header. | Test that host header isn't processed without a for header. | async def test_x_forwarded_host_not_processed_without_for(aiohttp_client):
"""Test that host header isn't processed without a for header."""
async def handler(request):
url = mock_api_client.make_url("/")
assert request.host == f"{url.host}:{url.port}"
assert request.scheme == "http"
assert not request.secure
assert request.remote == "127.0.0.1"
return web.Response()
app = web.Application()
app.router.add_get("/", handler)
async_setup_forwarded(app, [ip_network("127.0.0.1")])
mock_api_client = await aiohttp_client(app)
resp = await mock_api_client.get("/", headers={X_FORWARDED_HOST: "example.com"})
assert resp.status == 200 | [
"async",
"def",
"test_x_forwarded_host_not_processed_without_for",
"(",
"aiohttp_client",
")",
":",
"async",
"def",
"handler",
"(",
"request",
")",
":",
"url",
"=",
"mock_api_client",
".",
"make_url",
"(",
"\"/\"",
")",
"assert",
"request",
".",
"host",
"==",
"f\"{url.host}:{url.port}\"",
"assert",
"request",
".",
"scheme",
"==",
"\"http\"",
"assert",
"not",
"request",
".",
"secure",
"assert",
"request",
".",
"remote",
"==",
"\"127.0.0.1\"",
"return",
"web",
".",
"Response",
"(",
")",
"app",
"=",
"web",
".",
"Application",
"(",
")",
"app",
".",
"router",
".",
"add_get",
"(",
"\"/\"",
",",
"handler",
")",
"async_setup_forwarded",
"(",
"app",
",",
"[",
"ip_network",
"(",
"\"127.0.0.1\"",
")",
"]",
")",
"mock_api_client",
"=",
"await",
"aiohttp_client",
"(",
"app",
")",
"resp",
"=",
"await",
"mock_api_client",
".",
"get",
"(",
"\"/\"",
",",
"headers",
"=",
"{",
"X_FORWARDED_HOST",
":",
"\"example.com\"",
"}",
")",
"assert",
"resp",
".",
"status",
"==",
"200"
] | [
434,
0
] | [
453,
29
] | python | en | ['en', 'en', 'en'] | True |
test_x_forwarded_host_with_multiple_headers | (aiohttp_client, caplog) | Test that we get a HTTP 400 bad request with multiple headers. | Test that we get a HTTP 400 bad request with multiple headers. | async def test_x_forwarded_host_with_multiple_headers(aiohttp_client, caplog):
"""Test that we get a HTTP 400 bad request with multiple headers."""
app = web.Application()
app.router.add_get("/", mock_handler)
async_setup_forwarded(app, [ip_network("127.0.0.1")])
mock_api_client = await aiohttp_client(app)
resp = await mock_api_client.get(
"/",
headers=[
(X_FORWARDED_FOR, "222.222.222.222"),
(X_FORWARDED_HOST, "example.com"),
(X_FORWARDED_HOST, "example.spoof"),
],
)
assert resp.status == 400
assert "Too many headers for X-Forwarded-Host" in caplog.text | [
"async",
"def",
"test_x_forwarded_host_with_multiple_headers",
"(",
"aiohttp_client",
",",
"caplog",
")",
":",
"app",
"=",
"web",
".",
"Application",
"(",
")",
"app",
".",
"router",
".",
"add_get",
"(",
"\"/\"",
",",
"mock_handler",
")",
"async_setup_forwarded",
"(",
"app",
",",
"[",
"ip_network",
"(",
"\"127.0.0.1\"",
")",
"]",
")",
"mock_api_client",
"=",
"await",
"aiohttp_client",
"(",
"app",
")",
"resp",
"=",
"await",
"mock_api_client",
".",
"get",
"(",
"\"/\"",
",",
"headers",
"=",
"[",
"(",
"X_FORWARDED_FOR",
",",
"\"222.222.222.222\"",
")",
",",
"(",
"X_FORWARDED_HOST",
",",
"\"example.com\"",
")",
",",
"(",
"X_FORWARDED_HOST",
",",
"\"example.spoof\"",
")",
",",
"]",
",",
")",
"assert",
"resp",
".",
"status",
"==",
"400",
"assert",
"\"Too many headers for X-Forwarded-Host\"",
"in",
"caplog",
".",
"text"
] | [
456,
0
] | [
473,
65
] | python | en | ['en', 'en', 'en'] | True |
test_x_forwarded_host_with_empty_header | (aiohttp_client, caplog) | Test that we get a HTTP 400 bad request with empty host value. | Test that we get a HTTP 400 bad request with empty host value. | async def test_x_forwarded_host_with_empty_header(aiohttp_client, caplog):
"""Test that we get a HTTP 400 bad request with empty host value."""
app = web.Application()
app.router.add_get("/", mock_handler)
async_setup_forwarded(app, [ip_network("127.0.0.1")])
mock_api_client = await aiohttp_client(app)
resp = await mock_api_client.get(
"/", headers={X_FORWARDED_FOR: "222.222.222.222", X_FORWARDED_HOST: ""}
)
assert resp.status == 400
assert "Empty value received in X-Forward-Host header" in caplog.text | [
"async",
"def",
"test_x_forwarded_host_with_empty_header",
"(",
"aiohttp_client",
",",
"caplog",
")",
":",
"app",
"=",
"web",
".",
"Application",
"(",
")",
"app",
".",
"router",
".",
"add_get",
"(",
"\"/\"",
",",
"mock_handler",
")",
"async_setup_forwarded",
"(",
"app",
",",
"[",
"ip_network",
"(",
"\"127.0.0.1\"",
")",
"]",
")",
"mock_api_client",
"=",
"await",
"aiohttp_client",
"(",
"app",
")",
"resp",
"=",
"await",
"mock_api_client",
".",
"get",
"(",
"\"/\"",
",",
"headers",
"=",
"{",
"X_FORWARDED_FOR",
":",
"\"222.222.222.222\"",
",",
"X_FORWARDED_HOST",
":",
"\"\"",
"}",
")",
"assert",
"resp",
".",
"status",
"==",
"400",
"assert",
"\"Empty value received in X-Forward-Host header\"",
"in",
"caplog",
".",
"text"
] | [
476,
0
] | [
488,
73
] | python | en | ['en', 'en', 'en'] | True |
ZHAGroupMember.__init__ | (
self, zha_group: ZhaGroupType, zha_device: ZhaDeviceType, endpoint_id: int
) | Initialize the group member. | Initialize the group member. | def __init__(
self, zha_group: ZhaGroupType, zha_device: ZhaDeviceType, endpoint_id: int
):
"""Initialize the group member."""
self._zha_group: ZhaGroupType = zha_group
self._zha_device: ZhaDeviceType = zha_device
self._endpoint_id: int = endpoint_id | [
"def",
"__init__",
"(",
"self",
",",
"zha_group",
":",
"ZhaGroupType",
",",
"zha_device",
":",
"ZhaDeviceType",
",",
"endpoint_id",
":",
"int",
")",
":",
"self",
".",
"_zha_group",
":",
"ZhaGroupType",
"=",
"zha_group",
"self",
".",
"_zha_device",
":",
"ZhaDeviceType",
"=",
"zha_device",
"self",
".",
"_endpoint_id",
":",
"int",
"=",
"endpoint_id"
] | [
31,
4
] | [
37,
44
] | python | en | ['en', 'en', 'en'] | True |
ZHAGroupMember.group | (self) | Return the group this member belongs to. | Return the group this member belongs to. | def group(self) -> ZhaGroupType:
"""Return the group this member belongs to."""
return self._zha_group | [
"def",
"group",
"(",
"self",
")",
"->",
"ZhaGroupType",
":",
"return",
"self",
".",
"_zha_group"
] | [
40,
4
] | [
42,
30
] | python | en | ['en', 'af', 'en'] | True |
ZHAGroupMember.endpoint_id | (self) | Return the endpoint id for this group member. | Return the endpoint id for this group member. | def endpoint_id(self) -> int:
"""Return the endpoint id for this group member."""
return self._endpoint_id | [
"def",
"endpoint_id",
"(",
"self",
")",
"->",
"int",
":",
"return",
"self",
".",
"_endpoint_id"
] | [
45,
4
] | [
47,
32
] | python | en | ['en', 'en', 'en'] | True |
ZHAGroupMember.endpoint | (self) | Return the endpoint for this group member. | Return the endpoint for this group member. | def endpoint(self) -> ZigpyEndpointType:
"""Return the endpoint for this group member."""
return self._zha_device.device.endpoints.get(self.endpoint_id) | [
"def",
"endpoint",
"(",
"self",
")",
"->",
"ZigpyEndpointType",
":",
"return",
"self",
".",
"_zha_device",
".",
"device",
".",
"endpoints",
".",
"get",
"(",
"self",
".",
"endpoint_id",
")"
] | [
50,
4
] | [
52,
70
] | python | en | ['en', 'en', 'en'] | True |
ZHAGroupMember.device | (self) | Return the zha device for this group member. | Return the zha device for this group member. | def device(self) -> ZhaDeviceType:
"""Return the zha device for this group member."""
return self._zha_device | [
"def",
"device",
"(",
"self",
")",
"->",
"ZhaDeviceType",
":",
"return",
"self",
".",
"_zha_device"
] | [
55,
4
] | [
57,
31
] | python | en | ['en', 'en', 'en'] | True |
ZHAGroupMember.member_info | (self) | Get ZHA group info. | Get ZHA group info. | def member_info(self) -> Dict[str, Any]:
"""Get ZHA group info."""
member_info: Dict[str, Any] = {}
member_info["endpoint_id"] = self.endpoint_id
member_info["device"] = self.device.zha_device_info
member_info["entities"] = self.associated_entities
return member_info | [
"def",
"member_info",
"(",
"self",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"member_info",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
"=",
"{",
"}",
"member_info",
"[",
"\"endpoint_id\"",
"]",
"=",
"self",
".",
"endpoint_id",
"member_info",
"[",
"\"device\"",
"]",
"=",
"self",
".",
"device",
".",
"zha_device_info",
"member_info",
"[",
"\"entities\"",
"]",
"=",
"self",
".",
"associated_entities",
"return",
"member_info"
] | [
60,
4
] | [
66,
26
] | python | en | ['en', 'lb', 'en'] | True |
ZHAGroupMember.associated_entities | (self) | Return the list of entities that were derived from this endpoint. | Return the list of entities that were derived from this endpoint. | def associated_entities(self) -> List[GroupEntityReference]:
"""Return the list of entities that were derived from this endpoint."""
ha_entity_registry = self.device.gateway.ha_entity_registry
zha_device_registry = self.device.gateway.device_registry
return [
GroupEntityReference(
ha_entity_registry.async_get(entity_ref.reference_id).name,
ha_entity_registry.async_get(entity_ref.reference_id).original_name,
entity_ref.reference_id,
)._asdict()
for entity_ref in zha_device_registry.get(self.device.ieee)
if list(entity_ref.cluster_channels.values())[
0
].cluster.endpoint.endpoint_id
== self.endpoint_id
] | [
"def",
"associated_entities",
"(",
"self",
")",
"->",
"List",
"[",
"GroupEntityReference",
"]",
":",
"ha_entity_registry",
"=",
"self",
".",
"device",
".",
"gateway",
".",
"ha_entity_registry",
"zha_device_registry",
"=",
"self",
".",
"device",
".",
"gateway",
".",
"device_registry",
"return",
"[",
"GroupEntityReference",
"(",
"ha_entity_registry",
".",
"async_get",
"(",
"entity_ref",
".",
"reference_id",
")",
".",
"name",
",",
"ha_entity_registry",
".",
"async_get",
"(",
"entity_ref",
".",
"reference_id",
")",
".",
"original_name",
",",
"entity_ref",
".",
"reference_id",
",",
")",
".",
"_asdict",
"(",
")",
"for",
"entity_ref",
"in",
"zha_device_registry",
".",
"get",
"(",
"self",
".",
"device",
".",
"ieee",
")",
"if",
"list",
"(",
"entity_ref",
".",
"cluster_channels",
".",
"values",
"(",
")",
")",
"[",
"0",
"]",
".",
"cluster",
".",
"endpoint",
".",
"endpoint_id",
"==",
"self",
".",
"endpoint_id",
"]"
] | [
69,
4
] | [
84,
9
] | python | en | ['en', 'en', 'en'] | True |
ZHAGroupMember.async_remove_from_group | (self) | Remove the device endpoint from the provided zigbee group. | Remove the device endpoint from the provided zigbee group. | async def async_remove_from_group(self) -> None:
"""Remove the device endpoint from the provided zigbee group."""
try:
await self._zha_device.device.endpoints[
self._endpoint_id
].remove_from_group(self._zha_group.group_id)
except (zigpy.exceptions.ZigbeeException, asyncio.TimeoutError) as ex:
self.debug(
"Failed to remove endpoint: %s for device '%s' from group: 0x%04x ex: %s",
self._endpoint_id,
self._zha_device.ieee,
self._zha_group.group_id,
str(ex),
) | [
"async",
"def",
"async_remove_from_group",
"(",
"self",
")",
"->",
"None",
":",
"try",
":",
"await",
"self",
".",
"_zha_device",
".",
"device",
".",
"endpoints",
"[",
"self",
".",
"_endpoint_id",
"]",
".",
"remove_from_group",
"(",
"self",
".",
"_zha_group",
".",
"group_id",
")",
"except",
"(",
"zigpy",
".",
"exceptions",
".",
"ZigbeeException",
",",
"asyncio",
".",
"TimeoutError",
")",
"as",
"ex",
":",
"self",
".",
"debug",
"(",
"\"Failed to remove endpoint: %s for device '%s' from group: 0x%04x ex: %s\"",
",",
"self",
".",
"_endpoint_id",
",",
"self",
".",
"_zha_device",
".",
"ieee",
",",
"self",
".",
"_zha_group",
".",
"group_id",
",",
"str",
"(",
"ex",
")",
",",
")"
] | [
86,
4
] | [
99,
13
] | python | en | ['en', 'en', 'en'] | True |
ZHAGroupMember.log | (self, level: int, msg: str, *args) | Log a message. | Log a message. | def log(self, level: int, msg: str, *args) -> None:
"""Log a message."""
msg = f"[%s](%s): {msg}"
args = (f"0x{self._zha_group.group_id:04x}", self.endpoint_id) + args
_LOGGER.log(level, msg, *args) | [
"def",
"log",
"(",
"self",
",",
"level",
":",
"int",
",",
"msg",
":",
"str",
",",
"*",
"args",
")",
"->",
"None",
":",
"msg",
"=",
"f\"[%s](%s): {msg}\"",
"args",
"=",
"(",
"f\"0x{self._zha_group.group_id:04x}\"",
",",
"self",
".",
"endpoint_id",
")",
"+",
"args",
"_LOGGER",
".",
"log",
"(",
"level",
",",
"msg",
",",
"*",
"args",
")"
] | [
101,
4
] | [
105,
38
] | python | en | ['en', 'lb', 'en'] | True |
ZHAGroup.__init__ | (
self,
hass: HomeAssistantType,
zha_gateway: ZhaGatewayType,
zigpy_group: ZigpyGroupType,
) | Initialize the group. | Initialize the group. | def __init__(
self,
hass: HomeAssistantType,
zha_gateway: ZhaGatewayType,
zigpy_group: ZigpyGroupType,
):
"""Initialize the group."""
self.hass: HomeAssistantType = hass
self._zigpy_group: ZigpyGroupType = zigpy_group
self._zha_gateway: ZhaGatewayType = zha_gateway | [
"def",
"__init__",
"(",
"self",
",",
"hass",
":",
"HomeAssistantType",
",",
"zha_gateway",
":",
"ZhaGatewayType",
",",
"zigpy_group",
":",
"ZigpyGroupType",
",",
")",
":",
"self",
".",
"hass",
":",
"HomeAssistantType",
"=",
"hass",
"self",
".",
"_zigpy_group",
":",
"ZigpyGroupType",
"=",
"zigpy_group",
"self",
".",
"_zha_gateway",
":",
"ZhaGatewayType",
"=",
"zha_gateway"
] | [
111,
4
] | [
120,
55
] | python | en | ['en', 'en', 'en'] | True |
ZHAGroup.name | (self) | Return group name. | Return group name. | def name(self) -> str:
"""Return group name."""
return self._zigpy_group.name | [
"def",
"name",
"(",
"self",
")",
"->",
"str",
":",
"return",
"self",
".",
"_zigpy_group",
".",
"name"
] | [
123,
4
] | [
125,
37
] | python | de | ['de', 'ig', 'en'] | False |
ZHAGroup.group_id | (self) | Return group name. | Return group name. | def group_id(self) -> int:
"""Return group name."""
return self._zigpy_group.group_id | [
"def",
"group_id",
"(",
"self",
")",
"->",
"int",
":",
"return",
"self",
".",
"_zigpy_group",
".",
"group_id"
] | [
128,
4
] | [
130,
41
] | python | de | ['de', 'ig', 'en'] | False |
ZHAGroup.endpoint | (self) | Return the endpoint for this group. | Return the endpoint for this group. | def endpoint(self) -> ZigpyEndpointType:
"""Return the endpoint for this group."""
return self._zigpy_group.endpoint | [
"def",
"endpoint",
"(",
"self",
")",
"->",
"ZigpyEndpointType",
":",
"return",
"self",
".",
"_zigpy_group",
".",
"endpoint"
] | [
133,
4
] | [
135,
41
] | python | en | ['en', 'en', 'en'] | True |
ZHAGroup.members | (self) | Return the ZHA devices that are members of this group. | Return the ZHA devices that are members of this group. | def members(self) -> List[ZHAGroupMember]:
"""Return the ZHA devices that are members of this group."""
return [
ZHAGroupMember(
self, self._zha_gateway.devices.get(member_ieee), endpoint_id
)
for (member_ieee, endpoint_id) in self._zigpy_group.members.keys()
if member_ieee in self._zha_gateway.devices
] | [
"def",
"members",
"(",
"self",
")",
"->",
"List",
"[",
"ZHAGroupMember",
"]",
":",
"return",
"[",
"ZHAGroupMember",
"(",
"self",
",",
"self",
".",
"_zha_gateway",
".",
"devices",
".",
"get",
"(",
"member_ieee",
")",
",",
"endpoint_id",
")",
"for",
"(",
"member_ieee",
",",
"endpoint_id",
")",
"in",
"self",
".",
"_zigpy_group",
".",
"members",
".",
"keys",
"(",
")",
"if",
"member_ieee",
"in",
"self",
".",
"_zha_gateway",
".",
"devices",
"]"
] | [
138,
4
] | [
146,
9
] | python | en | ['en', 'en', 'en'] | True |
ZHAGroup.async_add_members | (self, members: List[GroupMember]) | Add members to this group. | Add members to this group. | async def async_add_members(self, members: List[GroupMember]) -> None:
"""Add members to this group."""
if len(members) > 1:
tasks = []
for member in members:
tasks.append(
self._zha_gateway.devices[member.ieee].async_add_endpoint_to_group(
member.endpoint_id, self.group_id
)
)
await asyncio.gather(*tasks)
else:
await self._zha_gateway.devices[
members[0].ieee
].async_add_endpoint_to_group(members[0].endpoint_id, self.group_id) | [
"async",
"def",
"async_add_members",
"(",
"self",
",",
"members",
":",
"List",
"[",
"GroupMember",
"]",
")",
"->",
"None",
":",
"if",
"len",
"(",
"members",
")",
">",
"1",
":",
"tasks",
"=",
"[",
"]",
"for",
"member",
"in",
"members",
":",
"tasks",
".",
"append",
"(",
"self",
".",
"_zha_gateway",
".",
"devices",
"[",
"member",
".",
"ieee",
"]",
".",
"async_add_endpoint_to_group",
"(",
"member",
".",
"endpoint_id",
",",
"self",
".",
"group_id",
")",
")",
"await",
"asyncio",
".",
"gather",
"(",
"*",
"tasks",
")",
"else",
":",
"await",
"self",
".",
"_zha_gateway",
".",
"devices",
"[",
"members",
"[",
"0",
"]",
".",
"ieee",
"]",
".",
"async_add_endpoint_to_group",
"(",
"members",
"[",
"0",
"]",
".",
"endpoint_id",
",",
"self",
".",
"group_id",
")"
] | [
148,
4
] | [
162,
80
] | python | en | ['en', 'en', 'en'] | True |
ZHAGroup.async_remove_members | (self, members: List[GroupMember]) | Remove members from this group. | Remove members from this group. | async def async_remove_members(self, members: List[GroupMember]) -> None:
"""Remove members from this group."""
if len(members) > 1:
tasks = []
for member in members:
tasks.append(
self._zha_gateway.devices[
member.ieee
].async_remove_endpoint_from_group(
member.endpoint_id, self.group_id
)
)
await asyncio.gather(*tasks)
else:
await self._zha_gateway.devices[
members[0].ieee
].async_remove_endpoint_from_group(members[0].endpoint_id, self.group_id) | [
"async",
"def",
"async_remove_members",
"(",
"self",
",",
"members",
":",
"List",
"[",
"GroupMember",
"]",
")",
"->",
"None",
":",
"if",
"len",
"(",
"members",
")",
">",
"1",
":",
"tasks",
"=",
"[",
"]",
"for",
"member",
"in",
"members",
":",
"tasks",
".",
"append",
"(",
"self",
".",
"_zha_gateway",
".",
"devices",
"[",
"member",
".",
"ieee",
"]",
".",
"async_remove_endpoint_from_group",
"(",
"member",
".",
"endpoint_id",
",",
"self",
".",
"group_id",
")",
")",
"await",
"asyncio",
".",
"gather",
"(",
"*",
"tasks",
")",
"else",
":",
"await",
"self",
".",
"_zha_gateway",
".",
"devices",
"[",
"members",
"[",
"0",
"]",
".",
"ieee",
"]",
".",
"async_remove_endpoint_from_group",
"(",
"members",
"[",
"0",
"]",
".",
"endpoint_id",
",",
"self",
".",
"group_id",
")"
] | [
164,
4
] | [
180,
85
] | python | en | ['en', 'en', 'en'] | True |
ZHAGroup.member_entity_ids | (self) | Return the ZHA entity ids for all entities for the members of this group. | Return the ZHA entity ids for all entities for the members of this group. | def member_entity_ids(self) -> List[str]:
"""Return the ZHA entity ids for all entities for the members of this group."""
all_entity_ids: List[str] = []
for member in self.members:
entity_references = member.associated_entities
for entity_reference in entity_references:
all_entity_ids.append(entity_reference["entity_id"])
return all_entity_ids | [
"def",
"member_entity_ids",
"(",
"self",
")",
"->",
"List",
"[",
"str",
"]",
":",
"all_entity_ids",
":",
"List",
"[",
"str",
"]",
"=",
"[",
"]",
"for",
"member",
"in",
"self",
".",
"members",
":",
"entity_references",
"=",
"member",
".",
"associated_entities",
"for",
"entity_reference",
"in",
"entity_references",
":",
"all_entity_ids",
".",
"append",
"(",
"entity_reference",
"[",
"\"entity_id\"",
"]",
")",
"return",
"all_entity_ids"
] | [
183,
4
] | [
190,
29
] | python | en | ['en', 'en', 'en'] | True |
ZHAGroup.get_domain_entity_ids | (self, domain) | Return entity ids from the entity domain for this group. | Return entity ids from the entity domain for this group. | def get_domain_entity_ids(self, domain) -> List[str]:
"""Return entity ids from the entity domain for this group."""
domain_entity_ids: List[str] = []
for member in self.members:
entities = async_entries_for_device(
self._zha_gateway.ha_entity_registry, member.device.device_id
)
domain_entity_ids.extend(
[entity.entity_id for entity in entities if entity.domain == domain]
)
return domain_entity_ids | [
"def",
"get_domain_entity_ids",
"(",
"self",
",",
"domain",
")",
"->",
"List",
"[",
"str",
"]",
":",
"domain_entity_ids",
":",
"List",
"[",
"str",
"]",
"=",
"[",
"]",
"for",
"member",
"in",
"self",
".",
"members",
":",
"entities",
"=",
"async_entries_for_device",
"(",
"self",
".",
"_zha_gateway",
".",
"ha_entity_registry",
",",
"member",
".",
"device",
".",
"device_id",
")",
"domain_entity_ids",
".",
"extend",
"(",
"[",
"entity",
".",
"entity_id",
"for",
"entity",
"in",
"entities",
"if",
"entity",
".",
"domain",
"==",
"domain",
"]",
")",
"return",
"domain_entity_ids"
] | [
192,
4
] | [
202,
32
] | python | en | ['en', 'en', 'en'] | True |
ZHAGroup.group_info | (self) | Get ZHA group info. | Get ZHA group info. | def group_info(self) -> Dict[str, Any]:
"""Get ZHA group info."""
group_info: Dict[str, Any] = {}
group_info["group_id"] = self.group_id
group_info["name"] = self.name
group_info["members"] = [member.member_info for member in self.members]
return group_info | [
"def",
"group_info",
"(",
"self",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"group_info",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
"=",
"{",
"}",
"group_info",
"[",
"\"group_id\"",
"]",
"=",
"self",
".",
"group_id",
"group_info",
"[",
"\"name\"",
"]",
"=",
"self",
".",
"name",
"group_info",
"[",
"\"members\"",
"]",
"=",
"[",
"member",
".",
"member_info",
"for",
"member",
"in",
"self",
".",
"members",
"]",
"return",
"group_info"
] | [
205,
4
] | [
211,
25
] | python | en | ['en', 'lb', 'en'] | True |
ZHAGroup.log | (self, level: int, msg: str, *args) | Log a message. | Log a message. | def log(self, level: int, msg: str, *args):
"""Log a message."""
msg = f"[%s](%s): {msg}"
args = (self.name, self.group_id) + args
_LOGGER.log(level, msg, *args) | [
"def",
"log",
"(",
"self",
",",
"level",
":",
"int",
",",
"msg",
":",
"str",
",",
"*",
"args",
")",
":",
"msg",
"=",
"f\"[%s](%s): {msg}\"",
"args",
"=",
"(",
"self",
".",
"name",
",",
"self",
".",
"group_id",
")",
"+",
"args",
"_LOGGER",
".",
"log",
"(",
"level",
",",
"msg",
",",
"*",
"args",
")"
] | [
213,
4
] | [
217,
38
] | python | en | ['en', 'lb', 'en'] | True |
AlexaError.__init__ | (self, error_message, payload=None) | Initialize an alexa error. | Initialize an alexa error. | def __init__(self, error_message, payload=None):
"""Initialize an alexa error."""
Exception.__init__(self)
self.error_message = error_message
self.payload = None | [
"def",
"__init__",
"(",
"self",
",",
"error_message",
",",
"payload",
"=",
"None",
")",
":",
"Exception",
".",
"__init__",
"(",
"self",
")",
"self",
".",
"error_message",
"=",
"error_message",
"self",
".",
"payload",
"=",
"None"
] | [
27,
4
] | [
31,
27
] | python | eu | ['eu', 'eu', 'it'] | True |
AlexaInvalidEndpointError.__init__ | (self, endpoint_id) | Initialize invalid endpoint error. | Initialize invalid endpoint error. | def __init__(self, endpoint_id):
"""Initialize invalid endpoint error."""
msg = f"The endpoint {endpoint_id} does not exist"
AlexaError.__init__(self, msg)
self.endpoint_id = endpoint_id | [
"def",
"__init__",
"(",
"self",
",",
"endpoint_id",
")",
":",
"msg",
"=",
"f\"The endpoint {endpoint_id} does not exist\"",
"AlexaError",
".",
"__init__",
"(",
"self",
",",
"msg",
")",
"self",
".",
"endpoint_id",
"=",
"endpoint_id"
] | [
40,
4
] | [
44,
38
] | python | en | ['no', 'en', 'en'] | True |
AlexaTempRangeError.__init__ | (self, hass, temp, min_temp, max_temp) | Initialize TempRange error. | Initialize TempRange error. | def __init__(self, hass, temp, min_temp, max_temp):
"""Initialize TempRange error."""
unit = hass.config.units.temperature_unit
temp_range = {
"minimumValue": {"value": min_temp, "scale": API_TEMP_UNITS[unit]},
"maximumValue": {"value": max_temp, "scale": API_TEMP_UNITS[unit]},
}
payload = {"validRange": temp_range}
msg = f"The requested temperature {temp} is out of range"
AlexaError.__init__(self, msg, payload) | [
"def",
"__init__",
"(",
"self",
",",
"hass",
",",
"temp",
",",
"min_temp",
",",
"max_temp",
")",
":",
"unit",
"=",
"hass",
".",
"config",
".",
"units",
".",
"temperature_unit",
"temp_range",
"=",
"{",
"\"minimumValue\"",
":",
"{",
"\"value\"",
":",
"min_temp",
",",
"\"scale\"",
":",
"API_TEMP_UNITS",
"[",
"unit",
"]",
"}",
",",
"\"maximumValue\"",
":",
"{",
"\"value\"",
":",
"max_temp",
",",
"\"scale\"",
":",
"API_TEMP_UNITS",
"[",
"unit",
"]",
"}",
",",
"}",
"payload",
"=",
"{",
"\"validRange\"",
":",
"temp_range",
"}",
"msg",
"=",
"f\"The requested temperature {temp} is out of range\"",
"AlexaError",
".",
"__init__",
"(",
"self",
",",
"msg",
",",
"payload",
")"
] | [
67,
4
] | [
77,
47
] | python | da | ['da', 'la', 'it'] | False |
KnxEntity.__init__ | (self, device: XknxDevice) | Set up device. | Set up device. | def __init__(self, device: XknxDevice):
"""Set up device."""
self._device = device | [
"def",
"__init__",
"(",
"self",
",",
"device",
":",
"XknxDevice",
")",
":",
"self",
".",
"_device",
"=",
"device"
] | [
11,
4
] | [
13,
29
] | python | cs | ['nl', 'cs', 'en'] | False |
KnxEntity.name | (self) | Return the name of the KNX device. | Return the name of the KNX device. | def name(self):
"""Return the name of the KNX device."""
return self._device.name | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"self",
".",
"_device",
".",
"name"
] | [
16,
4
] | [
18,
32
] | python | en | ['en', 'en', 'en'] | True |
KnxEntity.available | (self) | Return True if entity is available. | Return True if entity is available. | def available(self):
"""Return True if entity is available."""
return self.hass.data[DOMAIN].connected | [
"def",
"available",
"(",
"self",
")",
":",
"return",
"self",
".",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
".",
"connected"
] | [
21,
4
] | [
23,
47
] | python | en | ['en', 'en', 'en'] | True |
KnxEntity.should_poll | (self) | No polling needed within KNX. | No polling needed within KNX. | def should_poll(self):
"""No polling needed within KNX."""
return False | [
"def",
"should_poll",
"(",
"self",
")",
":",
"return",
"False"
] | [
26,
4
] | [
28,
20
] | python | en | ['en', 'en', 'en'] | True |
KnxEntity.async_update | (self) | Request a state update from KNX bus. | Request a state update from KNX bus. | async def async_update(self):
"""Request a state update from KNX bus."""
await self._device.sync() | [
"async",
"def",
"async_update",
"(",
"self",
")",
":",
"await",
"self",
".",
"_device",
".",
"sync",
"(",
")"
] | [
30,
4
] | [
32,
33
] | python | en | ['en', 'en', 'en'] | True |
KnxEntity.after_update_callback | (self, device: XknxDevice) | Call after device was updated. | Call after device was updated. | async def after_update_callback(self, device: XknxDevice):
"""Call after device was updated."""
self.async_write_ha_state() | [
"async",
"def",
"after_update_callback",
"(",
"self",
",",
"device",
":",
"XknxDevice",
")",
":",
"self",
".",
"async_write_ha_state",
"(",
")"
] | [
34,
4
] | [
36,
35
] | python | en | ['en', 'en', 'en'] | True |
KnxEntity.async_added_to_hass | (self) | Store register state change callback. | Store register state change callback. | async def async_added_to_hass(self) -> None:
"""Store register state change callback."""
self._device.register_device_updated_cb(self.after_update_callback)
if isinstance(self._device, XknxClimate):
self._device.mode.register_device_updated_cb(self.after_update_callback) | [
"async",
"def",
"async_added_to_hass",
"(",
"self",
")",
"->",
"None",
":",
"self",
".",
"_device",
".",
"register_device_updated_cb",
"(",
"self",
".",
"after_update_callback",
")",
"if",
"isinstance",
"(",
"self",
".",
"_device",
",",
"XknxClimate",
")",
":",
"self",
".",
"_device",
".",
"mode",
".",
"register_device_updated_cb",
"(",
"self",
".",
"after_update_callback",
")"
] | [
38,
4
] | [
43,
84
] | python | en | ['en', 'no', 'en'] | True |
KnxEntity.async_will_remove_from_hass | (self) | Disconnect device object when removed. | Disconnect device object when removed. | async def async_will_remove_from_hass(self) -> None:
"""Disconnect device object when removed."""
self._device.unregister_device_updated_cb(self.after_update_callback)
if isinstance(self._device, XknxClimate):
self._device.mode.unregister_device_updated_cb(self.after_update_callback) | [
"async",
"def",
"async_will_remove_from_hass",
"(",
"self",
")",
"->",
"None",
":",
"self",
".",
"_device",
".",
"unregister_device_updated_cb",
"(",
"self",
".",
"after_update_callback",
")",
"if",
"isinstance",
"(",
"self",
".",
"_device",
",",
"XknxClimate",
")",
":",
"self",
".",
"_device",
".",
"mode",
".",
"unregister_device_updated_cb",
"(",
"self",
".",
"after_update_callback",
")"
] | [
45,
4
] | [
50,
86
] | python | en | ['en', 'en', 'en'] | True |
async_setup | (hass: HomeAssistant, config: dict) | Set up the Notion component. | Set up the Notion component. | async def async_setup(hass: HomeAssistant, config: dict) -> bool:
"""Set up the Notion component."""
hass.data[DOMAIN] = {DATA_COORDINATOR: {}}
return True | [
"async",
"def",
"async_setup",
"(",
"hass",
":",
"HomeAssistant",
",",
"config",
":",
"dict",
")",
"->",
"bool",
":",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"=",
"{",
"DATA_COORDINATOR",
":",
"{",
"}",
"}",
"return",
"True"
] | [
38,
0
] | [
41,
15
] | python | en | ['en', 'en', 'en'] | True |
async_setup_entry | (hass: HomeAssistant, entry: ConfigEntry) | Set up Notion as a config entry. | Set up Notion as a config entry. | async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up Notion as a config entry."""
if not entry.unique_id:
hass.config_entries.async_update_entry(
entry, unique_id=entry.data[CONF_USERNAME]
)
session = aiohttp_client.async_get_clientsession(hass)
try:
client = await async_get_client(
entry.data[CONF_USERNAME], entry.data[CONF_PASSWORD], session
)
except InvalidCredentialsError:
_LOGGER.error("Invalid username and/or password")
return False
except NotionError as err:
_LOGGER.error("Config entry failed: %s", err)
raise ConfigEntryNotReady from err
async def async_update():
"""Get the latest data from the Notion API."""
data = {"bridges": {}, "sensors": {}, "tasks": {}}
tasks = {
"bridges": client.bridge.async_all(),
"sensors": client.sensor.async_all(),
"tasks": client.task.async_all(),
}
results = await asyncio.gather(*tasks.values(), return_exceptions=True)
for attr, result in zip(tasks, results):
if isinstance(result, NotionError):
raise UpdateFailed(
f"There was a Notion error while updating {attr}: {result}"
)
if isinstance(result, Exception):
raise UpdateFailed(
f"There was an unknown error while updating {attr}: {result}"
)
for item in result:
if attr == "bridges" and item["id"] not in data["bridges"]:
# If a new bridge is discovered, register it:
hass.async_create_task(async_register_new_bridge(hass, item, entry))
data[attr][item["id"]] = item
return data
coordinator = hass.data[DOMAIN][DATA_COORDINATOR][
entry.entry_id
] = DataUpdateCoordinator(
hass,
_LOGGER,
name=entry.data[CONF_USERNAME],
update_interval=DEFAULT_SCAN_INTERVAL,
update_method=async_update,
)
await coordinator.async_refresh()
for platform in PLATFORMS:
hass.async_create_task(
hass.config_entries.async_forward_entry_setup(entry, platform)
)
return True | [
"async",
"def",
"async_setup_entry",
"(",
"hass",
":",
"HomeAssistant",
",",
"entry",
":",
"ConfigEntry",
")",
"->",
"bool",
":",
"if",
"not",
"entry",
".",
"unique_id",
":",
"hass",
".",
"config_entries",
".",
"async_update_entry",
"(",
"entry",
",",
"unique_id",
"=",
"entry",
".",
"data",
"[",
"CONF_USERNAME",
"]",
")",
"session",
"=",
"aiohttp_client",
".",
"async_get_clientsession",
"(",
"hass",
")",
"try",
":",
"client",
"=",
"await",
"async_get_client",
"(",
"entry",
".",
"data",
"[",
"CONF_USERNAME",
"]",
",",
"entry",
".",
"data",
"[",
"CONF_PASSWORD",
"]",
",",
"session",
")",
"except",
"InvalidCredentialsError",
":",
"_LOGGER",
".",
"error",
"(",
"\"Invalid username and/or password\"",
")",
"return",
"False",
"except",
"NotionError",
"as",
"err",
":",
"_LOGGER",
".",
"error",
"(",
"\"Config entry failed: %s\"",
",",
"err",
")",
"raise",
"ConfigEntryNotReady",
"from",
"err",
"async",
"def",
"async_update",
"(",
")",
":",
"\"\"\"Get the latest data from the Notion API.\"\"\"",
"data",
"=",
"{",
"\"bridges\"",
":",
"{",
"}",
",",
"\"sensors\"",
":",
"{",
"}",
",",
"\"tasks\"",
":",
"{",
"}",
"}",
"tasks",
"=",
"{",
"\"bridges\"",
":",
"client",
".",
"bridge",
".",
"async_all",
"(",
")",
",",
"\"sensors\"",
":",
"client",
".",
"sensor",
".",
"async_all",
"(",
")",
",",
"\"tasks\"",
":",
"client",
".",
"task",
".",
"async_all",
"(",
")",
",",
"}",
"results",
"=",
"await",
"asyncio",
".",
"gather",
"(",
"*",
"tasks",
".",
"values",
"(",
")",
",",
"return_exceptions",
"=",
"True",
")",
"for",
"attr",
",",
"result",
"in",
"zip",
"(",
"tasks",
",",
"results",
")",
":",
"if",
"isinstance",
"(",
"result",
",",
"NotionError",
")",
":",
"raise",
"UpdateFailed",
"(",
"f\"There was a Notion error while updating {attr}: {result}\"",
")",
"if",
"isinstance",
"(",
"result",
",",
"Exception",
")",
":",
"raise",
"UpdateFailed",
"(",
"f\"There was an unknown error while updating {attr}: {result}\"",
")",
"for",
"item",
"in",
"result",
":",
"if",
"attr",
"==",
"\"bridges\"",
"and",
"item",
"[",
"\"id\"",
"]",
"not",
"in",
"data",
"[",
"\"bridges\"",
"]",
":",
"# If a new bridge is discovered, register it:",
"hass",
".",
"async_create_task",
"(",
"async_register_new_bridge",
"(",
"hass",
",",
"item",
",",
"entry",
")",
")",
"data",
"[",
"attr",
"]",
"[",
"item",
"[",
"\"id\"",
"]",
"]",
"=",
"item",
"return",
"data",
"coordinator",
"=",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"DATA_COORDINATOR",
"]",
"[",
"entry",
".",
"entry_id",
"]",
"=",
"DataUpdateCoordinator",
"(",
"hass",
",",
"_LOGGER",
",",
"name",
"=",
"entry",
".",
"data",
"[",
"CONF_USERNAME",
"]",
",",
"update_interval",
"=",
"DEFAULT_SCAN_INTERVAL",
",",
"update_method",
"=",
"async_update",
",",
")",
"await",
"coordinator",
".",
"async_refresh",
"(",
")",
"for",
"platform",
"in",
"PLATFORMS",
":",
"hass",
".",
"async_create_task",
"(",
"hass",
".",
"config_entries",
".",
"async_forward_entry_setup",
"(",
"entry",
",",
"platform",
")",
")",
"return",
"True"
] | [
44,
0
] | [
109,
15
] | python | en | ['en', 'en', 'en'] | True |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.