Search is not available for this dataset
identifier
stringlengths 1
155
| parameters
stringlengths 2
6.09k
| docstring
stringlengths 11
63.4k
| docstring_summary
stringlengths 0
63.4k
| function
stringlengths 29
99.8k
| function_tokens
sequence | start_point
sequence | end_point
sequence | language
stringclasses 1
value | docstring_language
stringlengths 2
7
| docstring_language_predictions
stringlengths 18
23
| is_langid_reliable
stringclasses 2
values |
---|---|---|---|---|---|---|---|---|---|---|---|
test_dehumidifier_set_mode | (hass, utcnow) | Test that we can set the mode of a HomeKit dehumidifier accessory. | Test that we can set the mode of a HomeKit dehumidifier accessory. | async def test_dehumidifier_set_mode(hass, utcnow):
"""Test that we can set the mode of a HomeKit dehumidifier accessory."""
helper = await setup_test_component(hass, create_dehumidifier_service)
await hass.services.async_call(
DOMAIN,
"set_mode",
{"entity_id": helper.entity_id, "mode": MODE_AUTO},
blocking=True,
)
assert helper.characteristics[TARGET_HUMIDIFIER_DEHUMIDIFIER_STATE].value == 0
assert helper.characteristics[ACTIVE].value == 1
await hass.services.async_call(
DOMAIN,
"set_mode",
{"entity_id": helper.entity_id, "mode": MODE_NORMAL},
blocking=True,
)
assert helper.characteristics[TARGET_HUMIDIFIER_DEHUMIDIFIER_STATE].value == 2
assert helper.characteristics[ACTIVE].value == 1 | [
"async",
"def",
"test_dehumidifier_set_mode",
"(",
"hass",
",",
"utcnow",
")",
":",
"helper",
"=",
"await",
"setup_test_component",
"(",
"hass",
",",
"create_dehumidifier_service",
")",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"DOMAIN",
",",
"\"set_mode\"",
",",
"{",
"\"entity_id\"",
":",
"helper",
".",
"entity_id",
",",
"\"mode\"",
":",
"MODE_AUTO",
"}",
",",
"blocking",
"=",
"True",
",",
")",
"assert",
"helper",
".",
"characteristics",
"[",
"TARGET_HUMIDIFIER_DEHUMIDIFIER_STATE",
"]",
".",
"value",
"==",
"0",
"assert",
"helper",
".",
"characteristics",
"[",
"ACTIVE",
"]",
".",
"value",
"==",
"1",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"DOMAIN",
",",
"\"set_mode\"",
",",
"{",
"\"entity_id\"",
":",
"helper",
".",
"entity_id",
",",
"\"mode\"",
":",
"MODE_NORMAL",
"}",
",",
"blocking",
"=",
"True",
",",
")",
"assert",
"helper",
".",
"characteristics",
"[",
"TARGET_HUMIDIFIER_DEHUMIDIFIER_STATE",
"]",
".",
"value",
"==",
"2",
"assert",
"helper",
".",
"characteristics",
"[",
"ACTIVE",
"]",
".",
"value",
"==",
"1"
] | [
208,
0
] | [
228,
52
] | python | en | ['en', 'en', 'en'] | True |
test_humidifier_read_only_mode | (hass, utcnow) | Test that we can read the state of a HomeKit humidifier accessory. | Test that we can read the state of a HomeKit humidifier accessory. | async def test_humidifier_read_only_mode(hass, utcnow):
"""Test that we can read the state of a HomeKit humidifier accessory."""
helper = await setup_test_component(hass, create_humidifier_service)
state = await helper.poll_and_get_state()
assert state.attributes["mode"] == "normal"
helper.characteristics[CURRENT_HUMIDIFIER_DEHUMIDIFIER_STATE].value = 0
state = await helper.poll_and_get_state()
assert state.attributes["mode"] == "normal"
helper.characteristics[CURRENT_HUMIDIFIER_DEHUMIDIFIER_STATE].value = 1
state = await helper.poll_and_get_state()
assert state.attributes["mode"] == "auto"
helper.characteristics[CURRENT_HUMIDIFIER_DEHUMIDIFIER_STATE].value = 2
state = await helper.poll_and_get_state()
assert state.attributes["mode"] == "normal"
helper.characteristics[CURRENT_HUMIDIFIER_DEHUMIDIFIER_STATE].value = 3
state = await helper.poll_and_get_state()
assert state.attributes["mode"] == "normal" | [
"async",
"def",
"test_humidifier_read_only_mode",
"(",
"hass",
",",
"utcnow",
")",
":",
"helper",
"=",
"await",
"setup_test_component",
"(",
"hass",
",",
"create_humidifier_service",
")",
"state",
"=",
"await",
"helper",
".",
"poll_and_get_state",
"(",
")",
"assert",
"state",
".",
"attributes",
"[",
"\"mode\"",
"]",
"==",
"\"normal\"",
"helper",
".",
"characteristics",
"[",
"CURRENT_HUMIDIFIER_DEHUMIDIFIER_STATE",
"]",
".",
"value",
"=",
"0",
"state",
"=",
"await",
"helper",
".",
"poll_and_get_state",
"(",
")",
"assert",
"state",
".",
"attributes",
"[",
"\"mode\"",
"]",
"==",
"\"normal\"",
"helper",
".",
"characteristics",
"[",
"CURRENT_HUMIDIFIER_DEHUMIDIFIER_STATE",
"]",
".",
"value",
"=",
"1",
"state",
"=",
"await",
"helper",
".",
"poll_and_get_state",
"(",
")",
"assert",
"state",
".",
"attributes",
"[",
"\"mode\"",
"]",
"==",
"\"auto\"",
"helper",
".",
"characteristics",
"[",
"CURRENT_HUMIDIFIER_DEHUMIDIFIER_STATE",
"]",
".",
"value",
"=",
"2",
"state",
"=",
"await",
"helper",
".",
"poll_and_get_state",
"(",
")",
"assert",
"state",
".",
"attributes",
"[",
"\"mode\"",
"]",
"==",
"\"normal\"",
"helper",
".",
"characteristics",
"[",
"CURRENT_HUMIDIFIER_DEHUMIDIFIER_STATE",
"]",
".",
"value",
"=",
"3",
"state",
"=",
"await",
"helper",
".",
"poll_and_get_state",
"(",
")",
"assert",
"state",
".",
"attributes",
"[",
"\"mode\"",
"]",
"==",
"\"normal\""
] | [
231,
0
] | [
252,
47
] | python | en | ['en', 'en', 'en'] | True |
test_dehumidifier_read_only_mode | (hass, utcnow) | Test that we can read the state of a HomeKit dehumidifier accessory. | Test that we can read the state of a HomeKit dehumidifier accessory. | async def test_dehumidifier_read_only_mode(hass, utcnow):
"""Test that we can read the state of a HomeKit dehumidifier accessory."""
helper = await setup_test_component(hass, create_dehumidifier_service)
state = await helper.poll_and_get_state()
assert state.attributes["mode"] == "normal"
helper.characteristics[CURRENT_HUMIDIFIER_DEHUMIDIFIER_STATE].value = 0
state = await helper.poll_and_get_state()
assert state.attributes["mode"] == "normal"
helper.characteristics[CURRENT_HUMIDIFIER_DEHUMIDIFIER_STATE].value = 1
state = await helper.poll_and_get_state()
assert state.attributes["mode"] == "auto"
helper.characteristics[CURRENT_HUMIDIFIER_DEHUMIDIFIER_STATE].value = 2
state = await helper.poll_and_get_state()
assert state.attributes["mode"] == "normal"
helper.characteristics[CURRENT_HUMIDIFIER_DEHUMIDIFIER_STATE].value = 3
state = await helper.poll_and_get_state()
assert state.attributes["mode"] == "normal" | [
"async",
"def",
"test_dehumidifier_read_only_mode",
"(",
"hass",
",",
"utcnow",
")",
":",
"helper",
"=",
"await",
"setup_test_component",
"(",
"hass",
",",
"create_dehumidifier_service",
")",
"state",
"=",
"await",
"helper",
".",
"poll_and_get_state",
"(",
")",
"assert",
"state",
".",
"attributes",
"[",
"\"mode\"",
"]",
"==",
"\"normal\"",
"helper",
".",
"characteristics",
"[",
"CURRENT_HUMIDIFIER_DEHUMIDIFIER_STATE",
"]",
".",
"value",
"=",
"0",
"state",
"=",
"await",
"helper",
".",
"poll_and_get_state",
"(",
")",
"assert",
"state",
".",
"attributes",
"[",
"\"mode\"",
"]",
"==",
"\"normal\"",
"helper",
".",
"characteristics",
"[",
"CURRENT_HUMIDIFIER_DEHUMIDIFIER_STATE",
"]",
".",
"value",
"=",
"1",
"state",
"=",
"await",
"helper",
".",
"poll_and_get_state",
"(",
")",
"assert",
"state",
".",
"attributes",
"[",
"\"mode\"",
"]",
"==",
"\"auto\"",
"helper",
".",
"characteristics",
"[",
"CURRENT_HUMIDIFIER_DEHUMIDIFIER_STATE",
"]",
".",
"value",
"=",
"2",
"state",
"=",
"await",
"helper",
".",
"poll_and_get_state",
"(",
")",
"assert",
"state",
".",
"attributes",
"[",
"\"mode\"",
"]",
"==",
"\"normal\"",
"helper",
".",
"characteristics",
"[",
"CURRENT_HUMIDIFIER_DEHUMIDIFIER_STATE",
"]",
".",
"value",
"=",
"3",
"state",
"=",
"await",
"helper",
".",
"poll_and_get_state",
"(",
")",
"assert",
"state",
".",
"attributes",
"[",
"\"mode\"",
"]",
"==",
"\"normal\""
] | [
255,
0
] | [
276,
47
] | python | en | ['en', 'en', 'en'] | True |
test_humidifier_target_humidity_modes | (hass, utcnow) | Test that we can read the state of a HomeKit humidifier accessory. | Test that we can read the state of a HomeKit humidifier accessory. | async def test_humidifier_target_humidity_modes(hass, utcnow):
"""Test that we can read the state of a HomeKit humidifier accessory."""
helper = await setup_test_component(hass, create_humidifier_service)
helper.characteristics[RELATIVE_HUMIDITY_HUMIDIFIER_THRESHOLD].value = 37
helper.characteristics[RELATIVE_HUMIDITY_CURRENT].value = 51
helper.characteristics[CURRENT_HUMIDIFIER_DEHUMIDIFIER_STATE].value = 1
state = await helper.poll_and_get_state()
assert state.attributes["mode"] == "auto"
assert state.attributes["humidity"] == 37
helper.characteristics[CURRENT_HUMIDIFIER_DEHUMIDIFIER_STATE].value = 3
state = await helper.poll_and_get_state()
assert state.attributes["mode"] == "normal"
assert state.attributes["humidity"] == 37
helper.characteristics[CURRENT_HUMIDIFIER_DEHUMIDIFIER_STATE].value = 2
state = await helper.poll_and_get_state()
assert state.attributes["mode"] == "normal"
assert state.attributes["humidity"] == 37
helper.characteristics[CURRENT_HUMIDIFIER_DEHUMIDIFIER_STATE].value = 0
state = await helper.poll_and_get_state()
assert state.attributes["mode"] == "normal"
assert state.attributes["humidity"] == 37 | [
"async",
"def",
"test_humidifier_target_humidity_modes",
"(",
"hass",
",",
"utcnow",
")",
":",
"helper",
"=",
"await",
"setup_test_component",
"(",
"hass",
",",
"create_humidifier_service",
")",
"helper",
".",
"characteristics",
"[",
"RELATIVE_HUMIDITY_HUMIDIFIER_THRESHOLD",
"]",
".",
"value",
"=",
"37",
"helper",
".",
"characteristics",
"[",
"RELATIVE_HUMIDITY_CURRENT",
"]",
".",
"value",
"=",
"51",
"helper",
".",
"characteristics",
"[",
"CURRENT_HUMIDIFIER_DEHUMIDIFIER_STATE",
"]",
".",
"value",
"=",
"1",
"state",
"=",
"await",
"helper",
".",
"poll_and_get_state",
"(",
")",
"assert",
"state",
".",
"attributes",
"[",
"\"mode\"",
"]",
"==",
"\"auto\"",
"assert",
"state",
".",
"attributes",
"[",
"\"humidity\"",
"]",
"==",
"37",
"helper",
".",
"characteristics",
"[",
"CURRENT_HUMIDIFIER_DEHUMIDIFIER_STATE",
"]",
".",
"value",
"=",
"3",
"state",
"=",
"await",
"helper",
".",
"poll_and_get_state",
"(",
")",
"assert",
"state",
".",
"attributes",
"[",
"\"mode\"",
"]",
"==",
"\"normal\"",
"assert",
"state",
".",
"attributes",
"[",
"\"humidity\"",
"]",
"==",
"37",
"helper",
".",
"characteristics",
"[",
"CURRENT_HUMIDIFIER_DEHUMIDIFIER_STATE",
"]",
".",
"value",
"=",
"2",
"state",
"=",
"await",
"helper",
".",
"poll_and_get_state",
"(",
")",
"assert",
"state",
".",
"attributes",
"[",
"\"mode\"",
"]",
"==",
"\"normal\"",
"assert",
"state",
".",
"attributes",
"[",
"\"humidity\"",
"]",
"==",
"37",
"helper",
".",
"characteristics",
"[",
"CURRENT_HUMIDIFIER_DEHUMIDIFIER_STATE",
"]",
".",
"value",
"=",
"0",
"state",
"=",
"await",
"helper",
".",
"poll_and_get_state",
"(",
")",
"assert",
"state",
".",
"attributes",
"[",
"\"mode\"",
"]",
"==",
"\"normal\"",
"assert",
"state",
".",
"attributes",
"[",
"\"humidity\"",
"]",
"==",
"37"
] | [
279,
0
] | [
304,
45
] | python | en | ['en', 'en', 'en'] | True |
test_dehumidifier_target_humidity_modes | (hass, utcnow) | Test that we can read the state of a HomeKit dehumidifier accessory. | Test that we can read the state of a HomeKit dehumidifier accessory. | async def test_dehumidifier_target_humidity_modes(hass, utcnow):
"""Test that we can read the state of a HomeKit dehumidifier accessory."""
helper = await setup_test_component(hass, create_dehumidifier_service)
helper.characteristics[RELATIVE_HUMIDITY_DEHUMIDIFIER_THRESHOLD].value = 73
helper.characteristics[RELATIVE_HUMIDITY_CURRENT].value = 51
helper.characteristics[CURRENT_HUMIDIFIER_DEHUMIDIFIER_STATE].value = 1
state = await helper.poll_and_get_state()
assert state.attributes["mode"] == "auto"
assert state.attributes["humidity"] == 73
helper.characteristics[CURRENT_HUMIDIFIER_DEHUMIDIFIER_STATE].value = 3
state = await helper.poll_and_get_state()
assert state.attributes["mode"] == "normal"
assert state.attributes["humidity"] == 73
helper.characteristics[CURRENT_HUMIDIFIER_DEHUMIDIFIER_STATE].value = 2
state = await helper.poll_and_get_state()
assert state.attributes["mode"] == "normal"
assert state.attributes["humidity"] == 73
helper.characteristics[CURRENT_HUMIDIFIER_DEHUMIDIFIER_STATE].value = 0
state = await helper.poll_and_get_state()
assert state.attributes["mode"] == "normal"
assert state.attributes["humidity"] == 73 | [
"async",
"def",
"test_dehumidifier_target_humidity_modes",
"(",
"hass",
",",
"utcnow",
")",
":",
"helper",
"=",
"await",
"setup_test_component",
"(",
"hass",
",",
"create_dehumidifier_service",
")",
"helper",
".",
"characteristics",
"[",
"RELATIVE_HUMIDITY_DEHUMIDIFIER_THRESHOLD",
"]",
".",
"value",
"=",
"73",
"helper",
".",
"characteristics",
"[",
"RELATIVE_HUMIDITY_CURRENT",
"]",
".",
"value",
"=",
"51",
"helper",
".",
"characteristics",
"[",
"CURRENT_HUMIDIFIER_DEHUMIDIFIER_STATE",
"]",
".",
"value",
"=",
"1",
"state",
"=",
"await",
"helper",
".",
"poll_and_get_state",
"(",
")",
"assert",
"state",
".",
"attributes",
"[",
"\"mode\"",
"]",
"==",
"\"auto\"",
"assert",
"state",
".",
"attributes",
"[",
"\"humidity\"",
"]",
"==",
"73",
"helper",
".",
"characteristics",
"[",
"CURRENT_HUMIDIFIER_DEHUMIDIFIER_STATE",
"]",
".",
"value",
"=",
"3",
"state",
"=",
"await",
"helper",
".",
"poll_and_get_state",
"(",
")",
"assert",
"state",
".",
"attributes",
"[",
"\"mode\"",
"]",
"==",
"\"normal\"",
"assert",
"state",
".",
"attributes",
"[",
"\"humidity\"",
"]",
"==",
"73",
"helper",
".",
"characteristics",
"[",
"CURRENT_HUMIDIFIER_DEHUMIDIFIER_STATE",
"]",
".",
"value",
"=",
"2",
"state",
"=",
"await",
"helper",
".",
"poll_and_get_state",
"(",
")",
"assert",
"state",
".",
"attributes",
"[",
"\"mode\"",
"]",
"==",
"\"normal\"",
"assert",
"state",
".",
"attributes",
"[",
"\"humidity\"",
"]",
"==",
"73",
"helper",
".",
"characteristics",
"[",
"CURRENT_HUMIDIFIER_DEHUMIDIFIER_STATE",
"]",
".",
"value",
"=",
"0",
"state",
"=",
"await",
"helper",
".",
"poll_and_get_state",
"(",
")",
"assert",
"state",
".",
"attributes",
"[",
"\"mode\"",
"]",
"==",
"\"normal\"",
"assert",
"state",
".",
"attributes",
"[",
"\"humidity\"",
"]",
"==",
"73"
] | [
307,
0
] | [
332,
45
] | python | en | ['en', 'en', 'en'] | True |
async_setup | (hass: HomeAssistant, yaml_config: Dict[str, Any]) | Activate Google Actions component. | Activate Google Actions component. | async def async_setup(hass: HomeAssistant, yaml_config: Dict[str, Any]):
"""Activate Google Actions component."""
config = yaml_config.get(DOMAIN, {})
google_config = GoogleConfig(hass, config)
await google_config.async_initialize()
hass.http.register_view(GoogleAssistantView(google_config))
if google_config.should_report_state:
google_config.async_enable_report_state()
async def request_sync_service_handler(call: ServiceCall):
"""Handle request sync service calls."""
agent_user_id = call.data.get("agent_user_id") or call.context.user_id
if agent_user_id is None:
_LOGGER.warning(
"No agent_user_id supplied for request_sync. Call as a user or pass in user id as agent_user_id"
)
return
await google_config.async_sync_entities(agent_user_id)
# Register service only if key is provided
if CONF_API_KEY in config or CONF_SERVICE_ACCOUNT in config:
hass.services.async_register(
DOMAIN, SERVICE_REQUEST_SYNC, request_sync_service_handler
)
return True | [
"async",
"def",
"async_setup",
"(",
"hass",
":",
"HomeAssistant",
",",
"yaml_config",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
")",
":",
"config",
"=",
"yaml_config",
".",
"get",
"(",
"DOMAIN",
",",
"{",
"}",
")",
"google_config",
"=",
"GoogleConfig",
"(",
"hass",
",",
"config",
")",
"await",
"google_config",
".",
"async_initialize",
"(",
")",
"hass",
".",
"http",
".",
"register_view",
"(",
"GoogleAssistantView",
"(",
"google_config",
")",
")",
"if",
"google_config",
".",
"should_report_state",
":",
"google_config",
".",
"async_enable_report_state",
"(",
")",
"async",
"def",
"request_sync_service_handler",
"(",
"call",
":",
"ServiceCall",
")",
":",
"\"\"\"Handle request sync service calls.\"\"\"",
"agent_user_id",
"=",
"call",
".",
"data",
".",
"get",
"(",
"\"agent_user_id\"",
")",
"or",
"call",
".",
"context",
".",
"user_id",
"if",
"agent_user_id",
"is",
"None",
":",
"_LOGGER",
".",
"warning",
"(",
"\"No agent_user_id supplied for request_sync. Call as a user or pass in user id as agent_user_id\"",
")",
"return",
"await",
"google_config",
".",
"async_sync_entities",
"(",
"agent_user_id",
")",
"# Register service only if key is provided",
"if",
"CONF_API_KEY",
"in",
"config",
"or",
"CONF_SERVICE_ACCOUNT",
"in",
"config",
":",
"hass",
".",
"services",
".",
"async_register",
"(",
"DOMAIN",
",",
"SERVICE_REQUEST_SYNC",
",",
"request_sync_service_handler",
")",
"return",
"True"
] | [
90,
0
] | [
120,
15
] | python | en | ['en', 'en', 'en'] | True |
test_form | (hass) | Test we get the form and can setup from user input. | Test we get the form and can setup from user input. | async def test_form(hass):
"""Test we get the form and can setup from user input."""
await setup.async_setup_component(hass, "persistent_notification", {})
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] == "form"
assert result["errors"] == {}
mock_flume_device_list = _get_mocked_flume_device_list()
with patch(
"homeassistant.components.flume.config_flow.FlumeAuth",
return_value=True,
), patch(
"homeassistant.components.flume.config_flow.FlumeDeviceList",
return_value=mock_flume_device_list,
), patch(
"homeassistant.components.flume.async_setup", return_value=True
) as mock_setup, patch(
"homeassistant.components.flume.async_setup_entry",
return_value=True,
) as mock_setup_entry:
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_USERNAME: "test-username",
CONF_PASSWORD: "test-password",
CONF_CLIENT_ID: "client_id",
CONF_CLIENT_SECRET: "client_secret",
},
)
await hass.async_block_till_done()
assert result2["type"] == "create_entry"
assert result2["title"] == "test-username"
assert result2["data"] == {
CONF_USERNAME: "test-username",
CONF_PASSWORD: "test-password",
CONF_CLIENT_ID: "client_id",
CONF_CLIENT_SECRET: "client_secret",
}
assert len(mock_setup.mock_calls) == 1
assert len(mock_setup_entry.mock_calls) == 1 | [
"async",
"def",
"test_form",
"(",
"hass",
")",
":",
"await",
"setup",
".",
"async_setup_component",
"(",
"hass",
",",
"\"persistent_notification\"",
",",
"{",
"}",
")",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"config_entries",
".",
"SOURCE_USER",
"}",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"\"form\"",
"assert",
"result",
"[",
"\"errors\"",
"]",
"==",
"{",
"}",
"mock_flume_device_list",
"=",
"_get_mocked_flume_device_list",
"(",
")",
"with",
"patch",
"(",
"\"homeassistant.components.flume.config_flow.FlumeAuth\"",
",",
"return_value",
"=",
"True",
",",
")",
",",
"patch",
"(",
"\"homeassistant.components.flume.config_flow.FlumeDeviceList\"",
",",
"return_value",
"=",
"mock_flume_device_list",
",",
")",
",",
"patch",
"(",
"\"homeassistant.components.flume.async_setup\"",
",",
"return_value",
"=",
"True",
")",
"as",
"mock_setup",
",",
"patch",
"(",
"\"homeassistant.components.flume.async_setup_entry\"",
",",
"return_value",
"=",
"True",
",",
")",
"as",
"mock_setup_entry",
":",
"result2",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_configure",
"(",
"result",
"[",
"\"flow_id\"",
"]",
",",
"{",
"CONF_USERNAME",
":",
"\"test-username\"",
",",
"CONF_PASSWORD",
":",
"\"test-password\"",
",",
"CONF_CLIENT_ID",
":",
"\"client_id\"",
",",
"CONF_CLIENT_SECRET",
":",
"\"client_secret\"",
",",
"}",
",",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"result2",
"[",
"\"type\"",
"]",
"==",
"\"create_entry\"",
"assert",
"result2",
"[",
"\"title\"",
"]",
"==",
"\"test-username\"",
"assert",
"result2",
"[",
"\"data\"",
"]",
"==",
"{",
"CONF_USERNAME",
":",
"\"test-username\"",
",",
"CONF_PASSWORD",
":",
"\"test-password\"",
",",
"CONF_CLIENT_ID",
":",
"\"client_id\"",
",",
"CONF_CLIENT_SECRET",
":",
"\"client_secret\"",
",",
"}",
"assert",
"len",
"(",
"mock_setup",
".",
"mock_calls",
")",
"==",
"1",
"assert",
"len",
"(",
"mock_setup_entry",
".",
"mock_calls",
")",
"==",
"1"
] | [
21,
0
] | [
64,
48
] | python | en | ['en', 'en', 'en'] | True |
test_form_import | (hass) | Test we can import the sensor platform config. | Test we can import the sensor platform config. | async def test_form_import(hass):
"""Test we can import the sensor platform config."""
await setup.async_setup_component(hass, "persistent_notification", {})
mock_flume_device_list = _get_mocked_flume_device_list()
with patch(
"homeassistant.components.flume.config_flow.FlumeAuth",
return_value=True,
), patch(
"homeassistant.components.flume.config_flow.FlumeDeviceList",
return_value=mock_flume_device_list,
), patch(
"homeassistant.components.flume.async_setup", return_value=True
) as mock_setup, patch(
"homeassistant.components.flume.async_setup_entry",
return_value=True,
) as mock_setup_entry:
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_IMPORT},
data={
CONF_USERNAME: "test-username",
CONF_PASSWORD: "test-password",
CONF_CLIENT_ID: "client_id",
CONF_CLIENT_SECRET: "client_secret",
},
)
await hass.async_block_till_done()
assert result["type"] == "create_entry"
assert result["title"] == "test-username"
assert result["data"] == {
CONF_USERNAME: "test-username",
CONF_PASSWORD: "test-password",
CONF_CLIENT_ID: "client_id",
CONF_CLIENT_SECRET: "client_secret",
}
assert len(mock_setup.mock_calls) == 1
assert len(mock_setup_entry.mock_calls) == 1 | [
"async",
"def",
"test_form_import",
"(",
"hass",
")",
":",
"await",
"setup",
".",
"async_setup_component",
"(",
"hass",
",",
"\"persistent_notification\"",
",",
"{",
"}",
")",
"mock_flume_device_list",
"=",
"_get_mocked_flume_device_list",
"(",
")",
"with",
"patch",
"(",
"\"homeassistant.components.flume.config_flow.FlumeAuth\"",
",",
"return_value",
"=",
"True",
",",
")",
",",
"patch",
"(",
"\"homeassistant.components.flume.config_flow.FlumeDeviceList\"",
",",
"return_value",
"=",
"mock_flume_device_list",
",",
")",
",",
"patch",
"(",
"\"homeassistant.components.flume.async_setup\"",
",",
"return_value",
"=",
"True",
")",
"as",
"mock_setup",
",",
"patch",
"(",
"\"homeassistant.components.flume.async_setup_entry\"",
",",
"return_value",
"=",
"True",
",",
")",
"as",
"mock_setup_entry",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"config_entries",
".",
"SOURCE_IMPORT",
"}",
",",
"data",
"=",
"{",
"CONF_USERNAME",
":",
"\"test-username\"",
",",
"CONF_PASSWORD",
":",
"\"test-password\"",
",",
"CONF_CLIENT_ID",
":",
"\"client_id\"",
",",
"CONF_CLIENT_SECRET",
":",
"\"client_secret\"",
",",
"}",
",",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"\"create_entry\"",
"assert",
"result",
"[",
"\"title\"",
"]",
"==",
"\"test-username\"",
"assert",
"result",
"[",
"\"data\"",
"]",
"==",
"{",
"CONF_USERNAME",
":",
"\"test-username\"",
",",
"CONF_PASSWORD",
":",
"\"test-password\"",
",",
"CONF_CLIENT_ID",
":",
"\"client_id\"",
",",
"CONF_CLIENT_SECRET",
":",
"\"client_secret\"",
",",
"}",
"assert",
"len",
"(",
"mock_setup",
".",
"mock_calls",
")",
"==",
"1",
"assert",
"len",
"(",
"mock_setup_entry",
".",
"mock_calls",
")",
"==",
"1"
] | [
67,
0
] | [
105,
48
] | python | en | ['en', 'da', 'en'] | True |
test_form_invalid_auth | (hass) | Test we handle invalid auth. | Test we handle invalid auth. | async def test_form_invalid_auth(hass):
"""Test we handle invalid auth."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
with patch(
"homeassistant.components.flume.config_flow.FlumeAuth",
return_value=True,
), patch(
"homeassistant.components.flume.config_flow.FlumeDeviceList",
side_effect=Exception,
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_USERNAME: "test-username",
CONF_PASSWORD: "test-password",
CONF_CLIENT_ID: "client_id",
CONF_CLIENT_SECRET: "client_secret",
},
)
assert result2["type"] == "form"
assert result2["errors"] == {"base": "invalid_auth"} | [
"async",
"def",
"test_form_invalid_auth",
"(",
"hass",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"config_entries",
".",
"SOURCE_USER",
"}",
")",
"with",
"patch",
"(",
"\"homeassistant.components.flume.config_flow.FlumeAuth\"",
",",
"return_value",
"=",
"True",
",",
")",
",",
"patch",
"(",
"\"homeassistant.components.flume.config_flow.FlumeDeviceList\"",
",",
"side_effect",
"=",
"Exception",
",",
")",
":",
"result2",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_configure",
"(",
"result",
"[",
"\"flow_id\"",
"]",
",",
"{",
"CONF_USERNAME",
":",
"\"test-username\"",
",",
"CONF_PASSWORD",
":",
"\"test-password\"",
",",
"CONF_CLIENT_ID",
":",
"\"client_id\"",
",",
"CONF_CLIENT_SECRET",
":",
"\"client_secret\"",
",",
"}",
",",
")",
"assert",
"result2",
"[",
"\"type\"",
"]",
"==",
"\"form\"",
"assert",
"result2",
"[",
"\"errors\"",
"]",
"==",
"{",
"\"base\"",
":",
"\"invalid_auth\"",
"}"
] | [
108,
0
] | [
132,
56
] | python | en | ['en', 'en', 'en'] | True |
test_form_cannot_connect | (hass) | Test we handle cannot connect error. | Test we handle cannot connect error. | async def test_form_cannot_connect(hass):
"""Test we handle cannot connect error."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
with patch(
"homeassistant.components.flume.config_flow.FlumeAuth",
return_value=True,
), patch(
"homeassistant.components.flume.config_flow.FlumeDeviceList",
side_effect=requests.exceptions.ConnectionError(),
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_USERNAME: "test-username",
CONF_PASSWORD: "test-password",
CONF_CLIENT_ID: "client_id",
CONF_CLIENT_SECRET: "client_secret",
},
)
assert result2["type"] == "form"
assert result2["errors"] == {"base": "cannot_connect"} | [
"async",
"def",
"test_form_cannot_connect",
"(",
"hass",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"config_entries",
".",
"SOURCE_USER",
"}",
")",
"with",
"patch",
"(",
"\"homeassistant.components.flume.config_flow.FlumeAuth\"",
",",
"return_value",
"=",
"True",
",",
")",
",",
"patch",
"(",
"\"homeassistant.components.flume.config_flow.FlumeDeviceList\"",
",",
"side_effect",
"=",
"requests",
".",
"exceptions",
".",
"ConnectionError",
"(",
")",
",",
")",
":",
"result2",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_configure",
"(",
"result",
"[",
"\"flow_id\"",
"]",
",",
"{",
"CONF_USERNAME",
":",
"\"test-username\"",
",",
"CONF_PASSWORD",
":",
"\"test-password\"",
",",
"CONF_CLIENT_ID",
":",
"\"client_id\"",
",",
"CONF_CLIENT_SECRET",
":",
"\"client_secret\"",
",",
"}",
",",
")",
"assert",
"result2",
"[",
"\"type\"",
"]",
"==",
"\"form\"",
"assert",
"result2",
"[",
"\"errors\"",
"]",
"==",
"{",
"\"base\"",
":",
"\"cannot_connect\"",
"}"
] | [
135,
0
] | [
158,
58
] | python | en | ['en', 'en', 'en'] | True |
async_attach_trigger | (hass, config, action, automation_info) | Listen for events based on configuration. | Listen for events based on configuration. | async def async_attach_trigger(hass, config, action, automation_info):
"""Listen for events based on configuration."""
number = config.get(CONF_NUMBER)
held_more_than = config.get(CONF_HELD_MORE_THAN)
held_less_than = config.get(CONF_HELD_LESS_THAN)
pressed_time = None
cancel_pressed_more_than = None
job = HassJob(action)
@callback
def call_action():
"""Call action with right context."""
hass.async_run_hass_job(
job,
{
"trigger": {
CONF_PLATFORM: "litejet",
CONF_NUMBER: number,
CONF_HELD_MORE_THAN: held_more_than,
CONF_HELD_LESS_THAN: held_less_than,
"description": f"litejet switch #{number}",
}
},
)
# held_more_than and held_less_than: trigger on released (if in time range)
# held_more_than: trigger after pressed with calculation
# held_less_than: trigger on released with calculation
# neither: trigger on pressed
@callback
def pressed_more_than_satisfied(now):
"""Handle the LiteJet's switch's button pressed >= held_more_than."""
call_action()
def pressed():
"""Handle the press of the LiteJet switch's button."""
nonlocal cancel_pressed_more_than, pressed_time
nonlocal held_less_than, held_more_than
pressed_time = dt_util.utcnow()
if held_more_than is None and held_less_than is None:
hass.add_job(call_action)
if held_more_than is not None and held_less_than is None:
cancel_pressed_more_than = track_point_in_utc_time(
hass, pressed_more_than_satisfied, dt_util.utcnow() + held_more_than
)
def released():
"""Handle the release of the LiteJet switch's button."""
nonlocal cancel_pressed_more_than, pressed_time
nonlocal held_less_than, held_more_than
# pylint: disable=not-callable
if cancel_pressed_more_than is not None:
cancel_pressed_more_than()
cancel_pressed_more_than = None
held_time = dt_util.utcnow() - pressed_time
if (
held_less_than is not None
and held_time < held_less_than
and (held_more_than is None or held_time > held_more_than)
):
hass.add_job(call_action)
hass.data["litejet_system"].on_switch_pressed(number, pressed)
hass.data["litejet_system"].on_switch_released(number, released)
@callback
def async_remove():
"""Remove all subscriptions used for this trigger."""
return
return async_remove | [
"async",
"def",
"async_attach_trigger",
"(",
"hass",
",",
"config",
",",
"action",
",",
"automation_info",
")",
":",
"number",
"=",
"config",
".",
"get",
"(",
"CONF_NUMBER",
")",
"held_more_than",
"=",
"config",
".",
"get",
"(",
"CONF_HELD_MORE_THAN",
")",
"held_less_than",
"=",
"config",
".",
"get",
"(",
"CONF_HELD_LESS_THAN",
")",
"pressed_time",
"=",
"None",
"cancel_pressed_more_than",
"=",
"None",
"job",
"=",
"HassJob",
"(",
"action",
")",
"@",
"callback",
"def",
"call_action",
"(",
")",
":",
"\"\"\"Call action with right context.\"\"\"",
"hass",
".",
"async_run_hass_job",
"(",
"job",
",",
"{",
"\"trigger\"",
":",
"{",
"CONF_PLATFORM",
":",
"\"litejet\"",
",",
"CONF_NUMBER",
":",
"number",
",",
"CONF_HELD_MORE_THAN",
":",
"held_more_than",
",",
"CONF_HELD_LESS_THAN",
":",
"held_less_than",
",",
"\"description\"",
":",
"f\"litejet switch #{number}\"",
",",
"}",
"}",
",",
")",
"# held_more_than and held_less_than: trigger on released (if in time range)",
"# held_more_than: trigger after pressed with calculation",
"# held_less_than: trigger on released with calculation",
"# neither: trigger on pressed",
"@",
"callback",
"def",
"pressed_more_than_satisfied",
"(",
"now",
")",
":",
"\"\"\"Handle the LiteJet's switch's button pressed >= held_more_than.\"\"\"",
"call_action",
"(",
")",
"def",
"pressed",
"(",
")",
":",
"\"\"\"Handle the press of the LiteJet switch's button.\"\"\"",
"nonlocal",
"cancel_pressed_more_than",
",",
"pressed_time",
"nonlocal",
"held_less_than",
",",
"held_more_than",
"pressed_time",
"=",
"dt_util",
".",
"utcnow",
"(",
")",
"if",
"held_more_than",
"is",
"None",
"and",
"held_less_than",
"is",
"None",
":",
"hass",
".",
"add_job",
"(",
"call_action",
")",
"if",
"held_more_than",
"is",
"not",
"None",
"and",
"held_less_than",
"is",
"None",
":",
"cancel_pressed_more_than",
"=",
"track_point_in_utc_time",
"(",
"hass",
",",
"pressed_more_than_satisfied",
",",
"dt_util",
".",
"utcnow",
"(",
")",
"+",
"held_more_than",
")",
"def",
"released",
"(",
")",
":",
"\"\"\"Handle the release of the LiteJet switch's button.\"\"\"",
"nonlocal",
"cancel_pressed_more_than",
",",
"pressed_time",
"nonlocal",
"held_less_than",
",",
"held_more_than",
"# pylint: disable=not-callable",
"if",
"cancel_pressed_more_than",
"is",
"not",
"None",
":",
"cancel_pressed_more_than",
"(",
")",
"cancel_pressed_more_than",
"=",
"None",
"held_time",
"=",
"dt_util",
".",
"utcnow",
"(",
")",
"-",
"pressed_time",
"if",
"(",
"held_less_than",
"is",
"not",
"None",
"and",
"held_time",
"<",
"held_less_than",
"and",
"(",
"held_more_than",
"is",
"None",
"or",
"held_time",
">",
"held_more_than",
")",
")",
":",
"hass",
".",
"add_job",
"(",
"call_action",
")",
"hass",
".",
"data",
"[",
"\"litejet_system\"",
"]",
".",
"on_switch_pressed",
"(",
"number",
",",
"pressed",
")",
"hass",
".",
"data",
"[",
"\"litejet_system\"",
"]",
".",
"on_switch_released",
"(",
"number",
",",
"released",
")",
"@",
"callback",
"def",
"async_remove",
"(",
")",
":",
"\"\"\"Remove all subscriptions used for this trigger.\"\"\"",
"return",
"return",
"async_remove"
] | [
29,
0
] | [
101,
23
] | python | en | ['en', 'en', 'en'] | True |
test_form | (hass) | Test we get the form. | Test we get the form. | async def test_form(hass):
"""Test we get the form."""
await setup.async_setup_component(hass, "persistent_notification", {})
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] == "form"
assert result["errors"] == {}
with patch(
"homeassistant.components.griddy.config_flow.AsyncGriddy.async_getnow",
return_value=MagicMock(),
), patch(
"homeassistant.components.griddy.async_setup", return_value=True
) as mock_setup, patch(
"homeassistant.components.griddy.async_setup_entry",
return_value=True,
) as mock_setup_entry:
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{"loadzone": "LZ_HOUSTON"},
)
await hass.async_block_till_done()
assert result2["type"] == "create_entry"
assert result2["title"] == "Load Zone LZ_HOUSTON"
assert result2["data"] == {"loadzone": "LZ_HOUSTON"}
assert len(mock_setup.mock_calls) == 1
assert len(mock_setup_entry.mock_calls) == 1 | [
"async",
"def",
"test_form",
"(",
"hass",
")",
":",
"await",
"setup",
".",
"async_setup_component",
"(",
"hass",
",",
"\"persistent_notification\"",
",",
"{",
"}",
")",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"config_entries",
".",
"SOURCE_USER",
"}",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"\"form\"",
"assert",
"result",
"[",
"\"errors\"",
"]",
"==",
"{",
"}",
"with",
"patch",
"(",
"\"homeassistant.components.griddy.config_flow.AsyncGriddy.async_getnow\"",
",",
"return_value",
"=",
"MagicMock",
"(",
")",
",",
")",
",",
"patch",
"(",
"\"homeassistant.components.griddy.async_setup\"",
",",
"return_value",
"=",
"True",
")",
"as",
"mock_setup",
",",
"patch",
"(",
"\"homeassistant.components.griddy.async_setup_entry\"",
",",
"return_value",
"=",
"True",
",",
")",
"as",
"mock_setup_entry",
":",
"result2",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_configure",
"(",
"result",
"[",
"\"flow_id\"",
"]",
",",
"{",
"\"loadzone\"",
":",
"\"LZ_HOUSTON\"",
"}",
",",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"result2",
"[",
"\"type\"",
"]",
"==",
"\"create_entry\"",
"assert",
"result2",
"[",
"\"title\"",
"]",
"==",
"\"Load Zone LZ_HOUSTON\"",
"assert",
"result2",
"[",
"\"data\"",
"]",
"==",
"{",
"\"loadzone\"",
":",
"\"LZ_HOUSTON\"",
"}",
"assert",
"len",
"(",
"mock_setup",
".",
"mock_calls",
")",
"==",
"1",
"assert",
"len",
"(",
"mock_setup_entry",
".",
"mock_calls",
")",
"==",
"1"
] | [
9,
0
] | [
37,
48
] | python | en | ['en', 'en', 'en'] | True |
test_form_cannot_connect | (hass) | Test we handle cannot connect error. | Test we handle cannot connect error. | async def test_form_cannot_connect(hass):
"""Test we handle cannot connect error."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
with patch(
"homeassistant.components.griddy.config_flow.AsyncGriddy.async_getnow",
side_effect=asyncio.TimeoutError,
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{"loadzone": "LZ_NORTH"},
)
assert result2["type"] == "form"
assert result2["errors"] == {"base": "cannot_connect"} | [
"async",
"def",
"test_form_cannot_connect",
"(",
"hass",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"config_entries",
".",
"SOURCE_USER",
"}",
")",
"with",
"patch",
"(",
"\"homeassistant.components.griddy.config_flow.AsyncGriddy.async_getnow\"",
",",
"side_effect",
"=",
"asyncio",
".",
"TimeoutError",
",",
")",
":",
"result2",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_configure",
"(",
"result",
"[",
"\"flow_id\"",
"]",
",",
"{",
"\"loadzone\"",
":",
"\"LZ_NORTH\"",
"}",
",",
")",
"assert",
"result2",
"[",
"\"type\"",
"]",
"==",
"\"form\"",
"assert",
"result2",
"[",
"\"errors\"",
"]",
"==",
"{",
"\"base\"",
":",
"\"cannot_connect\"",
"}"
] | [
40,
0
] | [
56,
58
] | python | en | ['en', 'en', 'en'] | True |
test_fetch_period_api | (hass, hass_client) | Test the fetch period view for history. | Test the fetch period view for history. | async def test_fetch_period_api(hass, hass_client):
"""Test the fetch period view for history."""
await hass.async_add_executor_job(init_recorder_component, hass)
await async_setup_component(hass, "history", {})
await hass.async_add_executor_job(hass.data[recorder.DATA_INSTANCE].block_till_done)
client = await hass_client()
response = await client.get(f"/api/history/period/{dt_util.utcnow().isoformat()}")
assert response.status == 200 | [
"async",
"def",
"test_fetch_period_api",
"(",
"hass",
",",
"hass_client",
")",
":",
"await",
"hass",
".",
"async_add_executor_job",
"(",
"init_recorder_component",
",",
"hass",
")",
"await",
"async_setup_component",
"(",
"hass",
",",
"\"history\"",
",",
"{",
"}",
")",
"await",
"hass",
".",
"async_add_executor_job",
"(",
"hass",
".",
"data",
"[",
"recorder",
".",
"DATA_INSTANCE",
"]",
".",
"block_till_done",
")",
"client",
"=",
"await",
"hass_client",
"(",
")",
"response",
"=",
"await",
"client",
".",
"get",
"(",
"f\"/api/history/period/{dt_util.utcnow().isoformat()}\"",
")",
"assert",
"response",
".",
"status",
"==",
"200"
] | [
761,
0
] | [
768,
33
] | python | en | ['en', 'en', 'en'] | True |
test_fetch_period_api_with_use_include_order | (hass, hass_client) | Test the fetch period view for history with include order. | Test the fetch period view for history with include order. | async def test_fetch_period_api_with_use_include_order(hass, hass_client):
"""Test the fetch period view for history with include order."""
await hass.async_add_executor_job(init_recorder_component, hass)
await async_setup_component(
hass, "history", {history.DOMAIN: {history.CONF_ORDER: True}}
)
await hass.async_add_executor_job(hass.data[recorder.DATA_INSTANCE].block_till_done)
client = await hass_client()
response = await client.get(f"/api/history/period/{dt_util.utcnow().isoformat()}")
assert response.status == 200 | [
"async",
"def",
"test_fetch_period_api_with_use_include_order",
"(",
"hass",
",",
"hass_client",
")",
":",
"await",
"hass",
".",
"async_add_executor_job",
"(",
"init_recorder_component",
",",
"hass",
")",
"await",
"async_setup_component",
"(",
"hass",
",",
"\"history\"",
",",
"{",
"history",
".",
"DOMAIN",
":",
"{",
"history",
".",
"CONF_ORDER",
":",
"True",
"}",
"}",
")",
"await",
"hass",
".",
"async_add_executor_job",
"(",
"hass",
".",
"data",
"[",
"recorder",
".",
"DATA_INSTANCE",
"]",
".",
"block_till_done",
")",
"client",
"=",
"await",
"hass_client",
"(",
")",
"response",
"=",
"await",
"client",
".",
"get",
"(",
"f\"/api/history/period/{dt_util.utcnow().isoformat()}\"",
")",
"assert",
"response",
".",
"status",
"==",
"200"
] | [
771,
0
] | [
780,
33
] | python | en | ['en', 'en', 'en'] | True |
test_fetch_period_api_with_minimal_response | (hass, hass_client) | Test the fetch period view for history with minimal_response. | Test the fetch period view for history with minimal_response. | async def test_fetch_period_api_with_minimal_response(hass, hass_client):
"""Test the fetch period view for history with minimal_response."""
await hass.async_add_executor_job(init_recorder_component, hass)
await async_setup_component(hass, "history", {})
await hass.async_add_executor_job(hass.data[recorder.DATA_INSTANCE].block_till_done)
client = await hass_client()
response = await client.get(
f"/api/history/period/{dt_util.utcnow().isoformat()}?minimal_response"
)
assert response.status == 200 | [
"async",
"def",
"test_fetch_period_api_with_minimal_response",
"(",
"hass",
",",
"hass_client",
")",
":",
"await",
"hass",
".",
"async_add_executor_job",
"(",
"init_recorder_component",
",",
"hass",
")",
"await",
"async_setup_component",
"(",
"hass",
",",
"\"history\"",
",",
"{",
"}",
")",
"await",
"hass",
".",
"async_add_executor_job",
"(",
"hass",
".",
"data",
"[",
"recorder",
".",
"DATA_INSTANCE",
"]",
".",
"block_till_done",
")",
"client",
"=",
"await",
"hass_client",
"(",
")",
"response",
"=",
"await",
"client",
".",
"get",
"(",
"f\"/api/history/period/{dt_util.utcnow().isoformat()}?minimal_response\"",
")",
"assert",
"response",
".",
"status",
"==",
"200"
] | [
783,
0
] | [
792,
33
] | python | en | ['en', 'en', 'en'] | True |
test_fetch_period_api_with_no_timestamp | (hass, hass_client) | Test the fetch period view for history with no timestamp. | Test the fetch period view for history with no timestamp. | async def test_fetch_period_api_with_no_timestamp(hass, hass_client):
"""Test the fetch period view for history with no timestamp."""
await hass.async_add_executor_job(init_recorder_component, hass)
await async_setup_component(hass, "history", {})
await hass.async_add_executor_job(hass.data[recorder.DATA_INSTANCE].block_till_done)
client = await hass_client()
response = await client.get("/api/history/period")
assert response.status == 200 | [
"async",
"def",
"test_fetch_period_api_with_no_timestamp",
"(",
"hass",
",",
"hass_client",
")",
":",
"await",
"hass",
".",
"async_add_executor_job",
"(",
"init_recorder_component",
",",
"hass",
")",
"await",
"async_setup_component",
"(",
"hass",
",",
"\"history\"",
",",
"{",
"}",
")",
"await",
"hass",
".",
"async_add_executor_job",
"(",
"hass",
".",
"data",
"[",
"recorder",
".",
"DATA_INSTANCE",
"]",
".",
"block_till_done",
")",
"client",
"=",
"await",
"hass_client",
"(",
")",
"response",
"=",
"await",
"client",
".",
"get",
"(",
"\"/api/history/period\"",
")",
"assert",
"response",
".",
"status",
"==",
"200"
] | [
795,
0
] | [
802,
33
] | python | en | ['en', 'en', 'en'] | True |
test_fetch_period_api_with_include_order | (hass, hass_client) | Test the fetch period view for history. | Test the fetch period view for history. | async def test_fetch_period_api_with_include_order(hass, hass_client):
"""Test the fetch period view for history."""
await hass.async_add_executor_job(init_recorder_component, hass)
await async_setup_component(
hass,
"history",
{
"history": {
"use_include_order": True,
"include": {"entities": ["light.kitchen"]},
}
},
)
await hass.async_add_executor_job(hass.data[recorder.DATA_INSTANCE].block_till_done)
client = await hass_client()
response = await client.get(
f"/api/history/period/{dt_util.utcnow().isoformat()}",
params={"filter_entity_id": "non.existing,something.else"},
)
assert response.status == 200 | [
"async",
"def",
"test_fetch_period_api_with_include_order",
"(",
"hass",
",",
"hass_client",
")",
":",
"await",
"hass",
".",
"async_add_executor_job",
"(",
"init_recorder_component",
",",
"hass",
")",
"await",
"async_setup_component",
"(",
"hass",
",",
"\"history\"",
",",
"{",
"\"history\"",
":",
"{",
"\"use_include_order\"",
":",
"True",
",",
"\"include\"",
":",
"{",
"\"entities\"",
":",
"[",
"\"light.kitchen\"",
"]",
"}",
",",
"}",
"}",
",",
")",
"await",
"hass",
".",
"async_add_executor_job",
"(",
"hass",
".",
"data",
"[",
"recorder",
".",
"DATA_INSTANCE",
"]",
".",
"block_till_done",
")",
"client",
"=",
"await",
"hass_client",
"(",
")",
"response",
"=",
"await",
"client",
".",
"get",
"(",
"f\"/api/history/period/{dt_util.utcnow().isoformat()}\"",
",",
"params",
"=",
"{",
"\"filter_entity_id\"",
":",
"\"non.existing,something.else\"",
"}",
",",
")",
"assert",
"response",
".",
"status",
"==",
"200"
] | [
805,
0
] | [
824,
33
] | python | en | ['en', 'en', 'en'] | True |
test_fetch_period_api_with_entity_glob_include | (hass, hass_client) | Test the fetch period view for history. | Test the fetch period view for history. | async def test_fetch_period_api_with_entity_glob_include(hass, hass_client):
"""Test the fetch period view for history."""
await hass.async_add_executor_job(init_recorder_component, hass)
await async_setup_component(
hass,
"history",
{
"history": {
"include": {"entity_globs": ["light.k*"]},
}
},
)
await hass.async_add_executor_job(hass.data[recorder.DATA_INSTANCE].block_till_done)
hass.states.async_set("light.kitchen", "on")
hass.states.async_set("light.cow", "on")
hass.states.async_set("light.nomatch", "on")
await hass.async_block_till_done()
await hass.async_add_executor_job(trigger_db_commit, hass)
await hass.async_block_till_done()
await hass.async_add_executor_job(hass.data[recorder.DATA_INSTANCE].block_till_done)
client = await hass_client()
response = await client.get(
f"/api/history/period/{dt_util.utcnow().isoformat()}",
)
assert response.status == 200
response_json = await response.json()
assert response_json[0][0]["entity_id"] == "light.kitchen" | [
"async",
"def",
"test_fetch_period_api_with_entity_glob_include",
"(",
"hass",
",",
"hass_client",
")",
":",
"await",
"hass",
".",
"async_add_executor_job",
"(",
"init_recorder_component",
",",
"hass",
")",
"await",
"async_setup_component",
"(",
"hass",
",",
"\"history\"",
",",
"{",
"\"history\"",
":",
"{",
"\"include\"",
":",
"{",
"\"entity_globs\"",
":",
"[",
"\"light.k*\"",
"]",
"}",
",",
"}",
"}",
",",
")",
"await",
"hass",
".",
"async_add_executor_job",
"(",
"hass",
".",
"data",
"[",
"recorder",
".",
"DATA_INSTANCE",
"]",
".",
"block_till_done",
")",
"hass",
".",
"states",
".",
"async_set",
"(",
"\"light.kitchen\"",
",",
"\"on\"",
")",
"hass",
".",
"states",
".",
"async_set",
"(",
"\"light.cow\"",
",",
"\"on\"",
")",
"hass",
".",
"states",
".",
"async_set",
"(",
"\"light.nomatch\"",
",",
"\"on\"",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"await",
"hass",
".",
"async_add_executor_job",
"(",
"trigger_db_commit",
",",
"hass",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"await",
"hass",
".",
"async_add_executor_job",
"(",
"hass",
".",
"data",
"[",
"recorder",
".",
"DATA_INSTANCE",
"]",
".",
"block_till_done",
")",
"client",
"=",
"await",
"hass_client",
"(",
")",
"response",
"=",
"await",
"client",
".",
"get",
"(",
"f\"/api/history/period/{dt_util.utcnow().isoformat()}\"",
",",
")",
"assert",
"response",
".",
"status",
"==",
"200",
"response_json",
"=",
"await",
"response",
".",
"json",
"(",
")",
"assert",
"response_json",
"[",
"0",
"]",
"[",
"0",
"]",
"[",
"\"entity_id\"",
"]",
"==",
"\"light.kitchen\""
] | [
827,
0
] | [
856,
62
] | python | en | ['en', 'en', 'en'] | True |
test_fetch_period_api_with_entity_glob_exclude | (hass, hass_client) | Test the fetch period view for history. | Test the fetch period view for history. | async def test_fetch_period_api_with_entity_glob_exclude(hass, hass_client):
"""Test the fetch period view for history."""
await hass.async_add_executor_job(init_recorder_component, hass)
await async_setup_component(
hass,
"history",
{
"history": {
"exclude": {
"entity_globs": ["light.k*"],
"domains": "switch",
"entities": "media_player.test",
},
}
},
)
await hass.async_add_executor_job(hass.data[recorder.DATA_INSTANCE].block_till_done)
hass.states.async_set("light.kitchen", "on")
hass.states.async_set("light.cow", "on")
hass.states.async_set("light.match", "on")
hass.states.async_set("switch.match", "on")
hass.states.async_set("media_player.test", "on")
await hass.async_block_till_done()
await hass.async_add_executor_job(trigger_db_commit, hass)
await hass.async_block_till_done()
await hass.async_add_executor_job(hass.data[recorder.DATA_INSTANCE].block_till_done)
client = await hass_client()
response = await client.get(
f"/api/history/period/{dt_util.utcnow().isoformat()}",
)
assert response.status == 200
response_json = await response.json()
assert len(response_json) == 2
assert response_json[0][0]["entity_id"] == "light.cow"
assert response_json[1][0]["entity_id"] == "light.match" | [
"async",
"def",
"test_fetch_period_api_with_entity_glob_exclude",
"(",
"hass",
",",
"hass_client",
")",
":",
"await",
"hass",
".",
"async_add_executor_job",
"(",
"init_recorder_component",
",",
"hass",
")",
"await",
"async_setup_component",
"(",
"hass",
",",
"\"history\"",
",",
"{",
"\"history\"",
":",
"{",
"\"exclude\"",
":",
"{",
"\"entity_globs\"",
":",
"[",
"\"light.k*\"",
"]",
",",
"\"domains\"",
":",
"\"switch\"",
",",
"\"entities\"",
":",
"\"media_player.test\"",
",",
"}",
",",
"}",
"}",
",",
")",
"await",
"hass",
".",
"async_add_executor_job",
"(",
"hass",
".",
"data",
"[",
"recorder",
".",
"DATA_INSTANCE",
"]",
".",
"block_till_done",
")",
"hass",
".",
"states",
".",
"async_set",
"(",
"\"light.kitchen\"",
",",
"\"on\"",
")",
"hass",
".",
"states",
".",
"async_set",
"(",
"\"light.cow\"",
",",
"\"on\"",
")",
"hass",
".",
"states",
".",
"async_set",
"(",
"\"light.match\"",
",",
"\"on\"",
")",
"hass",
".",
"states",
".",
"async_set",
"(",
"\"switch.match\"",
",",
"\"on\"",
")",
"hass",
".",
"states",
".",
"async_set",
"(",
"\"media_player.test\"",
",",
"\"on\"",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"await",
"hass",
".",
"async_add_executor_job",
"(",
"trigger_db_commit",
",",
"hass",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"await",
"hass",
".",
"async_add_executor_job",
"(",
"hass",
".",
"data",
"[",
"recorder",
".",
"DATA_INSTANCE",
"]",
".",
"block_till_done",
")",
"client",
"=",
"await",
"hass_client",
"(",
")",
"response",
"=",
"await",
"client",
".",
"get",
"(",
"f\"/api/history/period/{dt_util.utcnow().isoformat()}\"",
",",
")",
"assert",
"response",
".",
"status",
"==",
"200",
"response_json",
"=",
"await",
"response",
".",
"json",
"(",
")",
"assert",
"len",
"(",
"response_json",
")",
"==",
"2",
"assert",
"response_json",
"[",
"0",
"]",
"[",
"0",
"]",
"[",
"\"entity_id\"",
"]",
"==",
"\"light.cow\"",
"assert",
"response_json",
"[",
"1",
"]",
"[",
"0",
"]",
"[",
"\"entity_id\"",
"]",
"==",
"\"light.match\""
] | [
859,
0
] | [
896,
60
] | python | en | ['en', 'en', 'en'] | True |
test_fetch_period_api_with_entity_glob_include_and_exclude | (hass, hass_client) | Test the fetch period view for history. | Test the fetch period view for history. | async def test_fetch_period_api_with_entity_glob_include_and_exclude(hass, hass_client):
"""Test the fetch period view for history."""
await hass.async_add_executor_job(init_recorder_component, hass)
await async_setup_component(
hass,
"history",
{
"history": {
"exclude": {
"entity_globs": ["light.many*"],
},
"include": {
"entity_globs": ["light.m*"],
"domains": "switch",
"entities": "media_player.test",
},
}
},
)
await hass.async_add_executor_job(hass.data[recorder.DATA_INSTANCE].block_till_done)
hass.states.async_set("light.kitchen", "on")
hass.states.async_set("light.cow", "on")
hass.states.async_set("light.match", "on")
hass.states.async_set("light.many_state_changes", "on")
hass.states.async_set("switch.match", "on")
hass.states.async_set("media_player.test", "on")
await hass.async_block_till_done()
await hass.async_add_executor_job(trigger_db_commit, hass)
await hass.async_block_till_done()
await hass.async_add_executor_job(hass.data[recorder.DATA_INSTANCE].block_till_done)
client = await hass_client()
response = await client.get(
f"/api/history/period/{dt_util.utcnow().isoformat()}",
)
assert response.status == 200
response_json = await response.json()
assert len(response_json) == 3
assert response_json[0][0]["entity_id"] == "light.match"
assert response_json[1][0]["entity_id"] == "media_player.test"
assert response_json[2][0]["entity_id"] == "switch.match" | [
"async",
"def",
"test_fetch_period_api_with_entity_glob_include_and_exclude",
"(",
"hass",
",",
"hass_client",
")",
":",
"await",
"hass",
".",
"async_add_executor_job",
"(",
"init_recorder_component",
",",
"hass",
")",
"await",
"async_setup_component",
"(",
"hass",
",",
"\"history\"",
",",
"{",
"\"history\"",
":",
"{",
"\"exclude\"",
":",
"{",
"\"entity_globs\"",
":",
"[",
"\"light.many*\"",
"]",
",",
"}",
",",
"\"include\"",
":",
"{",
"\"entity_globs\"",
":",
"[",
"\"light.m*\"",
"]",
",",
"\"domains\"",
":",
"\"switch\"",
",",
"\"entities\"",
":",
"\"media_player.test\"",
",",
"}",
",",
"}",
"}",
",",
")",
"await",
"hass",
".",
"async_add_executor_job",
"(",
"hass",
".",
"data",
"[",
"recorder",
".",
"DATA_INSTANCE",
"]",
".",
"block_till_done",
")",
"hass",
".",
"states",
".",
"async_set",
"(",
"\"light.kitchen\"",
",",
"\"on\"",
")",
"hass",
".",
"states",
".",
"async_set",
"(",
"\"light.cow\"",
",",
"\"on\"",
")",
"hass",
".",
"states",
".",
"async_set",
"(",
"\"light.match\"",
",",
"\"on\"",
")",
"hass",
".",
"states",
".",
"async_set",
"(",
"\"light.many_state_changes\"",
",",
"\"on\"",
")",
"hass",
".",
"states",
".",
"async_set",
"(",
"\"switch.match\"",
",",
"\"on\"",
")",
"hass",
".",
"states",
".",
"async_set",
"(",
"\"media_player.test\"",
",",
"\"on\"",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"await",
"hass",
".",
"async_add_executor_job",
"(",
"trigger_db_commit",
",",
"hass",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"await",
"hass",
".",
"async_add_executor_job",
"(",
"hass",
".",
"data",
"[",
"recorder",
".",
"DATA_INSTANCE",
"]",
".",
"block_till_done",
")",
"client",
"=",
"await",
"hass_client",
"(",
")",
"response",
"=",
"await",
"client",
".",
"get",
"(",
"f\"/api/history/period/{dt_util.utcnow().isoformat()}\"",
",",
")",
"assert",
"response",
".",
"status",
"==",
"200",
"response_json",
"=",
"await",
"response",
".",
"json",
"(",
")",
"assert",
"len",
"(",
"response_json",
")",
"==",
"3",
"assert",
"response_json",
"[",
"0",
"]",
"[",
"0",
"]",
"[",
"\"entity_id\"",
"]",
"==",
"\"light.match\"",
"assert",
"response_json",
"[",
"1",
"]",
"[",
"0",
"]",
"[",
"\"entity_id\"",
"]",
"==",
"\"media_player.test\"",
"assert",
"response_json",
"[",
"2",
"]",
"[",
"0",
"]",
"[",
"\"entity_id\"",
"]",
"==",
"\"switch.match\""
] | [
899,
0
] | [
941,
61
] | python | en | ['en', 'en', 'en'] | True |
test_entity_ids_limit_via_api | (hass, hass_client) | Test limiting history to entity_ids. | Test limiting history to entity_ids. | async def test_entity_ids_limit_via_api(hass, hass_client):
"""Test limiting history to entity_ids."""
await hass.async_add_executor_job(init_recorder_component, hass)
await async_setup_component(
hass,
"history",
{"history": {}},
)
await hass.async_add_executor_job(hass.data[recorder.DATA_INSTANCE].block_till_done)
hass.states.async_set("light.kitchen", "on")
hass.states.async_set("light.cow", "on")
hass.states.async_set("light.nomatch", "on")
await hass.async_block_till_done()
await hass.async_add_executor_job(trigger_db_commit, hass)
await hass.async_block_till_done()
await hass.async_add_executor_job(hass.data[recorder.DATA_INSTANCE].block_till_done)
client = await hass_client()
response = await client.get(
f"/api/history/period/{dt_util.utcnow().isoformat()}?filter_entity_id=light.kitchen,light.cow",
)
assert response.status == 200
response_json = await response.json()
assert len(response_json) == 2
assert response_json[0][0]["entity_id"] == "light.kitchen"
assert response_json[1][0]["entity_id"] == "light.cow" | [
"async",
"def",
"test_entity_ids_limit_via_api",
"(",
"hass",
",",
"hass_client",
")",
":",
"await",
"hass",
".",
"async_add_executor_job",
"(",
"init_recorder_component",
",",
"hass",
")",
"await",
"async_setup_component",
"(",
"hass",
",",
"\"history\"",
",",
"{",
"\"history\"",
":",
"{",
"}",
"}",
",",
")",
"await",
"hass",
".",
"async_add_executor_job",
"(",
"hass",
".",
"data",
"[",
"recorder",
".",
"DATA_INSTANCE",
"]",
".",
"block_till_done",
")",
"hass",
".",
"states",
".",
"async_set",
"(",
"\"light.kitchen\"",
",",
"\"on\"",
")",
"hass",
".",
"states",
".",
"async_set",
"(",
"\"light.cow\"",
",",
"\"on\"",
")",
"hass",
".",
"states",
".",
"async_set",
"(",
"\"light.nomatch\"",
",",
"\"on\"",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"await",
"hass",
".",
"async_add_executor_job",
"(",
"trigger_db_commit",
",",
"hass",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"await",
"hass",
".",
"async_add_executor_job",
"(",
"hass",
".",
"data",
"[",
"recorder",
".",
"DATA_INSTANCE",
"]",
".",
"block_till_done",
")",
"client",
"=",
"await",
"hass_client",
"(",
")",
"response",
"=",
"await",
"client",
".",
"get",
"(",
"f\"/api/history/period/{dt_util.utcnow().isoformat()}?filter_entity_id=light.kitchen,light.cow\"",
",",
")",
"assert",
"response",
".",
"status",
"==",
"200",
"response_json",
"=",
"await",
"response",
".",
"json",
"(",
")",
"assert",
"len",
"(",
"response_json",
")",
"==",
"2",
"assert",
"response_json",
"[",
"0",
"]",
"[",
"0",
"]",
"[",
"\"entity_id\"",
"]",
"==",
"\"light.kitchen\"",
"assert",
"response_json",
"[",
"1",
"]",
"[",
"0",
"]",
"[",
"\"entity_id\"",
"]",
"==",
"\"light.cow\""
] | [
944,
0
] | [
971,
58
] | python | en | ['en', 'en', 'en'] | True |
test_entity_ids_limit_via_api_with_skip_initial_state | (hass, hass_client) | Test limiting history to entity_ids with skip_initial_state. | Test limiting history to entity_ids with skip_initial_state. | async def test_entity_ids_limit_via_api_with_skip_initial_state(hass, hass_client):
"""Test limiting history to entity_ids with skip_initial_state."""
await hass.async_add_executor_job(init_recorder_component, hass)
await async_setup_component(
hass,
"history",
{"history": {}},
)
await hass.async_add_executor_job(hass.data[recorder.DATA_INSTANCE].block_till_done)
hass.states.async_set("light.kitchen", "on")
hass.states.async_set("light.cow", "on")
hass.states.async_set("light.nomatch", "on")
await hass.async_block_till_done()
await hass.async_add_executor_job(trigger_db_commit, hass)
await hass.async_block_till_done()
await hass.async_add_executor_job(hass.data[recorder.DATA_INSTANCE].block_till_done)
client = await hass_client()
response = await client.get(
f"/api/history/period/{dt_util.utcnow().isoformat()}?filter_entity_id=light.kitchen,light.cow&skip_initial_state",
)
assert response.status == 200
response_json = await response.json()
assert len(response_json) == 0
when = dt_util.utcnow() - timedelta(minutes=1)
response = await client.get(
f"/api/history/period/{when.isoformat()}?filter_entity_id=light.kitchen,light.cow&skip_initial_state",
)
assert response.status == 200
response_json = await response.json()
assert len(response_json) == 2
assert response_json[0][0]["entity_id"] == "light.kitchen"
assert response_json[1][0]["entity_id"] == "light.cow" | [
"async",
"def",
"test_entity_ids_limit_via_api_with_skip_initial_state",
"(",
"hass",
",",
"hass_client",
")",
":",
"await",
"hass",
".",
"async_add_executor_job",
"(",
"init_recorder_component",
",",
"hass",
")",
"await",
"async_setup_component",
"(",
"hass",
",",
"\"history\"",
",",
"{",
"\"history\"",
":",
"{",
"}",
"}",
",",
")",
"await",
"hass",
".",
"async_add_executor_job",
"(",
"hass",
".",
"data",
"[",
"recorder",
".",
"DATA_INSTANCE",
"]",
".",
"block_till_done",
")",
"hass",
".",
"states",
".",
"async_set",
"(",
"\"light.kitchen\"",
",",
"\"on\"",
")",
"hass",
".",
"states",
".",
"async_set",
"(",
"\"light.cow\"",
",",
"\"on\"",
")",
"hass",
".",
"states",
".",
"async_set",
"(",
"\"light.nomatch\"",
",",
"\"on\"",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"await",
"hass",
".",
"async_add_executor_job",
"(",
"trigger_db_commit",
",",
"hass",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"await",
"hass",
".",
"async_add_executor_job",
"(",
"hass",
".",
"data",
"[",
"recorder",
".",
"DATA_INSTANCE",
"]",
".",
"block_till_done",
")",
"client",
"=",
"await",
"hass_client",
"(",
")",
"response",
"=",
"await",
"client",
".",
"get",
"(",
"f\"/api/history/period/{dt_util.utcnow().isoformat()}?filter_entity_id=light.kitchen,light.cow&skip_initial_state\"",
",",
")",
"assert",
"response",
".",
"status",
"==",
"200",
"response_json",
"=",
"await",
"response",
".",
"json",
"(",
")",
"assert",
"len",
"(",
"response_json",
")",
"==",
"0",
"when",
"=",
"dt_util",
".",
"utcnow",
"(",
")",
"-",
"timedelta",
"(",
"minutes",
"=",
"1",
")",
"response",
"=",
"await",
"client",
".",
"get",
"(",
"f\"/api/history/period/{when.isoformat()}?filter_entity_id=light.kitchen,light.cow&skip_initial_state\"",
",",
")",
"assert",
"response",
".",
"status",
"==",
"200",
"response_json",
"=",
"await",
"response",
".",
"json",
"(",
")",
"assert",
"len",
"(",
"response_json",
")",
"==",
"2",
"assert",
"response_json",
"[",
"0",
"]",
"[",
"0",
"]",
"[",
"\"entity_id\"",
"]",
"==",
"\"light.kitchen\"",
"assert",
"response_json",
"[",
"1",
"]",
"[",
"0",
"]",
"[",
"\"entity_id\"",
"]",
"==",
"\"light.cow\""
] | [
974,
0
] | [
1009,
58
] | python | en | ['en', 'en', 'en'] | True |
TestComponentHistory.setUp | (self) | Set up things to be run when tests are started. | Set up things to be run when tests are started. | def setUp(self): # pylint: disable=invalid-name
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
self.addCleanup(self.tear_down_cleanup) | [
"def",
"setUp",
"(",
"self",
")",
":",
"# pylint: disable=invalid-name",
"self",
".",
"hass",
"=",
"get_test_home_assistant",
"(",
")",
"self",
".",
"addCleanup",
"(",
"self",
".",
"tear_down_cleanup",
")"
] | [
26,
4
] | [
29,
47
] | python | en | ['en', 'en', 'en'] | True |
TestComponentHistory.tear_down_cleanup | (self) | Stop everything that was started. | Stop everything that was started. | def tear_down_cleanup(self):
"""Stop everything that was started."""
self.hass.stop() | [
"def",
"tear_down_cleanup",
"(",
"self",
")",
":",
"self",
".",
"hass",
".",
"stop",
"(",
")"
] | [
31,
4
] | [
33,
24
] | python | en | ['en', 'en', 'en'] | True |
TestComponentHistory.init_recorder | (self) | Initialize the recorder. | Initialize the recorder. | def init_recorder(self):
"""Initialize the recorder."""
init_recorder_component(self.hass)
self.hass.start()
wait_recording_done(self.hass) | [
"def",
"init_recorder",
"(",
"self",
")",
":",
"init_recorder_component",
"(",
"self",
".",
"hass",
")",
"self",
".",
"hass",
".",
"start",
"(",
")",
"wait_recording_done",
"(",
"self",
".",
"hass",
")"
] | [
35,
4
] | [
39,
38
] | python | en | ['en', 'en', 'en'] | True |
TestComponentHistory.test_setup | (self) | Test setup method of history. | Test setup method of history. | def test_setup(self):
"""Test setup method of history."""
config = history.CONFIG_SCHEMA(
{
# ha.DOMAIN: {},
history.DOMAIN: {
history.CONF_INCLUDE: {
history.CONF_DOMAINS: ["media_player"],
history.CONF_ENTITIES: ["thermostat.test"],
},
history.CONF_EXCLUDE: {
history.CONF_DOMAINS: ["thermostat"],
history.CONF_ENTITIES: ["media_player.test"],
},
}
}
)
self.init_recorder()
assert setup_component(self.hass, history.DOMAIN, config) | [
"def",
"test_setup",
"(",
"self",
")",
":",
"config",
"=",
"history",
".",
"CONFIG_SCHEMA",
"(",
"{",
"# ha.DOMAIN: {},",
"history",
".",
"DOMAIN",
":",
"{",
"history",
".",
"CONF_INCLUDE",
":",
"{",
"history",
".",
"CONF_DOMAINS",
":",
"[",
"\"media_player\"",
"]",
",",
"history",
".",
"CONF_ENTITIES",
":",
"[",
"\"thermostat.test\"",
"]",
",",
"}",
",",
"history",
".",
"CONF_EXCLUDE",
":",
"{",
"history",
".",
"CONF_DOMAINS",
":",
"[",
"\"thermostat\"",
"]",
",",
"history",
".",
"CONF_ENTITIES",
":",
"[",
"\"media_player.test\"",
"]",
",",
"}",
",",
"}",
"}",
")",
"self",
".",
"init_recorder",
"(",
")",
"assert",
"setup_component",
"(",
"self",
".",
"hass",
",",
"history",
".",
"DOMAIN",
",",
"config",
")"
] | [
41,
4
] | [
59,
65
] | python | en | ['en', 'et', 'en'] | True |
TestComponentHistory.test_get_states | (self) | Test getting states at a specific point in time. | Test getting states at a specific point in time. | def test_get_states(self):
"""Test getting states at a specific point in time."""
self.test_setup()
states = []
now = dt_util.utcnow()
with patch(
"homeassistant.components.recorder.dt_util.utcnow", return_value=now
):
for i in range(5):
state = ha.State(
"test.point_in_time_{}".format(i % 5),
f"State {i}",
{"attribute_test": i},
)
mock_state_change_event(self.hass, state)
states.append(state)
wait_recording_done(self.hass)
future = now + timedelta(seconds=1)
with patch(
"homeassistant.components.recorder.dt_util.utcnow", return_value=future
):
for i in range(5):
state = ha.State(
"test.point_in_time_{}".format(i % 5),
f"State {i}",
{"attribute_test": i},
)
mock_state_change_event(self.hass, state)
wait_recording_done(self.hass)
# Get states returns everything before POINT
for state1, state2 in zip(
states,
sorted(
history.get_states(self.hass, future), key=lambda state: state.entity_id
),
):
assert state1 == state2
# Test get_state here because we have a DB setup
assert states[0] == history.get_state(self.hass, future, states[0].entity_id)
time_before_recorder_ran = now - timedelta(days=1000)
assert history.get_states(self.hass, time_before_recorder_ran) == []
assert history.get_state(self.hass, time_before_recorder_ran, "demo.id") is None | [
"def",
"test_get_states",
"(",
"self",
")",
":",
"self",
".",
"test_setup",
"(",
")",
"states",
"=",
"[",
"]",
"now",
"=",
"dt_util",
".",
"utcnow",
"(",
")",
"with",
"patch",
"(",
"\"homeassistant.components.recorder.dt_util.utcnow\"",
",",
"return_value",
"=",
"now",
")",
":",
"for",
"i",
"in",
"range",
"(",
"5",
")",
":",
"state",
"=",
"ha",
".",
"State",
"(",
"\"test.point_in_time_{}\"",
".",
"format",
"(",
"i",
"%",
"5",
")",
",",
"f\"State {i}\"",
",",
"{",
"\"attribute_test\"",
":",
"i",
"}",
",",
")",
"mock_state_change_event",
"(",
"self",
".",
"hass",
",",
"state",
")",
"states",
".",
"append",
"(",
"state",
")",
"wait_recording_done",
"(",
"self",
".",
"hass",
")",
"future",
"=",
"now",
"+",
"timedelta",
"(",
"seconds",
"=",
"1",
")",
"with",
"patch",
"(",
"\"homeassistant.components.recorder.dt_util.utcnow\"",
",",
"return_value",
"=",
"future",
")",
":",
"for",
"i",
"in",
"range",
"(",
"5",
")",
":",
"state",
"=",
"ha",
".",
"State",
"(",
"\"test.point_in_time_{}\"",
".",
"format",
"(",
"i",
"%",
"5",
")",
",",
"f\"State {i}\"",
",",
"{",
"\"attribute_test\"",
":",
"i",
"}",
",",
")",
"mock_state_change_event",
"(",
"self",
".",
"hass",
",",
"state",
")",
"wait_recording_done",
"(",
"self",
".",
"hass",
")",
"# Get states returns everything before POINT",
"for",
"state1",
",",
"state2",
"in",
"zip",
"(",
"states",
",",
"sorted",
"(",
"history",
".",
"get_states",
"(",
"self",
".",
"hass",
",",
"future",
")",
",",
"key",
"=",
"lambda",
"state",
":",
"state",
".",
"entity_id",
")",
",",
")",
":",
"assert",
"state1",
"==",
"state2",
"# Test get_state here because we have a DB setup",
"assert",
"states",
"[",
"0",
"]",
"==",
"history",
".",
"get_state",
"(",
"self",
".",
"hass",
",",
"future",
",",
"states",
"[",
"0",
"]",
".",
"entity_id",
")",
"time_before_recorder_ran",
"=",
"now",
"-",
"timedelta",
"(",
"days",
"=",
"1000",
")",
"assert",
"history",
".",
"get_states",
"(",
"self",
".",
"hass",
",",
"time_before_recorder_ran",
")",
"==",
"[",
"]",
"assert",
"history",
".",
"get_state",
"(",
"self",
".",
"hass",
",",
"time_before_recorder_ran",
",",
"\"demo.id\"",
")",
"is",
"None"
] | [
61,
4
] | [
113,
88
] | python | en | ['en', 'en', 'en'] | True |
TestComponentHistory.test_state_changes_during_period | (self) | Test state change during period. | Test state change during period. | def test_state_changes_during_period(self):
"""Test state change during period."""
self.test_setup()
entity_id = "media_player.test"
def set_state(state):
"""Set the state."""
self.hass.states.set(entity_id, state)
wait_recording_done(self.hass)
return self.hass.states.get(entity_id)
start = dt_util.utcnow()
point = start + timedelta(seconds=1)
end = point + timedelta(seconds=1)
with patch(
"homeassistant.components.recorder.dt_util.utcnow", return_value=start
):
set_state("idle")
set_state("YouTube")
with patch(
"homeassistant.components.recorder.dt_util.utcnow", return_value=point
):
states = [
set_state("idle"),
set_state("Netflix"),
set_state("Plex"),
set_state("YouTube"),
]
with patch(
"homeassistant.components.recorder.dt_util.utcnow", return_value=end
):
set_state("Netflix")
set_state("Plex")
hist = history.state_changes_during_period(self.hass, start, end, entity_id)
assert states == hist[entity_id] | [
"def",
"test_state_changes_during_period",
"(",
"self",
")",
":",
"self",
".",
"test_setup",
"(",
")",
"entity_id",
"=",
"\"media_player.test\"",
"def",
"set_state",
"(",
"state",
")",
":",
"\"\"\"Set the state.\"\"\"",
"self",
".",
"hass",
".",
"states",
".",
"set",
"(",
"entity_id",
",",
"state",
")",
"wait_recording_done",
"(",
"self",
".",
"hass",
")",
"return",
"self",
".",
"hass",
".",
"states",
".",
"get",
"(",
"entity_id",
")",
"start",
"=",
"dt_util",
".",
"utcnow",
"(",
")",
"point",
"=",
"start",
"+",
"timedelta",
"(",
"seconds",
"=",
"1",
")",
"end",
"=",
"point",
"+",
"timedelta",
"(",
"seconds",
"=",
"1",
")",
"with",
"patch",
"(",
"\"homeassistant.components.recorder.dt_util.utcnow\"",
",",
"return_value",
"=",
"start",
")",
":",
"set_state",
"(",
"\"idle\"",
")",
"set_state",
"(",
"\"YouTube\"",
")",
"with",
"patch",
"(",
"\"homeassistant.components.recorder.dt_util.utcnow\"",
",",
"return_value",
"=",
"point",
")",
":",
"states",
"=",
"[",
"set_state",
"(",
"\"idle\"",
")",
",",
"set_state",
"(",
"\"Netflix\"",
")",
",",
"set_state",
"(",
"\"Plex\"",
")",
",",
"set_state",
"(",
"\"YouTube\"",
")",
",",
"]",
"with",
"patch",
"(",
"\"homeassistant.components.recorder.dt_util.utcnow\"",
",",
"return_value",
"=",
"end",
")",
":",
"set_state",
"(",
"\"Netflix\"",
")",
"set_state",
"(",
"\"Plex\"",
")",
"hist",
"=",
"history",
".",
"state_changes_during_period",
"(",
"self",
".",
"hass",
",",
"start",
",",
"end",
",",
"entity_id",
")",
"assert",
"states",
"==",
"hist",
"[",
"entity_id",
"]"
] | [
115,
4
] | [
154,
40
] | python | en | ['fr', 'en', 'en'] | True |
TestComponentHistory.test_get_last_state_changes | (self) | Test number of state changes. | Test number of state changes. | def test_get_last_state_changes(self):
"""Test number of state changes."""
self.test_setup()
entity_id = "sensor.test"
def set_state(state):
"""Set the state."""
self.hass.states.set(entity_id, state)
wait_recording_done(self.hass)
return self.hass.states.get(entity_id)
start = dt_util.utcnow() - timedelta(minutes=2)
point = start + timedelta(minutes=1)
point2 = point + timedelta(minutes=1)
with patch(
"homeassistant.components.recorder.dt_util.utcnow", return_value=start
):
set_state("1")
states = []
with patch(
"homeassistant.components.recorder.dt_util.utcnow", return_value=point
):
states.append(set_state("2"))
with patch(
"homeassistant.components.recorder.dt_util.utcnow", return_value=point2
):
states.append(set_state("3"))
hist = history.get_last_state_changes(self.hass, 2, entity_id)
assert states == hist[entity_id] | [
"def",
"test_get_last_state_changes",
"(",
"self",
")",
":",
"self",
".",
"test_setup",
"(",
")",
"entity_id",
"=",
"\"sensor.test\"",
"def",
"set_state",
"(",
"state",
")",
":",
"\"\"\"Set the state.\"\"\"",
"self",
".",
"hass",
".",
"states",
".",
"set",
"(",
"entity_id",
",",
"state",
")",
"wait_recording_done",
"(",
"self",
".",
"hass",
")",
"return",
"self",
".",
"hass",
".",
"states",
".",
"get",
"(",
"entity_id",
")",
"start",
"=",
"dt_util",
".",
"utcnow",
"(",
")",
"-",
"timedelta",
"(",
"minutes",
"=",
"2",
")",
"point",
"=",
"start",
"+",
"timedelta",
"(",
"minutes",
"=",
"1",
")",
"point2",
"=",
"point",
"+",
"timedelta",
"(",
"minutes",
"=",
"1",
")",
"with",
"patch",
"(",
"\"homeassistant.components.recorder.dt_util.utcnow\"",
",",
"return_value",
"=",
"start",
")",
":",
"set_state",
"(",
"\"1\"",
")",
"states",
"=",
"[",
"]",
"with",
"patch",
"(",
"\"homeassistant.components.recorder.dt_util.utcnow\"",
",",
"return_value",
"=",
"point",
")",
":",
"states",
".",
"append",
"(",
"set_state",
"(",
"\"2\"",
")",
")",
"with",
"patch",
"(",
"\"homeassistant.components.recorder.dt_util.utcnow\"",
",",
"return_value",
"=",
"point2",
")",
":",
"states",
".",
"append",
"(",
"set_state",
"(",
"\"3\"",
")",
")",
"hist",
"=",
"history",
".",
"get_last_state_changes",
"(",
"self",
".",
"hass",
",",
"2",
",",
"entity_id",
")",
"assert",
"states",
"==",
"hist",
"[",
"entity_id",
"]"
] | [
156,
4
] | [
189,
40
] | python | en | ['en', 'en', 'en'] | True |
TestComponentHistory.test_ensure_state_can_be_copied | (self) | Ensure a state can pass though copy().
The filter integration uses copy() on states
from history.
| Ensure a state can pass though copy(). | def test_ensure_state_can_be_copied(self):
"""Ensure a state can pass though copy().
The filter integration uses copy() on states
from history.
"""
self.test_setup()
entity_id = "sensor.test"
def set_state(state):
"""Set the state."""
self.hass.states.set(entity_id, state)
wait_recording_done(self.hass)
return self.hass.states.get(entity_id)
start = dt_util.utcnow() - timedelta(minutes=2)
point = start + timedelta(minutes=1)
with patch(
"homeassistant.components.recorder.dt_util.utcnow", return_value=start
):
set_state("1")
with patch(
"homeassistant.components.recorder.dt_util.utcnow", return_value=point
):
set_state("2")
hist = history.get_last_state_changes(self.hass, 2, entity_id)
assert copy(hist[entity_id][0]) == hist[entity_id][0]
assert copy(hist[entity_id][1]) == hist[entity_id][1] | [
"def",
"test_ensure_state_can_be_copied",
"(",
"self",
")",
":",
"self",
".",
"test_setup",
"(",
")",
"entity_id",
"=",
"\"sensor.test\"",
"def",
"set_state",
"(",
"state",
")",
":",
"\"\"\"Set the state.\"\"\"",
"self",
".",
"hass",
".",
"states",
".",
"set",
"(",
"entity_id",
",",
"state",
")",
"wait_recording_done",
"(",
"self",
".",
"hass",
")",
"return",
"self",
".",
"hass",
".",
"states",
".",
"get",
"(",
"entity_id",
")",
"start",
"=",
"dt_util",
".",
"utcnow",
"(",
")",
"-",
"timedelta",
"(",
"minutes",
"=",
"2",
")",
"point",
"=",
"start",
"+",
"timedelta",
"(",
"minutes",
"=",
"1",
")",
"with",
"patch",
"(",
"\"homeassistant.components.recorder.dt_util.utcnow\"",
",",
"return_value",
"=",
"start",
")",
":",
"set_state",
"(",
"\"1\"",
")",
"with",
"patch",
"(",
"\"homeassistant.components.recorder.dt_util.utcnow\"",
",",
"return_value",
"=",
"point",
")",
":",
"set_state",
"(",
"\"2\"",
")",
"hist",
"=",
"history",
".",
"get_last_state_changes",
"(",
"self",
".",
"hass",
",",
"2",
",",
"entity_id",
")",
"assert",
"copy",
"(",
"hist",
"[",
"entity_id",
"]",
"[",
"0",
"]",
")",
"==",
"hist",
"[",
"entity_id",
"]",
"[",
"0",
"]",
"assert",
"copy",
"(",
"hist",
"[",
"entity_id",
"]",
"[",
"1",
"]",
")",
"==",
"hist",
"[",
"entity_id",
"]",
"[",
"1",
"]"
] | [
191,
4
] | [
222,
61
] | python | en | ['en', 'en', 'en'] | True |
TestComponentHistory.test_get_significant_states | (self) | Test that only significant states are returned.
We should get back every thermostat change that
includes an attribute change, but only the state updates for
media player (attribute changes are not significant and not returned).
| Test that only significant states are returned. | def test_get_significant_states(self):
"""Test that only significant states are returned.
We should get back every thermostat change that
includes an attribute change, but only the state updates for
media player (attribute changes are not significant and not returned).
"""
zero, four, states = self.record_states()
hist = history.get_significant_states(
self.hass, zero, four, filters=history.Filters()
)
assert states == hist | [
"def",
"test_get_significant_states",
"(",
"self",
")",
":",
"zero",
",",
"four",
",",
"states",
"=",
"self",
".",
"record_states",
"(",
")",
"hist",
"=",
"history",
".",
"get_significant_states",
"(",
"self",
".",
"hass",
",",
"zero",
",",
"four",
",",
"filters",
"=",
"history",
".",
"Filters",
"(",
")",
")",
"assert",
"states",
"==",
"hist"
] | [
224,
4
] | [
235,
29
] | python | en | ['en', 'en', 'en'] | True |
TestComponentHistory.test_get_significant_states_minimal_response | (self) | Test that only significant states are returned.
When minimal responses is set only the first and
last states return a complete state.
We should get back every thermostat change that
includes an attribute change, but only the state updates for
media player (attribute changes are not significant and not returned).
| Test that only significant states are returned. | def test_get_significant_states_minimal_response(self):
"""Test that only significant states are returned.
When minimal responses is set only the first and
last states return a complete state.
We should get back every thermostat change that
includes an attribute change, but only the state updates for
media player (attribute changes are not significant and not returned).
"""
zero, four, states = self.record_states()
hist = history.get_significant_states(
self.hass, zero, four, filters=history.Filters(), minimal_response=True
)
# The second media_player.test state is reduced
# down to last_changed and state when minimal_response
# is set. We use JSONEncoder to make sure that are
# pre-encoded last_changed is always the same as what
# will happen with encoding a native state
input_state = states["media_player.test"][1]
orig_last_changed = json.dumps(
process_timestamp(input_state.last_changed),
cls=JSONEncoder,
).replace('"', "")
orig_state = input_state.state
states["media_player.test"][1] = {
"last_changed": orig_last_changed,
"state": orig_state,
}
assert states == hist | [
"def",
"test_get_significant_states_minimal_response",
"(",
"self",
")",
":",
"zero",
",",
"four",
",",
"states",
"=",
"self",
".",
"record_states",
"(",
")",
"hist",
"=",
"history",
".",
"get_significant_states",
"(",
"self",
".",
"hass",
",",
"zero",
",",
"four",
",",
"filters",
"=",
"history",
".",
"Filters",
"(",
")",
",",
"minimal_response",
"=",
"True",
")",
"# The second media_player.test state is reduced",
"# down to last_changed and state when minimal_response",
"# is set. We use JSONEncoder to make sure that are",
"# pre-encoded last_changed is always the same as what",
"# will happen with encoding a native state",
"input_state",
"=",
"states",
"[",
"\"media_player.test\"",
"]",
"[",
"1",
"]",
"orig_last_changed",
"=",
"json",
".",
"dumps",
"(",
"process_timestamp",
"(",
"input_state",
".",
"last_changed",
")",
",",
"cls",
"=",
"JSONEncoder",
",",
")",
".",
"replace",
"(",
"'\"'",
",",
"\"\"",
")",
"orig_state",
"=",
"input_state",
".",
"state",
"states",
"[",
"\"media_player.test\"",
"]",
"[",
"1",
"]",
"=",
"{",
"\"last_changed\"",
":",
"orig_last_changed",
",",
"\"state\"",
":",
"orig_state",
",",
"}",
"assert",
"states",
"==",
"hist"
] | [
237,
4
] | [
268,
29
] | python | en | ['en', 'en', 'en'] | True |
TestComponentHistory.test_get_significant_states_with_initial | (self) | Test that only significant states are returned.
We should get back every thermostat change that
includes an attribute change, but only the state updates for
media player (attribute changes are not significant and not returned).
| Test that only significant states are returned. | def test_get_significant_states_with_initial(self):
"""Test that only significant states are returned.
We should get back every thermostat change that
includes an attribute change, but only the state updates for
media player (attribute changes are not significant and not returned).
"""
zero, four, states = self.record_states()
one = zero + timedelta(seconds=1)
one_and_half = zero + timedelta(seconds=1.5)
for entity_id in states:
if entity_id == "media_player.test":
states[entity_id] = states[entity_id][1:]
for state in states[entity_id]:
if state.last_changed == one:
state.last_changed = one_and_half
hist = history.get_significant_states(
self.hass,
one_and_half,
four,
filters=history.Filters(),
include_start_time_state=True,
)
assert states == hist | [
"def",
"test_get_significant_states_with_initial",
"(",
"self",
")",
":",
"zero",
",",
"four",
",",
"states",
"=",
"self",
".",
"record_states",
"(",
")",
"one",
"=",
"zero",
"+",
"timedelta",
"(",
"seconds",
"=",
"1",
")",
"one_and_half",
"=",
"zero",
"+",
"timedelta",
"(",
"seconds",
"=",
"1.5",
")",
"for",
"entity_id",
"in",
"states",
":",
"if",
"entity_id",
"==",
"\"media_player.test\"",
":",
"states",
"[",
"entity_id",
"]",
"=",
"states",
"[",
"entity_id",
"]",
"[",
"1",
":",
"]",
"for",
"state",
"in",
"states",
"[",
"entity_id",
"]",
":",
"if",
"state",
".",
"last_changed",
"==",
"one",
":",
"state",
".",
"last_changed",
"=",
"one_and_half",
"hist",
"=",
"history",
".",
"get_significant_states",
"(",
"self",
".",
"hass",
",",
"one_and_half",
",",
"four",
",",
"filters",
"=",
"history",
".",
"Filters",
"(",
")",
",",
"include_start_time_state",
"=",
"True",
",",
")",
"assert",
"states",
"==",
"hist"
] | [
270,
4
] | [
294,
29
] | python | en | ['en', 'en', 'en'] | True |
TestComponentHistory.test_get_significant_states_without_initial | (self) | Test that only significant states are returned.
We should get back every thermostat change that
includes an attribute change, but only the state updates for
media player (attribute changes are not significant and not returned).
| Test that only significant states are returned. | def test_get_significant_states_without_initial(self):
"""Test that only significant states are returned.
We should get back every thermostat change that
includes an attribute change, but only the state updates for
media player (attribute changes are not significant and not returned).
"""
zero, four, states = self.record_states()
one = zero + timedelta(seconds=1)
one_and_half = zero + timedelta(seconds=1.5)
for entity_id in states:
states[entity_id] = list(
filter(lambda s: s.last_changed != one, states[entity_id])
)
del states["media_player.test2"]
hist = history.get_significant_states(
self.hass,
one_and_half,
four,
filters=history.Filters(),
include_start_time_state=False,
)
assert states == hist | [
"def",
"test_get_significant_states_without_initial",
"(",
"self",
")",
":",
"zero",
",",
"four",
",",
"states",
"=",
"self",
".",
"record_states",
"(",
")",
"one",
"=",
"zero",
"+",
"timedelta",
"(",
"seconds",
"=",
"1",
")",
"one_and_half",
"=",
"zero",
"+",
"timedelta",
"(",
"seconds",
"=",
"1.5",
")",
"for",
"entity_id",
"in",
"states",
":",
"states",
"[",
"entity_id",
"]",
"=",
"list",
"(",
"filter",
"(",
"lambda",
"s",
":",
"s",
".",
"last_changed",
"!=",
"one",
",",
"states",
"[",
"entity_id",
"]",
")",
")",
"del",
"states",
"[",
"\"media_player.test2\"",
"]",
"hist",
"=",
"history",
".",
"get_significant_states",
"(",
"self",
".",
"hass",
",",
"one_and_half",
",",
"four",
",",
"filters",
"=",
"history",
".",
"Filters",
"(",
")",
",",
"include_start_time_state",
"=",
"False",
",",
")",
"assert",
"states",
"==",
"hist"
] | [
296,
4
] | [
319,
29
] | python | en | ['en', 'en', 'en'] | True |
TestComponentHistory.test_get_significant_states_entity_id | (self) | Test that only significant states are returned for one entity. | Test that only significant states are returned for one entity. | def test_get_significant_states_entity_id(self):
"""Test that only significant states are returned for one entity."""
zero, four, states = self.record_states()
del states["media_player.test2"]
del states["media_player.test3"]
del states["thermostat.test"]
del states["thermostat.test2"]
del states["script.can_cancel_this_one"]
hist = history.get_significant_states(
self.hass, zero, four, ["media_player.test"], filters=history.Filters()
)
assert states == hist | [
"def",
"test_get_significant_states_entity_id",
"(",
"self",
")",
":",
"zero",
",",
"four",
",",
"states",
"=",
"self",
".",
"record_states",
"(",
")",
"del",
"states",
"[",
"\"media_player.test2\"",
"]",
"del",
"states",
"[",
"\"media_player.test3\"",
"]",
"del",
"states",
"[",
"\"thermostat.test\"",
"]",
"del",
"states",
"[",
"\"thermostat.test2\"",
"]",
"del",
"states",
"[",
"\"script.can_cancel_this_one\"",
"]",
"hist",
"=",
"history",
".",
"get_significant_states",
"(",
"self",
".",
"hass",
",",
"zero",
",",
"four",
",",
"[",
"\"media_player.test\"",
"]",
",",
"filters",
"=",
"history",
".",
"Filters",
"(",
")",
")",
"assert",
"states",
"==",
"hist"
] | [
321,
4
] | [
333,
29
] | python | en | ['en', 'en', 'en'] | True |
TestComponentHistory.test_get_significant_states_multiple_entity_ids | (self) | Test that only significant states are returned for one entity. | Test that only significant states are returned for one entity. | def test_get_significant_states_multiple_entity_ids(self):
"""Test that only significant states are returned for one entity."""
zero, four, states = self.record_states()
del states["media_player.test2"]
del states["media_player.test3"]
del states["thermostat.test2"]
del states["script.can_cancel_this_one"]
hist = history.get_significant_states(
self.hass,
zero,
four,
["media_player.test", "thermostat.test"],
filters=history.Filters(),
)
assert states == hist | [
"def",
"test_get_significant_states_multiple_entity_ids",
"(",
"self",
")",
":",
"zero",
",",
"four",
",",
"states",
"=",
"self",
".",
"record_states",
"(",
")",
"del",
"states",
"[",
"\"media_player.test2\"",
"]",
"del",
"states",
"[",
"\"media_player.test3\"",
"]",
"del",
"states",
"[",
"\"thermostat.test2\"",
"]",
"del",
"states",
"[",
"\"script.can_cancel_this_one\"",
"]",
"hist",
"=",
"history",
".",
"get_significant_states",
"(",
"self",
".",
"hass",
",",
"zero",
",",
"four",
",",
"[",
"\"media_player.test\"",
",",
"\"thermostat.test\"",
"]",
",",
"filters",
"=",
"history",
".",
"Filters",
"(",
")",
",",
")",
"assert",
"states",
"==",
"hist"
] | [
335,
4
] | [
350,
29
] | python | en | ['en', 'en', 'en'] | True |
TestComponentHistory.test_get_significant_states_exclude_domain | (self) | Test if significant states are returned when excluding domains.
We should get back every thermostat change that includes an attribute
change, but no media player changes.
| Test if significant states are returned when excluding domains. | def test_get_significant_states_exclude_domain(self):
"""Test if significant states are returned when excluding domains.
We should get back every thermostat change that includes an attribute
change, but no media player changes.
"""
zero, four, states = self.record_states()
del states["media_player.test"]
del states["media_player.test2"]
del states["media_player.test3"]
config = history.CONFIG_SCHEMA(
{
ha.DOMAIN: {},
history.DOMAIN: {
history.CONF_EXCLUDE: {history.CONF_DOMAINS: ["media_player"]}
},
}
)
self.check_significant_states(zero, four, states, config) | [
"def",
"test_get_significant_states_exclude_domain",
"(",
"self",
")",
":",
"zero",
",",
"four",
",",
"states",
"=",
"self",
".",
"record_states",
"(",
")",
"del",
"states",
"[",
"\"media_player.test\"",
"]",
"del",
"states",
"[",
"\"media_player.test2\"",
"]",
"del",
"states",
"[",
"\"media_player.test3\"",
"]",
"config",
"=",
"history",
".",
"CONFIG_SCHEMA",
"(",
"{",
"ha",
".",
"DOMAIN",
":",
"{",
"}",
",",
"history",
".",
"DOMAIN",
":",
"{",
"history",
".",
"CONF_EXCLUDE",
":",
"{",
"history",
".",
"CONF_DOMAINS",
":",
"[",
"\"media_player\"",
"]",
"}",
"}",
",",
"}",
")",
"self",
".",
"check_significant_states",
"(",
"zero",
",",
"four",
",",
"states",
",",
"config",
")"
] | [
352,
4
] | [
371,
65
] | python | en | ['en', 'en', 'en'] | True |
TestComponentHistory.test_get_significant_states_exclude_entity | (self) | Test if significant states are returned when excluding entities.
We should get back every thermostat and script changes, but no media
player changes.
| Test if significant states are returned when excluding entities. | def test_get_significant_states_exclude_entity(self):
"""Test if significant states are returned when excluding entities.
We should get back every thermostat and script changes, but no media
player changes.
"""
zero, four, states = self.record_states()
del states["media_player.test"]
config = history.CONFIG_SCHEMA(
{
ha.DOMAIN: {},
history.DOMAIN: {
history.CONF_EXCLUDE: {history.CONF_ENTITIES: ["media_player.test"]}
},
}
)
self.check_significant_states(zero, four, states, config) | [
"def",
"test_get_significant_states_exclude_entity",
"(",
"self",
")",
":",
"zero",
",",
"four",
",",
"states",
"=",
"self",
".",
"record_states",
"(",
")",
"del",
"states",
"[",
"\"media_player.test\"",
"]",
"config",
"=",
"history",
".",
"CONFIG_SCHEMA",
"(",
"{",
"ha",
".",
"DOMAIN",
":",
"{",
"}",
",",
"history",
".",
"DOMAIN",
":",
"{",
"history",
".",
"CONF_EXCLUDE",
":",
"{",
"history",
".",
"CONF_ENTITIES",
":",
"[",
"\"media_player.test\"",
"]",
"}",
"}",
",",
"}",
")",
"self",
".",
"check_significant_states",
"(",
"zero",
",",
"four",
",",
"states",
",",
"config",
")"
] | [
373,
4
] | [
390,
65
] | python | en | ['en', 'en', 'en'] | True |
TestComponentHistory.test_get_significant_states_exclude | (self) | Test significant states when excluding entities and domains.
We should not get back every thermostat and media player test changes.
| Test significant states when excluding entities and domains. | def test_get_significant_states_exclude(self):
"""Test significant states when excluding entities and domains.
We should not get back every thermostat and media player test changes.
"""
zero, four, states = self.record_states()
del states["media_player.test"]
del states["thermostat.test"]
del states["thermostat.test2"]
config = history.CONFIG_SCHEMA(
{
ha.DOMAIN: {},
history.DOMAIN: {
history.CONF_EXCLUDE: {
history.CONF_DOMAINS: ["thermostat"],
history.CONF_ENTITIES: ["media_player.test"],
}
},
}
)
self.check_significant_states(zero, four, states, config) | [
"def",
"test_get_significant_states_exclude",
"(",
"self",
")",
":",
"zero",
",",
"four",
",",
"states",
"=",
"self",
".",
"record_states",
"(",
")",
"del",
"states",
"[",
"\"media_player.test\"",
"]",
"del",
"states",
"[",
"\"thermostat.test\"",
"]",
"del",
"states",
"[",
"\"thermostat.test2\"",
"]",
"config",
"=",
"history",
".",
"CONFIG_SCHEMA",
"(",
"{",
"ha",
".",
"DOMAIN",
":",
"{",
"}",
",",
"history",
".",
"DOMAIN",
":",
"{",
"history",
".",
"CONF_EXCLUDE",
":",
"{",
"history",
".",
"CONF_DOMAINS",
":",
"[",
"\"thermostat\"",
"]",
",",
"history",
".",
"CONF_ENTITIES",
":",
"[",
"\"media_player.test\"",
"]",
",",
"}",
"}",
",",
"}",
")",
"self",
".",
"check_significant_states",
"(",
"zero",
",",
"four",
",",
"states",
",",
"config",
")"
] | [
392,
4
] | [
413,
65
] | python | en | ['en', 'en', 'en'] | True |
TestComponentHistory.test_get_significant_states_exclude_include_entity | (self) | Test significant states when excluding domains and include entities.
We should not get back every thermostat and media player test changes.
| Test significant states when excluding domains and include entities. | def test_get_significant_states_exclude_include_entity(self):
"""Test significant states when excluding domains and include entities.
We should not get back every thermostat and media player test changes.
"""
zero, four, states = self.record_states()
del states["media_player.test2"]
del states["media_player.test3"]
del states["thermostat.test"]
del states["thermostat.test2"]
del states["script.can_cancel_this_one"]
config = history.CONFIG_SCHEMA(
{
ha.DOMAIN: {},
history.DOMAIN: {
history.CONF_INCLUDE: {
history.CONF_ENTITIES: ["media_player.test", "thermostat.test"]
},
history.CONF_EXCLUDE: {history.CONF_DOMAINS: ["thermostat"]},
},
}
)
self.check_significant_states(zero, four, states, config) | [
"def",
"test_get_significant_states_exclude_include_entity",
"(",
"self",
")",
":",
"zero",
",",
"four",
",",
"states",
"=",
"self",
".",
"record_states",
"(",
")",
"del",
"states",
"[",
"\"media_player.test2\"",
"]",
"del",
"states",
"[",
"\"media_player.test3\"",
"]",
"del",
"states",
"[",
"\"thermostat.test\"",
"]",
"del",
"states",
"[",
"\"thermostat.test2\"",
"]",
"del",
"states",
"[",
"\"script.can_cancel_this_one\"",
"]",
"config",
"=",
"history",
".",
"CONFIG_SCHEMA",
"(",
"{",
"ha",
".",
"DOMAIN",
":",
"{",
"}",
",",
"history",
".",
"DOMAIN",
":",
"{",
"history",
".",
"CONF_INCLUDE",
":",
"{",
"history",
".",
"CONF_ENTITIES",
":",
"[",
"\"media_player.test\"",
",",
"\"thermostat.test\"",
"]",
"}",
",",
"history",
".",
"CONF_EXCLUDE",
":",
"{",
"history",
".",
"CONF_DOMAINS",
":",
"[",
"\"thermostat\"",
"]",
"}",
",",
"}",
",",
"}",
")",
"self",
".",
"check_significant_states",
"(",
"zero",
",",
"four",
",",
"states",
",",
"config",
")"
] | [
415,
4
] | [
438,
65
] | python | en | ['en', 'en', 'en'] | True |
TestComponentHistory.test_get_significant_states_include_domain | (self) | Test if significant states are returned when including domains.
We should get back every thermostat and script changes, but no media
player changes.
| Test if significant states are returned when including domains. | def test_get_significant_states_include_domain(self):
"""Test if significant states are returned when including domains.
We should get back every thermostat and script changes, but no media
player changes.
"""
zero, four, states = self.record_states()
del states["media_player.test"]
del states["media_player.test2"]
del states["media_player.test3"]
config = history.CONFIG_SCHEMA(
{
ha.DOMAIN: {},
history.DOMAIN: {
history.CONF_INCLUDE: {
history.CONF_DOMAINS: ["thermostat", "script"]
}
},
}
)
self.check_significant_states(zero, four, states, config) | [
"def",
"test_get_significant_states_include_domain",
"(",
"self",
")",
":",
"zero",
",",
"four",
",",
"states",
"=",
"self",
".",
"record_states",
"(",
")",
"del",
"states",
"[",
"\"media_player.test\"",
"]",
"del",
"states",
"[",
"\"media_player.test2\"",
"]",
"del",
"states",
"[",
"\"media_player.test3\"",
"]",
"config",
"=",
"history",
".",
"CONFIG_SCHEMA",
"(",
"{",
"ha",
".",
"DOMAIN",
":",
"{",
"}",
",",
"history",
".",
"DOMAIN",
":",
"{",
"history",
".",
"CONF_INCLUDE",
":",
"{",
"history",
".",
"CONF_DOMAINS",
":",
"[",
"\"thermostat\"",
",",
"\"script\"",
"]",
"}",
"}",
",",
"}",
")",
"self",
".",
"check_significant_states",
"(",
"zero",
",",
"four",
",",
"states",
",",
"config",
")"
] | [
440,
4
] | [
461,
65
] | python | en | ['en', 'en', 'en'] | True |
TestComponentHistory.test_get_significant_states_include_entity | (self) | Test if significant states are returned when including entities.
We should only get back changes of the media_player.test entity.
| Test if significant states are returned when including entities. | def test_get_significant_states_include_entity(self):
"""Test if significant states are returned when including entities.
We should only get back changes of the media_player.test entity.
"""
zero, four, states = self.record_states()
del states["media_player.test2"]
del states["media_player.test3"]
del states["thermostat.test"]
del states["thermostat.test2"]
del states["script.can_cancel_this_one"]
config = history.CONFIG_SCHEMA(
{
ha.DOMAIN: {},
history.DOMAIN: {
history.CONF_INCLUDE: {history.CONF_ENTITIES: ["media_player.test"]}
},
}
)
self.check_significant_states(zero, four, states, config) | [
"def",
"test_get_significant_states_include_entity",
"(",
"self",
")",
":",
"zero",
",",
"four",
",",
"states",
"=",
"self",
".",
"record_states",
"(",
")",
"del",
"states",
"[",
"\"media_player.test2\"",
"]",
"del",
"states",
"[",
"\"media_player.test3\"",
"]",
"del",
"states",
"[",
"\"thermostat.test\"",
"]",
"del",
"states",
"[",
"\"thermostat.test2\"",
"]",
"del",
"states",
"[",
"\"script.can_cancel_this_one\"",
"]",
"config",
"=",
"history",
".",
"CONFIG_SCHEMA",
"(",
"{",
"ha",
".",
"DOMAIN",
":",
"{",
"}",
",",
"history",
".",
"DOMAIN",
":",
"{",
"history",
".",
"CONF_INCLUDE",
":",
"{",
"history",
".",
"CONF_ENTITIES",
":",
"[",
"\"media_player.test\"",
"]",
"}",
"}",
",",
"}",
")",
"self",
".",
"check_significant_states",
"(",
"zero",
",",
"four",
",",
"states",
",",
"config",
")"
] | [
463,
4
] | [
483,
65
] | python | en | ['en', 'en', 'en'] | True |
TestComponentHistory.test_get_significant_states_include | (self) | Test significant states when including domains and entities.
We should only get back changes of the media_player.test entity and the
thermostat domain.
| Test significant states when including domains and entities. | def test_get_significant_states_include(self):
"""Test significant states when including domains and entities.
We should only get back changes of the media_player.test entity and the
thermostat domain.
"""
zero, four, states = self.record_states()
del states["media_player.test2"]
del states["media_player.test3"]
del states["script.can_cancel_this_one"]
config = history.CONFIG_SCHEMA(
{
ha.DOMAIN: {},
history.DOMAIN: {
history.CONF_INCLUDE: {
history.CONF_DOMAINS: ["thermostat"],
history.CONF_ENTITIES: ["media_player.test"],
}
},
}
)
self.check_significant_states(zero, four, states, config) | [
"def",
"test_get_significant_states_include",
"(",
"self",
")",
":",
"zero",
",",
"four",
",",
"states",
"=",
"self",
".",
"record_states",
"(",
")",
"del",
"states",
"[",
"\"media_player.test2\"",
"]",
"del",
"states",
"[",
"\"media_player.test3\"",
"]",
"del",
"states",
"[",
"\"script.can_cancel_this_one\"",
"]",
"config",
"=",
"history",
".",
"CONFIG_SCHEMA",
"(",
"{",
"ha",
".",
"DOMAIN",
":",
"{",
"}",
",",
"history",
".",
"DOMAIN",
":",
"{",
"history",
".",
"CONF_INCLUDE",
":",
"{",
"history",
".",
"CONF_DOMAINS",
":",
"[",
"\"thermostat\"",
"]",
",",
"history",
".",
"CONF_ENTITIES",
":",
"[",
"\"media_player.test\"",
"]",
",",
"}",
"}",
",",
"}",
")",
"self",
".",
"check_significant_states",
"(",
"zero",
",",
"four",
",",
"states",
",",
"config",
")"
] | [
485,
4
] | [
507,
65
] | python | en | ['en', 'en', 'en'] | True |
TestComponentHistory.test_get_significant_states_include_exclude_domain | (self) | Test if significant states when excluding and including domains.
We should not get back any changes since we include only the
media_player domain but also exclude it.
| Test if significant states when excluding and including domains. | def test_get_significant_states_include_exclude_domain(self):
"""Test if significant states when excluding and including domains.
We should not get back any changes since we include only the
media_player domain but also exclude it.
"""
zero, four, states = self.record_states()
del states["media_player.test"]
del states["media_player.test2"]
del states["media_player.test3"]
del states["thermostat.test"]
del states["thermostat.test2"]
del states["script.can_cancel_this_one"]
config = history.CONFIG_SCHEMA(
{
ha.DOMAIN: {},
history.DOMAIN: {
history.CONF_INCLUDE: {history.CONF_DOMAINS: ["media_player"]},
history.CONF_EXCLUDE: {history.CONF_DOMAINS: ["media_player"]},
},
}
)
self.check_significant_states(zero, four, states, config) | [
"def",
"test_get_significant_states_include_exclude_domain",
"(",
"self",
")",
":",
"zero",
",",
"four",
",",
"states",
"=",
"self",
".",
"record_states",
"(",
")",
"del",
"states",
"[",
"\"media_player.test\"",
"]",
"del",
"states",
"[",
"\"media_player.test2\"",
"]",
"del",
"states",
"[",
"\"media_player.test3\"",
"]",
"del",
"states",
"[",
"\"thermostat.test\"",
"]",
"del",
"states",
"[",
"\"thermostat.test2\"",
"]",
"del",
"states",
"[",
"\"script.can_cancel_this_one\"",
"]",
"config",
"=",
"history",
".",
"CONFIG_SCHEMA",
"(",
"{",
"ha",
".",
"DOMAIN",
":",
"{",
"}",
",",
"history",
".",
"DOMAIN",
":",
"{",
"history",
".",
"CONF_INCLUDE",
":",
"{",
"history",
".",
"CONF_DOMAINS",
":",
"[",
"\"media_player\"",
"]",
"}",
",",
"history",
".",
"CONF_EXCLUDE",
":",
"{",
"history",
".",
"CONF_DOMAINS",
":",
"[",
"\"media_player\"",
"]",
"}",
",",
"}",
",",
"}",
")",
"self",
".",
"check_significant_states",
"(",
"zero",
",",
"four",
",",
"states",
",",
"config",
")"
] | [
509,
4
] | [
532,
65
] | python | en | ['en', 'en', 'en'] | True |
TestComponentHistory.test_get_significant_states_include_exclude_entity | (self) | Test if significant states when excluding and including domains.
We should not get back any changes since we include only
media_player.test but also exclude it.
| Test if significant states when excluding and including domains. | def test_get_significant_states_include_exclude_entity(self):
"""Test if significant states when excluding and including domains.
We should not get back any changes since we include only
media_player.test but also exclude it.
"""
zero, four, states = self.record_states()
del states["media_player.test"]
del states["media_player.test2"]
del states["media_player.test3"]
del states["thermostat.test"]
del states["thermostat.test2"]
del states["script.can_cancel_this_one"]
config = history.CONFIG_SCHEMA(
{
ha.DOMAIN: {},
history.DOMAIN: {
history.CONF_INCLUDE: {
history.CONF_ENTITIES: ["media_player.test"]
},
history.CONF_EXCLUDE: {
history.CONF_ENTITIES: ["media_player.test"]
},
},
}
)
self.check_significant_states(zero, four, states, config) | [
"def",
"test_get_significant_states_include_exclude_entity",
"(",
"self",
")",
":",
"zero",
",",
"four",
",",
"states",
"=",
"self",
".",
"record_states",
"(",
")",
"del",
"states",
"[",
"\"media_player.test\"",
"]",
"del",
"states",
"[",
"\"media_player.test2\"",
"]",
"del",
"states",
"[",
"\"media_player.test3\"",
"]",
"del",
"states",
"[",
"\"thermostat.test\"",
"]",
"del",
"states",
"[",
"\"thermostat.test2\"",
"]",
"del",
"states",
"[",
"\"script.can_cancel_this_one\"",
"]",
"config",
"=",
"history",
".",
"CONFIG_SCHEMA",
"(",
"{",
"ha",
".",
"DOMAIN",
":",
"{",
"}",
",",
"history",
".",
"DOMAIN",
":",
"{",
"history",
".",
"CONF_INCLUDE",
":",
"{",
"history",
".",
"CONF_ENTITIES",
":",
"[",
"\"media_player.test\"",
"]",
"}",
",",
"history",
".",
"CONF_EXCLUDE",
":",
"{",
"history",
".",
"CONF_ENTITIES",
":",
"[",
"\"media_player.test\"",
"]",
"}",
",",
"}",
",",
"}",
")",
"self",
".",
"check_significant_states",
"(",
"zero",
",",
"four",
",",
"states",
",",
"config",
")"
] | [
534,
4
] | [
561,
65
] | python | en | ['en', 'en', 'en'] | True |
TestComponentHistory.test_get_significant_states_include_exclude | (self) | Test if significant states when in/excluding domains and entities.
We should only get back changes of the media_player.test2 entity.
| Test if significant states when in/excluding domains and entities. | def test_get_significant_states_include_exclude(self):
"""Test if significant states when in/excluding domains and entities.
We should only get back changes of the media_player.test2 entity.
"""
zero, four, states = self.record_states()
del states["media_player.test"]
del states["thermostat.test"]
del states["thermostat.test2"]
del states["script.can_cancel_this_one"]
config = history.CONFIG_SCHEMA(
{
ha.DOMAIN: {},
history.DOMAIN: {
history.CONF_INCLUDE: {
history.CONF_DOMAINS: ["media_player"],
history.CONF_ENTITIES: ["thermostat.test"],
},
history.CONF_EXCLUDE: {
history.CONF_DOMAINS: ["thermostat"],
history.CONF_ENTITIES: ["media_player.test"],
},
},
}
)
self.check_significant_states(zero, four, states, config) | [
"def",
"test_get_significant_states_include_exclude",
"(",
"self",
")",
":",
"zero",
",",
"four",
",",
"states",
"=",
"self",
".",
"record_states",
"(",
")",
"del",
"states",
"[",
"\"media_player.test\"",
"]",
"del",
"states",
"[",
"\"thermostat.test\"",
"]",
"del",
"states",
"[",
"\"thermostat.test2\"",
"]",
"del",
"states",
"[",
"\"script.can_cancel_this_one\"",
"]",
"config",
"=",
"history",
".",
"CONFIG_SCHEMA",
"(",
"{",
"ha",
".",
"DOMAIN",
":",
"{",
"}",
",",
"history",
".",
"DOMAIN",
":",
"{",
"history",
".",
"CONF_INCLUDE",
":",
"{",
"history",
".",
"CONF_DOMAINS",
":",
"[",
"\"media_player\"",
"]",
",",
"history",
".",
"CONF_ENTITIES",
":",
"[",
"\"thermostat.test\"",
"]",
",",
"}",
",",
"history",
".",
"CONF_EXCLUDE",
":",
"{",
"history",
".",
"CONF_DOMAINS",
":",
"[",
"\"thermostat\"",
"]",
",",
"history",
".",
"CONF_ENTITIES",
":",
"[",
"\"media_player.test\"",
"]",
",",
"}",
",",
"}",
",",
"}",
")",
"self",
".",
"check_significant_states",
"(",
"zero",
",",
"four",
",",
"states",
",",
"config",
")"
] | [
563,
4
] | [
589,
65
] | python | en | ['en', 'en', 'en'] | True |
TestComponentHistory.test_get_significant_states_are_ordered | (self) | Test order of results from get_significant_states.
When entity ids are given, the results should be returned with the data
in the same order.
| Test order of results from get_significant_states. | def test_get_significant_states_are_ordered(self):
"""Test order of results from get_significant_states.
When entity ids are given, the results should be returned with the data
in the same order.
"""
zero, four, states = self.record_states()
entity_ids = ["media_player.test", "media_player.test2"]
hist = history.get_significant_states(
self.hass, zero, four, entity_ids, filters=history.Filters()
)
assert list(hist.keys()) == entity_ids
entity_ids = ["media_player.test2", "media_player.test"]
hist = history.get_significant_states(
self.hass, zero, four, entity_ids, filters=history.Filters()
)
assert list(hist.keys()) == entity_ids | [
"def",
"test_get_significant_states_are_ordered",
"(",
"self",
")",
":",
"zero",
",",
"four",
",",
"states",
"=",
"self",
".",
"record_states",
"(",
")",
"entity_ids",
"=",
"[",
"\"media_player.test\"",
",",
"\"media_player.test2\"",
"]",
"hist",
"=",
"history",
".",
"get_significant_states",
"(",
"self",
".",
"hass",
",",
"zero",
",",
"four",
",",
"entity_ids",
",",
"filters",
"=",
"history",
".",
"Filters",
"(",
")",
")",
"assert",
"list",
"(",
"hist",
".",
"keys",
"(",
")",
")",
"==",
"entity_ids",
"entity_ids",
"=",
"[",
"\"media_player.test2\"",
",",
"\"media_player.test\"",
"]",
"hist",
"=",
"history",
".",
"get_significant_states",
"(",
"self",
".",
"hass",
",",
"zero",
",",
"four",
",",
"entity_ids",
",",
"filters",
"=",
"history",
".",
"Filters",
"(",
")",
")",
"assert",
"list",
"(",
"hist",
".",
"keys",
"(",
")",
")",
"==",
"entity_ids"
] | [
591,
4
] | [
607,
46
] | python | en | ['en', 'en', 'en'] | True |
TestComponentHistory.test_get_significant_states_only | (self) | Test significant states when significant_states_only is set. | Test significant states when significant_states_only is set. | def test_get_significant_states_only(self):
"""Test significant states when significant_states_only is set."""
self.test_setup()
entity_id = "sensor.test"
def set_state(state, **kwargs):
"""Set the state."""
self.hass.states.set(entity_id, state, **kwargs)
wait_recording_done(self.hass)
return self.hass.states.get(entity_id)
start = dt_util.utcnow() - timedelta(minutes=4)
points = []
for i in range(1, 4):
points.append(start + timedelta(minutes=i))
states = []
with patch(
"homeassistant.components.recorder.dt_util.utcnow", return_value=start
):
set_state("123", attributes={"attribute": 10.64})
with patch(
"homeassistant.components.recorder.dt_util.utcnow", return_value=points[0]
):
# Attributes are different, state not
states.append(set_state("123", attributes={"attribute": 21.42}))
with patch(
"homeassistant.components.recorder.dt_util.utcnow", return_value=points[1]
):
# state is different, attributes not
states.append(set_state("32", attributes={"attribute": 21.42}))
with patch(
"homeassistant.components.recorder.dt_util.utcnow", return_value=points[2]
):
# everything is different
states.append(set_state("412", attributes={"attribute": 54.23}))
hist = history.get_significant_states(
self.hass, start, significant_changes_only=True
)
assert len(hist[entity_id]) == 2
assert states[0] not in hist[entity_id]
assert states[1] in hist[entity_id]
assert states[2] in hist[entity_id]
hist = history.get_significant_states(
self.hass, start, significant_changes_only=False
)
assert len(hist[entity_id]) == 3
assert states == hist[entity_id] | [
"def",
"test_get_significant_states_only",
"(",
"self",
")",
":",
"self",
".",
"test_setup",
"(",
")",
"entity_id",
"=",
"\"sensor.test\"",
"def",
"set_state",
"(",
"state",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"Set the state.\"\"\"",
"self",
".",
"hass",
".",
"states",
".",
"set",
"(",
"entity_id",
",",
"state",
",",
"*",
"*",
"kwargs",
")",
"wait_recording_done",
"(",
"self",
".",
"hass",
")",
"return",
"self",
".",
"hass",
".",
"states",
".",
"get",
"(",
"entity_id",
")",
"start",
"=",
"dt_util",
".",
"utcnow",
"(",
")",
"-",
"timedelta",
"(",
"minutes",
"=",
"4",
")",
"points",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"4",
")",
":",
"points",
".",
"append",
"(",
"start",
"+",
"timedelta",
"(",
"minutes",
"=",
"i",
")",
")",
"states",
"=",
"[",
"]",
"with",
"patch",
"(",
"\"homeassistant.components.recorder.dt_util.utcnow\"",
",",
"return_value",
"=",
"start",
")",
":",
"set_state",
"(",
"\"123\"",
",",
"attributes",
"=",
"{",
"\"attribute\"",
":",
"10.64",
"}",
")",
"with",
"patch",
"(",
"\"homeassistant.components.recorder.dt_util.utcnow\"",
",",
"return_value",
"=",
"points",
"[",
"0",
"]",
")",
":",
"# Attributes are different, state not",
"states",
".",
"append",
"(",
"set_state",
"(",
"\"123\"",
",",
"attributes",
"=",
"{",
"\"attribute\"",
":",
"21.42",
"}",
")",
")",
"with",
"patch",
"(",
"\"homeassistant.components.recorder.dt_util.utcnow\"",
",",
"return_value",
"=",
"points",
"[",
"1",
"]",
")",
":",
"# state is different, attributes not",
"states",
".",
"append",
"(",
"set_state",
"(",
"\"32\"",
",",
"attributes",
"=",
"{",
"\"attribute\"",
":",
"21.42",
"}",
")",
")",
"with",
"patch",
"(",
"\"homeassistant.components.recorder.dt_util.utcnow\"",
",",
"return_value",
"=",
"points",
"[",
"2",
"]",
")",
":",
"# everything is different",
"states",
".",
"append",
"(",
"set_state",
"(",
"\"412\"",
",",
"attributes",
"=",
"{",
"\"attribute\"",
":",
"54.23",
"}",
")",
")",
"hist",
"=",
"history",
".",
"get_significant_states",
"(",
"self",
".",
"hass",
",",
"start",
",",
"significant_changes_only",
"=",
"True",
")",
"assert",
"len",
"(",
"hist",
"[",
"entity_id",
"]",
")",
"==",
"2",
"assert",
"states",
"[",
"0",
"]",
"not",
"in",
"hist",
"[",
"entity_id",
"]",
"assert",
"states",
"[",
"1",
"]",
"in",
"hist",
"[",
"entity_id",
"]",
"assert",
"states",
"[",
"2",
"]",
"in",
"hist",
"[",
"entity_id",
"]",
"hist",
"=",
"history",
".",
"get_significant_states",
"(",
"self",
".",
"hass",
",",
"start",
",",
"significant_changes_only",
"=",
"False",
")",
"assert",
"len",
"(",
"hist",
"[",
"entity_id",
"]",
")",
"==",
"3",
"assert",
"states",
"==",
"hist",
"[",
"entity_id",
"]"
] | [
609,
4
] | [
663,
40
] | python | en | ['en', 'en', 'en'] | True |
TestComponentHistory.check_significant_states | (self, zero, four, states, config) | Check if significant states are retrieved. | Check if significant states are retrieved. | def check_significant_states(self, zero, four, states, config):
"""Check if significant states are retrieved."""
filters = history.Filters()
exclude = config[history.DOMAIN].get(history.CONF_EXCLUDE)
if exclude:
filters.excluded_entities = exclude.get(history.CONF_ENTITIES, [])
filters.excluded_domains = exclude.get(history.CONF_DOMAINS, [])
include = config[history.DOMAIN].get(history.CONF_INCLUDE)
if include:
filters.included_entities = include.get(history.CONF_ENTITIES, [])
filters.included_domains = include.get(history.CONF_DOMAINS, [])
hist = history.get_significant_states(self.hass, zero, four, filters=filters)
assert states == hist | [
"def",
"check_significant_states",
"(",
"self",
",",
"zero",
",",
"four",
",",
"states",
",",
"config",
")",
":",
"filters",
"=",
"history",
".",
"Filters",
"(",
")",
"exclude",
"=",
"config",
"[",
"history",
".",
"DOMAIN",
"]",
".",
"get",
"(",
"history",
".",
"CONF_EXCLUDE",
")",
"if",
"exclude",
":",
"filters",
".",
"excluded_entities",
"=",
"exclude",
".",
"get",
"(",
"history",
".",
"CONF_ENTITIES",
",",
"[",
"]",
")",
"filters",
".",
"excluded_domains",
"=",
"exclude",
".",
"get",
"(",
"history",
".",
"CONF_DOMAINS",
",",
"[",
"]",
")",
"include",
"=",
"config",
"[",
"history",
".",
"DOMAIN",
"]",
".",
"get",
"(",
"history",
".",
"CONF_INCLUDE",
")",
"if",
"include",
":",
"filters",
".",
"included_entities",
"=",
"include",
".",
"get",
"(",
"history",
".",
"CONF_ENTITIES",
",",
"[",
"]",
")",
"filters",
".",
"included_domains",
"=",
"include",
".",
"get",
"(",
"history",
".",
"CONF_DOMAINS",
",",
"[",
"]",
")",
"hist",
"=",
"history",
".",
"get_significant_states",
"(",
"self",
".",
"hass",
",",
"zero",
",",
"four",
",",
"filters",
"=",
"filters",
")",
"assert",
"states",
"==",
"hist"
] | [
665,
4
] | [
678,
29
] | python | en | ['en', 'en', 'en'] | True |
TestComponentHistory.record_states | (self) | Record some test states.
We inject a bunch of state updates from media player, zone and
thermostat.
| Record some test states. | def record_states(self):
"""Record some test states.
We inject a bunch of state updates from media player, zone and
thermostat.
"""
self.test_setup()
mp = "media_player.test"
mp2 = "media_player.test2"
mp3 = "media_player.test3"
therm = "thermostat.test"
therm2 = "thermostat.test2"
zone = "zone.home"
script_c = "script.can_cancel_this_one"
def set_state(entity_id, state, **kwargs):
"""Set the state."""
self.hass.states.set(entity_id, state, **kwargs)
wait_recording_done(self.hass)
return self.hass.states.get(entity_id)
zero = dt_util.utcnow()
one = zero + timedelta(seconds=1)
two = one + timedelta(seconds=1)
three = two + timedelta(seconds=1)
four = three + timedelta(seconds=1)
states = {therm: [], therm2: [], mp: [], mp2: [], mp3: [], script_c: []}
with patch(
"homeassistant.components.recorder.dt_util.utcnow", return_value=one
):
states[mp].append(
set_state(mp, "idle", attributes={"media_title": str(sentinel.mt1)})
)
states[mp].append(
set_state(mp, "YouTube", attributes={"media_title": str(sentinel.mt2)})
)
states[mp2].append(
set_state(mp2, "YouTube", attributes={"media_title": str(sentinel.mt2)})
)
states[mp3].append(
set_state(mp3, "idle", attributes={"media_title": str(sentinel.mt1)})
)
states[therm].append(
set_state(therm, 20, attributes={"current_temperature": 19.5})
)
with patch(
"homeassistant.components.recorder.dt_util.utcnow", return_value=two
):
# This state will be skipped only different in time
set_state(mp, "YouTube", attributes={"media_title": str(sentinel.mt3)})
# This state will be skipped because domain is excluded
set_state(zone, "zoning")
states[script_c].append(
set_state(script_c, "off", attributes={"can_cancel": True})
)
states[therm].append(
set_state(therm, 21, attributes={"current_temperature": 19.8})
)
states[therm2].append(
set_state(therm2, 20, attributes={"current_temperature": 19})
)
with patch(
"homeassistant.components.recorder.dt_util.utcnow", return_value=three
):
states[mp].append(
set_state(mp, "Netflix", attributes={"media_title": str(sentinel.mt4)})
)
states[mp3].append(
set_state(mp3, "Netflix", attributes={"media_title": str(sentinel.mt3)})
)
# Attributes changed even though state is the same
states[therm].append(
set_state(therm, 21, attributes={"current_temperature": 20})
)
return zero, four, states | [
"def",
"record_states",
"(",
"self",
")",
":",
"self",
".",
"test_setup",
"(",
")",
"mp",
"=",
"\"media_player.test\"",
"mp2",
"=",
"\"media_player.test2\"",
"mp3",
"=",
"\"media_player.test3\"",
"therm",
"=",
"\"thermostat.test\"",
"therm2",
"=",
"\"thermostat.test2\"",
"zone",
"=",
"\"zone.home\"",
"script_c",
"=",
"\"script.can_cancel_this_one\"",
"def",
"set_state",
"(",
"entity_id",
",",
"state",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"Set the state.\"\"\"",
"self",
".",
"hass",
".",
"states",
".",
"set",
"(",
"entity_id",
",",
"state",
",",
"*",
"*",
"kwargs",
")",
"wait_recording_done",
"(",
"self",
".",
"hass",
")",
"return",
"self",
".",
"hass",
".",
"states",
".",
"get",
"(",
"entity_id",
")",
"zero",
"=",
"dt_util",
".",
"utcnow",
"(",
")",
"one",
"=",
"zero",
"+",
"timedelta",
"(",
"seconds",
"=",
"1",
")",
"two",
"=",
"one",
"+",
"timedelta",
"(",
"seconds",
"=",
"1",
")",
"three",
"=",
"two",
"+",
"timedelta",
"(",
"seconds",
"=",
"1",
")",
"four",
"=",
"three",
"+",
"timedelta",
"(",
"seconds",
"=",
"1",
")",
"states",
"=",
"{",
"therm",
":",
"[",
"]",
",",
"therm2",
":",
"[",
"]",
",",
"mp",
":",
"[",
"]",
",",
"mp2",
":",
"[",
"]",
",",
"mp3",
":",
"[",
"]",
",",
"script_c",
":",
"[",
"]",
"}",
"with",
"patch",
"(",
"\"homeassistant.components.recorder.dt_util.utcnow\"",
",",
"return_value",
"=",
"one",
")",
":",
"states",
"[",
"mp",
"]",
".",
"append",
"(",
"set_state",
"(",
"mp",
",",
"\"idle\"",
",",
"attributes",
"=",
"{",
"\"media_title\"",
":",
"str",
"(",
"sentinel",
".",
"mt1",
")",
"}",
")",
")",
"states",
"[",
"mp",
"]",
".",
"append",
"(",
"set_state",
"(",
"mp",
",",
"\"YouTube\"",
",",
"attributes",
"=",
"{",
"\"media_title\"",
":",
"str",
"(",
"sentinel",
".",
"mt2",
")",
"}",
")",
")",
"states",
"[",
"mp2",
"]",
".",
"append",
"(",
"set_state",
"(",
"mp2",
",",
"\"YouTube\"",
",",
"attributes",
"=",
"{",
"\"media_title\"",
":",
"str",
"(",
"sentinel",
".",
"mt2",
")",
"}",
")",
")",
"states",
"[",
"mp3",
"]",
".",
"append",
"(",
"set_state",
"(",
"mp3",
",",
"\"idle\"",
",",
"attributes",
"=",
"{",
"\"media_title\"",
":",
"str",
"(",
"sentinel",
".",
"mt1",
")",
"}",
")",
")",
"states",
"[",
"therm",
"]",
".",
"append",
"(",
"set_state",
"(",
"therm",
",",
"20",
",",
"attributes",
"=",
"{",
"\"current_temperature\"",
":",
"19.5",
"}",
")",
")",
"with",
"patch",
"(",
"\"homeassistant.components.recorder.dt_util.utcnow\"",
",",
"return_value",
"=",
"two",
")",
":",
"# This state will be skipped only different in time",
"set_state",
"(",
"mp",
",",
"\"YouTube\"",
",",
"attributes",
"=",
"{",
"\"media_title\"",
":",
"str",
"(",
"sentinel",
".",
"mt3",
")",
"}",
")",
"# This state will be skipped because domain is excluded",
"set_state",
"(",
"zone",
",",
"\"zoning\"",
")",
"states",
"[",
"script_c",
"]",
".",
"append",
"(",
"set_state",
"(",
"script_c",
",",
"\"off\"",
",",
"attributes",
"=",
"{",
"\"can_cancel\"",
":",
"True",
"}",
")",
")",
"states",
"[",
"therm",
"]",
".",
"append",
"(",
"set_state",
"(",
"therm",
",",
"21",
",",
"attributes",
"=",
"{",
"\"current_temperature\"",
":",
"19.8",
"}",
")",
")",
"states",
"[",
"therm2",
"]",
".",
"append",
"(",
"set_state",
"(",
"therm2",
",",
"20",
",",
"attributes",
"=",
"{",
"\"current_temperature\"",
":",
"19",
"}",
")",
")",
"with",
"patch",
"(",
"\"homeassistant.components.recorder.dt_util.utcnow\"",
",",
"return_value",
"=",
"three",
")",
":",
"states",
"[",
"mp",
"]",
".",
"append",
"(",
"set_state",
"(",
"mp",
",",
"\"Netflix\"",
",",
"attributes",
"=",
"{",
"\"media_title\"",
":",
"str",
"(",
"sentinel",
".",
"mt4",
")",
"}",
")",
")",
"states",
"[",
"mp3",
"]",
".",
"append",
"(",
"set_state",
"(",
"mp3",
",",
"\"Netflix\"",
",",
"attributes",
"=",
"{",
"\"media_title\"",
":",
"str",
"(",
"sentinel",
".",
"mt3",
")",
"}",
")",
")",
"# Attributes changed even though state is the same",
"states",
"[",
"therm",
"]",
".",
"append",
"(",
"set_state",
"(",
"therm",
",",
"21",
",",
"attributes",
"=",
"{",
"\"current_temperature\"",
":",
"20",
"}",
")",
")",
"return",
"zero",
",",
"four",
",",
"states"
] | [
680,
4
] | [
758,
33
] | python | en | ['en', 'en', 'en'] | True |
IHCDevice.__init__ | (
self, ihc_controller, name, ihc_id: int, info: bool, product=None
) | Initialize IHC attributes. | Initialize IHC attributes. | def __init__(
self, ihc_controller, name, ihc_id: int, info: bool, product=None
) -> None:
"""Initialize IHC attributes."""
self.ihc_controller = ihc_controller
self._name = name
self.ihc_id = ihc_id
self.info = info
if product:
self.ihc_name = product["name"]
self.ihc_note = product["note"]
self.ihc_position = product["position"]
else:
self.ihc_name = ""
self.ihc_note = ""
self.ihc_position = "" | [
"def",
"__init__",
"(",
"self",
",",
"ihc_controller",
",",
"name",
",",
"ihc_id",
":",
"int",
",",
"info",
":",
"bool",
",",
"product",
"=",
"None",
")",
"->",
"None",
":",
"self",
".",
"ihc_controller",
"=",
"ihc_controller",
"self",
".",
"_name",
"=",
"name",
"self",
".",
"ihc_id",
"=",
"ihc_id",
"self",
".",
"info",
"=",
"info",
"if",
"product",
":",
"self",
".",
"ihc_name",
"=",
"product",
"[",
"\"name\"",
"]",
"self",
".",
"ihc_note",
"=",
"product",
"[",
"\"note\"",
"]",
"self",
".",
"ihc_position",
"=",
"product",
"[",
"\"position\"",
"]",
"else",
":",
"self",
".",
"ihc_name",
"=",
"\"\"",
"self",
".",
"ihc_note",
"=",
"\"\"",
"self",
".",
"ihc_position",
"=",
"\"\""
] | [
12,
4
] | [
27,
34
] | python | en | ['en', 'co', 'en'] | True |
IHCDevice.async_added_to_hass | (self) | Add callback for IHC changes. | Add callback for IHC changes. | async def async_added_to_hass(self):
"""Add callback for IHC changes."""
self.ihc_controller.add_notify_event(self.ihc_id, self.on_ihc_change, True) | [
"async",
"def",
"async_added_to_hass",
"(",
"self",
")",
":",
"self",
".",
"ihc_controller",
".",
"add_notify_event",
"(",
"self",
".",
"ihc_id",
",",
"self",
".",
"on_ihc_change",
",",
"True",
")"
] | [
29,
4
] | [
31,
83
] | python | en | ['en', 'en', 'en'] | True |
IHCDevice.should_poll | (self) | No polling needed for IHC devices. | No polling needed for IHC devices. | def should_poll(self) -> bool:
"""No polling needed for IHC devices."""
return False | [
"def",
"should_poll",
"(",
"self",
")",
"->",
"bool",
":",
"return",
"False"
] | [
34,
4
] | [
36,
20
] | python | en | ['en', 'en', 'en'] | True |
IHCDevice.name | (self) | Return the device name. | Return the device name. | def name(self):
"""Return the device name."""
return self._name | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"self",
".",
"_name"
] | [
39,
4
] | [
41,
25
] | python | en | ['en', 'en', 'en'] | True |
IHCDevice.device_state_attributes | (self) | Return the state attributes. | Return the state attributes. | def device_state_attributes(self):
"""Return the state attributes."""
if not self.info:
return {}
return {
"ihc_id": self.ihc_id,
"ihc_name": self.ihc_name,
"ihc_note": self.ihc_note,
"ihc_position": self.ihc_position,
} | [
"def",
"device_state_attributes",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"info",
":",
"return",
"{",
"}",
"return",
"{",
"\"ihc_id\"",
":",
"self",
".",
"ihc_id",
",",
"\"ihc_name\"",
":",
"self",
".",
"ihc_name",
",",
"\"ihc_note\"",
":",
"self",
".",
"ihc_note",
",",
"\"ihc_position\"",
":",
"self",
".",
"ihc_position",
",",
"}"
] | [
44,
4
] | [
53,
9
] | python | en | ['en', 'en', 'en'] | True |
IHCDevice.on_ihc_change | (self, ihc_id, value) | Handle IHC resource change.
Derived classes must overwrite this to do device specific stuff.
| Handle IHC resource change. | def on_ihc_change(self, ihc_id, value):
"""Handle IHC resource change.
Derived classes must overwrite this to do device specific stuff.
"""
raise NotImplementedError | [
"def",
"on_ihc_change",
"(",
"self",
",",
"ihc_id",
",",
"value",
")",
":",
"raise",
"NotImplementedError"
] | [
55,
4
] | [
60,
33
] | python | en | ['en', 'xh', 'en'] | True |
fahrenheit_to_celsius | (fahrenheit: float, interval: bool = False) | Convert a temperature in Fahrenheit to Celsius. | Convert a temperature in Fahrenheit to Celsius. | def fahrenheit_to_celsius(fahrenheit: float, interval: bool = False) -> float:
"""Convert a temperature in Fahrenheit to Celsius."""
if interval:
return fahrenheit / 1.8
return (fahrenheit - 32.0) / 1.8 | [
"def",
"fahrenheit_to_celsius",
"(",
"fahrenheit",
":",
"float",
",",
"interval",
":",
"bool",
"=",
"False",
")",
"->",
"float",
":",
"if",
"interval",
":",
"return",
"fahrenheit",
"/",
"1.8",
"return",
"(",
"fahrenheit",
"-",
"32.0",
")",
"/",
"1.8"
] | [
9,
0
] | [
13,
36
] | python | en | ['en', 'la', 'nl'] | False |
celsius_to_fahrenheit | (celsius: float, interval: bool = False) | Convert a temperature in Celsius to Fahrenheit. | Convert a temperature in Celsius to Fahrenheit. | def celsius_to_fahrenheit(celsius: float, interval: bool = False) -> float:
"""Convert a temperature in Celsius to Fahrenheit."""
if interval:
return celsius * 1.8
return celsius * 1.8 + 32.0 | [
"def",
"celsius_to_fahrenheit",
"(",
"celsius",
":",
"float",
",",
"interval",
":",
"bool",
"=",
"False",
")",
"->",
"float",
":",
"if",
"interval",
":",
"return",
"celsius",
"*",
"1.8",
"return",
"celsius",
"*",
"1.8",
"+",
"32.0"
] | [
16,
0
] | [
20,
31
] | python | en | ['en', 'la', 'nl'] | False |
convert | (
temperature: float, from_unit: str, to_unit: str, interval: bool = False
) | Convert a temperature from one unit to another. | Convert a temperature from one unit to another. | def convert(
temperature: float, from_unit: str, to_unit: str, interval: bool = False
) -> float:
"""Convert a temperature from one unit to another."""
if from_unit not in (TEMP_CELSIUS, TEMP_FAHRENHEIT):
raise ValueError(UNIT_NOT_RECOGNIZED_TEMPLATE.format(from_unit, TEMPERATURE))
if to_unit not in (TEMP_CELSIUS, TEMP_FAHRENHEIT):
raise ValueError(UNIT_NOT_RECOGNIZED_TEMPLATE.format(to_unit, TEMPERATURE))
if from_unit == to_unit:
return temperature
if from_unit == TEMP_CELSIUS:
return celsius_to_fahrenheit(temperature, interval)
return fahrenheit_to_celsius(temperature, interval) | [
"def",
"convert",
"(",
"temperature",
":",
"float",
",",
"from_unit",
":",
"str",
",",
"to_unit",
":",
"str",
",",
"interval",
":",
"bool",
"=",
"False",
")",
"->",
"float",
":",
"if",
"from_unit",
"not",
"in",
"(",
"TEMP_CELSIUS",
",",
"TEMP_FAHRENHEIT",
")",
":",
"raise",
"ValueError",
"(",
"UNIT_NOT_RECOGNIZED_TEMPLATE",
".",
"format",
"(",
"from_unit",
",",
"TEMPERATURE",
")",
")",
"if",
"to_unit",
"not",
"in",
"(",
"TEMP_CELSIUS",
",",
"TEMP_FAHRENHEIT",
")",
":",
"raise",
"ValueError",
"(",
"UNIT_NOT_RECOGNIZED_TEMPLATE",
".",
"format",
"(",
"to_unit",
",",
"TEMPERATURE",
")",
")",
"if",
"from_unit",
"==",
"to_unit",
":",
"return",
"temperature",
"if",
"from_unit",
"==",
"TEMP_CELSIUS",
":",
"return",
"celsius_to_fahrenheit",
"(",
"temperature",
",",
"interval",
")",
"return",
"fahrenheit_to_celsius",
"(",
"temperature",
",",
"interval",
")"
] | [
23,
0
] | [
36,
55
] | python | en | ['en', 'en', 'en'] | True |
test_entity_and_device_attributes | (hass, device_factory) | Test the attributes of the entity are correct. | Test the attributes of the entity are correct. | async def test_entity_and_device_attributes(hass, device_factory):
"""Test the attributes of the entity are correct."""
# Arrange
device = device_factory("Switch_1", [Capability.switch], {Attribute.switch: "on"})
entity_registry = await hass.helpers.entity_registry.async_get_registry()
device_registry = await hass.helpers.device_registry.async_get_registry()
# Act
await setup_platform(hass, SWITCH_DOMAIN, devices=[device])
# Assert
entry = entity_registry.async_get("switch.switch_1")
assert entry
assert entry.unique_id == device.device_id
entry = device_registry.async_get_device({(DOMAIN, device.device_id)}, [])
assert entry
assert entry.name == device.label
assert entry.model == device.device_type_name
assert entry.manufacturer == "Unavailable" | [
"async",
"def",
"test_entity_and_device_attributes",
"(",
"hass",
",",
"device_factory",
")",
":",
"# Arrange",
"device",
"=",
"device_factory",
"(",
"\"Switch_1\"",
",",
"[",
"Capability",
".",
"switch",
"]",
",",
"{",
"Attribute",
".",
"switch",
":",
"\"on\"",
"}",
")",
"entity_registry",
"=",
"await",
"hass",
".",
"helpers",
".",
"entity_registry",
".",
"async_get_registry",
"(",
")",
"device_registry",
"=",
"await",
"hass",
".",
"helpers",
".",
"device_registry",
".",
"async_get_registry",
"(",
")",
"# Act",
"await",
"setup_platform",
"(",
"hass",
",",
"SWITCH_DOMAIN",
",",
"devices",
"=",
"[",
"device",
"]",
")",
"# Assert",
"entry",
"=",
"entity_registry",
".",
"async_get",
"(",
"\"switch.switch_1\"",
")",
"assert",
"entry",
"assert",
"entry",
".",
"unique_id",
"==",
"device",
".",
"device_id",
"entry",
"=",
"device_registry",
".",
"async_get_device",
"(",
"{",
"(",
"DOMAIN",
",",
"device",
".",
"device_id",
")",
"}",
",",
"[",
"]",
")",
"assert",
"entry",
"assert",
"entry",
".",
"name",
"==",
"device",
".",
"label",
"assert",
"entry",
".",
"model",
"==",
"device",
".",
"device_type_name",
"assert",
"entry",
".",
"manufacturer",
"==",
"\"Unavailable\""
] | [
19,
0
] | [
36,
46
] | python | en | ['en', 'en', 'en'] | True |
test_turn_off | (hass, device_factory) | Test the switch turns of successfully. | Test the switch turns of successfully. | async def test_turn_off(hass, device_factory):
"""Test the switch turns of successfully."""
# Arrange
device = device_factory("Switch_1", [Capability.switch], {Attribute.switch: "on"})
await setup_platform(hass, SWITCH_DOMAIN, devices=[device])
# Act
await hass.services.async_call(
"switch", "turn_off", {"entity_id": "switch.switch_1"}, blocking=True
)
# Assert
state = hass.states.get("switch.switch_1")
assert state is not None
assert state.state == "off" | [
"async",
"def",
"test_turn_off",
"(",
"hass",
",",
"device_factory",
")",
":",
"# Arrange",
"device",
"=",
"device_factory",
"(",
"\"Switch_1\"",
",",
"[",
"Capability",
".",
"switch",
"]",
",",
"{",
"Attribute",
".",
"switch",
":",
"\"on\"",
"}",
")",
"await",
"setup_platform",
"(",
"hass",
",",
"SWITCH_DOMAIN",
",",
"devices",
"=",
"[",
"device",
"]",
")",
"# Act",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"\"switch\"",
",",
"\"turn_off\"",
",",
"{",
"\"entity_id\"",
":",
"\"switch.switch_1\"",
"}",
",",
"blocking",
"=",
"True",
")",
"# Assert",
"state",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"\"switch.switch_1\"",
")",
"assert",
"state",
"is",
"not",
"None",
"assert",
"state",
".",
"state",
"==",
"\"off\""
] | [
39,
0
] | [
51,
31
] | python | en | ['en', 'en', 'en'] | True |
test_turn_on | (hass, device_factory) | Test the switch turns of successfully. | Test the switch turns of successfully. | async def test_turn_on(hass, device_factory):
"""Test the switch turns of successfully."""
# Arrange
device = device_factory(
"Switch_1",
[Capability.switch, Capability.power_meter, Capability.energy_meter],
{Attribute.switch: "off", Attribute.power: 355, Attribute.energy: 11.422},
)
await setup_platform(hass, SWITCH_DOMAIN, devices=[device])
# Act
await hass.services.async_call(
"switch", "turn_on", {"entity_id": "switch.switch_1"}, blocking=True
)
# Assert
state = hass.states.get("switch.switch_1")
assert state is not None
assert state.state == "on"
assert state.attributes[ATTR_CURRENT_POWER_W] == 355
assert state.attributes[ATTR_TODAY_ENERGY_KWH] == 11.422 | [
"async",
"def",
"test_turn_on",
"(",
"hass",
",",
"device_factory",
")",
":",
"# Arrange",
"device",
"=",
"device_factory",
"(",
"\"Switch_1\"",
",",
"[",
"Capability",
".",
"switch",
",",
"Capability",
".",
"power_meter",
",",
"Capability",
".",
"energy_meter",
"]",
",",
"{",
"Attribute",
".",
"switch",
":",
"\"off\"",
",",
"Attribute",
".",
"power",
":",
"355",
",",
"Attribute",
".",
"energy",
":",
"11.422",
"}",
",",
")",
"await",
"setup_platform",
"(",
"hass",
",",
"SWITCH_DOMAIN",
",",
"devices",
"=",
"[",
"device",
"]",
")",
"# Act",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"\"switch\"",
",",
"\"turn_on\"",
",",
"{",
"\"entity_id\"",
":",
"\"switch.switch_1\"",
"}",
",",
"blocking",
"=",
"True",
")",
"# Assert",
"state",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"\"switch.switch_1\"",
")",
"assert",
"state",
"is",
"not",
"None",
"assert",
"state",
".",
"state",
"==",
"\"on\"",
"assert",
"state",
".",
"attributes",
"[",
"ATTR_CURRENT_POWER_W",
"]",
"==",
"355",
"assert",
"state",
".",
"attributes",
"[",
"ATTR_TODAY_ENERGY_KWH",
"]",
"==",
"11.422"
] | [
54,
0
] | [
72,
60
] | python | en | ['en', 'en', 'en'] | True |
test_update_from_signal | (hass, device_factory) | Test the switch updates when receiving a signal. | Test the switch updates when receiving a signal. | async def test_update_from_signal(hass, device_factory):
"""Test the switch updates when receiving a signal."""
# Arrange
device = device_factory("Switch_1", [Capability.switch], {Attribute.switch: "off"})
await setup_platform(hass, SWITCH_DOMAIN, devices=[device])
await device.switch_on(True)
# Act
async_dispatcher_send(hass, SIGNAL_SMARTTHINGS_UPDATE, [device.device_id])
# Assert
await hass.async_block_till_done()
state = hass.states.get("switch.switch_1")
assert state is not None
assert state.state == "on" | [
"async",
"def",
"test_update_from_signal",
"(",
"hass",
",",
"device_factory",
")",
":",
"# Arrange",
"device",
"=",
"device_factory",
"(",
"\"Switch_1\"",
",",
"[",
"Capability",
".",
"switch",
"]",
",",
"{",
"Attribute",
".",
"switch",
":",
"\"off\"",
"}",
")",
"await",
"setup_platform",
"(",
"hass",
",",
"SWITCH_DOMAIN",
",",
"devices",
"=",
"[",
"device",
"]",
")",
"await",
"device",
".",
"switch_on",
"(",
"True",
")",
"# Act",
"async_dispatcher_send",
"(",
"hass",
",",
"SIGNAL_SMARTTHINGS_UPDATE",
",",
"[",
"device",
".",
"device_id",
"]",
")",
"# Assert",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"state",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"\"switch.switch_1\"",
")",
"assert",
"state",
"is",
"not",
"None",
"assert",
"state",
".",
"state",
"==",
"\"on\""
] | [
75,
0
] | [
87,
30
] | python | en | ['en', 'en', 'en'] | True |
test_unload_config_entry | (hass, device_factory) | Test the switch is removed when the config entry is unloaded. | Test the switch is removed when the config entry is unloaded. | async def test_unload_config_entry(hass, device_factory):
"""Test the switch is removed when the config entry is unloaded."""
# Arrange
device = device_factory("Switch 1", [Capability.switch], {Attribute.switch: "on"})
config_entry = await setup_platform(hass, SWITCH_DOMAIN, devices=[device])
# Act
await hass.config_entries.async_forward_entry_unload(config_entry, "switch")
# Assert
assert not hass.states.get("switch.switch_1") | [
"async",
"def",
"test_unload_config_entry",
"(",
"hass",
",",
"device_factory",
")",
":",
"# Arrange",
"device",
"=",
"device_factory",
"(",
"\"Switch 1\"",
",",
"[",
"Capability",
".",
"switch",
"]",
",",
"{",
"Attribute",
".",
"switch",
":",
"\"on\"",
"}",
")",
"config_entry",
"=",
"await",
"setup_platform",
"(",
"hass",
",",
"SWITCH_DOMAIN",
",",
"devices",
"=",
"[",
"device",
"]",
")",
"# Act",
"await",
"hass",
".",
"config_entries",
".",
"async_forward_entry_unload",
"(",
"config_entry",
",",
"\"switch\"",
")",
"# Assert",
"assert",
"not",
"hass",
".",
"states",
".",
"get",
"(",
"\"switch.switch_1\"",
")"
] | [
90,
0
] | [
98,
49
] | python | en | ['en', 'en', 'en'] | True |
ids_tensor | (shape, vocab_size, rng=None) | Creates a random int32 tensor of the shape within the vocab size. | Creates a random int32 tensor of the shape within the vocab size. | def ids_tensor(shape, vocab_size, rng=None):
"""Creates a random int32 tensor of the shape within the vocab size."""
if rng is None:
rng = random.Random()
total_dims = 1
for dim in shape:
total_dims *= dim
values = []
for _ in range(total_dims):
values.append(rng.randint(0, vocab_size - 1))
output = np.array(values, dtype=jnp.int32).reshape(shape)
return output | [
"def",
"ids_tensor",
"(",
"shape",
",",
"vocab_size",
",",
"rng",
"=",
"None",
")",
":",
"if",
"rng",
"is",
"None",
":",
"rng",
"=",
"random",
".",
"Random",
"(",
")",
"total_dims",
"=",
"1",
"for",
"dim",
"in",
"shape",
":",
"total_dims",
"*=",
"dim",
"values",
"=",
"[",
"]",
"for",
"_",
"in",
"range",
"(",
"total_dims",
")",
":",
"values",
".",
"append",
"(",
"rng",
".",
"randint",
"(",
"0",
",",
"vocab_size",
"-",
"1",
")",
")",
"output",
"=",
"np",
".",
"array",
"(",
"values",
",",
"dtype",
"=",
"jnp",
".",
"int32",
")",
".",
"reshape",
"(",
"shape",
")",
"return",
"output"
] | [
37,
0
] | [
52,
17
] | python | en | ['en', 'en', 'en'] | True |
mock_transmission_api | () | Mock an api. | Mock an api. | def mock_transmission_api():
"""Mock an api."""
with patch("transmissionrpc.Client"):
yield | [
"def",
"mock_transmission_api",
"(",
")",
":",
"with",
"patch",
"(",
"\"transmissionrpc.Client\"",
")",
":",
"yield"
] | [
47,
0
] | [
50,
13
] | python | en | ['en', 'su', 'en'] | True |
mock_api_authentication_error | () | Mock an api. | Mock an api. | def mock_api_authentication_error():
"""Mock an api."""
with patch(
"transmissionrpc.Client", side_effect=TransmissionError("401: Unauthorized")
):
yield | [
"def",
"mock_api_authentication_error",
"(",
")",
":",
"with",
"patch",
"(",
"\"transmissionrpc.Client\"",
",",
"side_effect",
"=",
"TransmissionError",
"(",
"\"401: Unauthorized\"",
")",
")",
":",
"yield"
] | [
54,
0
] | [
59,
13
] | python | en | ['en', 'su', 'en'] | True |
mock_api_connection_error | () | Mock an api. | Mock an api. | def mock_api_connection_error():
"""Mock an api."""
with patch(
"transmissionrpc.Client",
side_effect=TransmissionError("111: Connection refused"),
):
yield | [
"def",
"mock_api_connection_error",
"(",
")",
":",
"with",
"patch",
"(",
"\"transmissionrpc.Client\"",
",",
"side_effect",
"=",
"TransmissionError",
"(",
"\"111: Connection refused\"",
")",
",",
")",
":",
"yield"
] | [
63,
0
] | [
69,
13
] | python | en | ['en', 'su', 'en'] | True |
mock_api_unknown_error | () | Mock an api. | Mock an api. | def mock_api_unknown_error():
"""Mock an api."""
with patch("transmissionrpc.Client", side_effect=TransmissionError):
yield | [
"def",
"mock_api_unknown_error",
"(",
")",
":",
"with",
"patch",
"(",
"\"transmissionrpc.Client\"",
",",
"side_effect",
"=",
"TransmissionError",
")",
":",
"yield"
] | [
73,
0
] | [
76,
13
] | python | en | ['en', 'su', 'en'] | True |
transmission_setup_fixture | () | Mock transmission entry setup. | Mock transmission entry setup. | def transmission_setup_fixture():
"""Mock transmission entry setup."""
with patch(
"homeassistant.components.transmission.async_setup_entry", return_value=True
):
yield | [
"def",
"transmission_setup_fixture",
"(",
")",
":",
"with",
"patch",
"(",
"\"homeassistant.components.transmission.async_setup_entry\"",
",",
"return_value",
"=",
"True",
")",
":",
"yield"
] | [
80,
0
] | [
85,
13
] | python | en | ['en', 'da', 'en'] | True |
init_config_flow | (hass) | Init a configuration flow. | Init a configuration flow. | def init_config_flow(hass):
"""Init a configuration flow."""
flow = config_flow.TransmissionFlowHandler()
flow.hass = hass
return flow | [
"def",
"init_config_flow",
"(",
"hass",
")",
":",
"flow",
"=",
"config_flow",
".",
"TransmissionFlowHandler",
"(",
")",
"flow",
".",
"hass",
"=",
"hass",
"return",
"flow"
] | [
88,
0
] | [
92,
15
] | python | en | ['es', 'fr', 'en'] | False |
test_flow_user_config | (hass, api) | Test user config. | Test user config. | async def test_flow_user_config(hass, api):
"""Test user config."""
result = await hass.config_entries.flow.async_init(
transmission.DOMAIN, context={"source": "user"}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["step_id"] == "user" | [
"async",
"def",
"test_flow_user_config",
"(",
"hass",
",",
"api",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"transmission",
".",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"\"user\"",
"}",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_FORM",
"assert",
"result",
"[",
"\"step_id\"",
"]",
"==",
"\"user\""
] | [
95,
0
] | [
101,
38
] | python | en | ['en', 'da', 'en'] | True |
test_flow_required_fields | (hass, api) | Test with required fields only. | Test with required fields only. | async def test_flow_required_fields(hass, api):
"""Test with required fields only."""
result = await hass.config_entries.flow.async_init(
transmission.DOMAIN,
context={"source": "user"},
data={CONF_NAME: NAME, CONF_HOST: HOST, CONF_PORT: PORT},
)
assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
assert result["title"] == NAME
assert result["data"][CONF_NAME] == NAME
assert result["data"][CONF_HOST] == HOST
assert result["data"][CONF_PORT] == PORT | [
"async",
"def",
"test_flow_required_fields",
"(",
"hass",
",",
"api",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"transmission",
".",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"\"user\"",
"}",
",",
"data",
"=",
"{",
"CONF_NAME",
":",
"NAME",
",",
"CONF_HOST",
":",
"HOST",
",",
"CONF_PORT",
":",
"PORT",
"}",
",",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_CREATE_ENTRY",
"assert",
"result",
"[",
"\"title\"",
"]",
"==",
"NAME",
"assert",
"result",
"[",
"\"data\"",
"]",
"[",
"CONF_NAME",
"]",
"==",
"NAME",
"assert",
"result",
"[",
"\"data\"",
"]",
"[",
"CONF_HOST",
"]",
"==",
"HOST",
"assert",
"result",
"[",
"\"data\"",
"]",
"[",
"CONF_PORT",
"]",
"==",
"PORT"
] | [
104,
0
] | [
116,
44
] | python | en | ['en', 'en', 'en'] | True |
test_flow_all_provided | (hass, api) | Test with all provided. | Test with all provided. | async def test_flow_all_provided(hass, api):
"""Test with all provided."""
result = await hass.config_entries.flow.async_init(
transmission.DOMAIN, context={"source": "user"}, data=MOCK_ENTRY
)
assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
assert result["title"] == NAME
assert result["data"][CONF_NAME] == NAME
assert result["data"][CONF_HOST] == HOST
assert result["data"][CONF_USERNAME] == USERNAME
assert result["data"][CONF_PASSWORD] == PASSWORD
assert result["data"][CONF_PORT] == PORT | [
"async",
"def",
"test_flow_all_provided",
"(",
"hass",
",",
"api",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"transmission",
".",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"\"user\"",
"}",
",",
"data",
"=",
"MOCK_ENTRY",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_CREATE_ENTRY",
"assert",
"result",
"[",
"\"title\"",
"]",
"==",
"NAME",
"assert",
"result",
"[",
"\"data\"",
"]",
"[",
"CONF_NAME",
"]",
"==",
"NAME",
"assert",
"result",
"[",
"\"data\"",
"]",
"[",
"CONF_HOST",
"]",
"==",
"HOST",
"assert",
"result",
"[",
"\"data\"",
"]",
"[",
"CONF_USERNAME",
"]",
"==",
"USERNAME",
"assert",
"result",
"[",
"\"data\"",
"]",
"[",
"CONF_PASSWORD",
"]",
"==",
"PASSWORD",
"assert",
"result",
"[",
"\"data\"",
"]",
"[",
"CONF_PORT",
"]",
"==",
"PORT"
] | [
119,
0
] | [
131,
44
] | python | en | ['en', 'en', 'en'] | True |
test_options | (hass) | Test updating options. | Test updating options. | async def test_options(hass):
"""Test updating options."""
entry = MockConfigEntry(
domain=transmission.DOMAIN,
title=CONF_NAME,
data=MOCK_ENTRY,
options={CONF_SCAN_INTERVAL: DEFAULT_SCAN_INTERVAL},
)
flow = init_config_flow(hass)
options_flow = flow.async_get_options_flow(entry)
result = await options_flow.async_step_init()
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["step_id"] == "init"
result = await options_flow.async_step_init({CONF_SCAN_INTERVAL: 10})
assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
assert result["data"][CONF_SCAN_INTERVAL] == 10 | [
"async",
"def",
"test_options",
"(",
"hass",
")",
":",
"entry",
"=",
"MockConfigEntry",
"(",
"domain",
"=",
"transmission",
".",
"DOMAIN",
",",
"title",
"=",
"CONF_NAME",
",",
"data",
"=",
"MOCK_ENTRY",
",",
"options",
"=",
"{",
"CONF_SCAN_INTERVAL",
":",
"DEFAULT_SCAN_INTERVAL",
"}",
",",
")",
"flow",
"=",
"init_config_flow",
"(",
"hass",
")",
"options_flow",
"=",
"flow",
".",
"async_get_options_flow",
"(",
"entry",
")",
"result",
"=",
"await",
"options_flow",
".",
"async_step_init",
"(",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_FORM",
"assert",
"result",
"[",
"\"step_id\"",
"]",
"==",
"\"init\"",
"result",
"=",
"await",
"options_flow",
".",
"async_step_init",
"(",
"{",
"CONF_SCAN_INTERVAL",
":",
"10",
"}",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_CREATE_ENTRY",
"assert",
"result",
"[",
"\"data\"",
"]",
"[",
"CONF_SCAN_INTERVAL",
"]",
"==",
"10"
] | [
134,
0
] | [
150,
51
] | python | en | ['en', 'en', 'en'] | True |
test_import | (hass, api) | Test import step. | Test import step. | async def test_import(hass, api):
"""Test import step."""
flow = init_config_flow(hass)
# import with minimum fields only
result = await flow.async_step_import(
{
CONF_NAME: DEFAULT_NAME,
CONF_HOST: HOST,
CONF_PORT: DEFAULT_PORT,
CONF_SCAN_INTERVAL: timedelta(seconds=DEFAULT_SCAN_INTERVAL),
CONF_LIMIT: DEFAULT_LIMIT,
CONF_ORDER: DEFAULT_ORDER,
}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
assert result["title"] == DEFAULT_NAME
assert result["data"][CONF_NAME] == DEFAULT_NAME
assert result["data"][CONF_HOST] == HOST
assert result["data"][CONF_PORT] == DEFAULT_PORT
assert result["data"][CONF_SCAN_INTERVAL] == DEFAULT_SCAN_INTERVAL
# import with all
result = await flow.async_step_import(
{
CONF_NAME: NAME,
CONF_HOST: HOST,
CONF_USERNAME: USERNAME,
CONF_PASSWORD: PASSWORD,
CONF_PORT: PORT,
CONF_SCAN_INTERVAL: timedelta(seconds=SCAN_INTERVAL),
CONF_LIMIT: DEFAULT_LIMIT,
CONF_ORDER: DEFAULT_ORDER,
}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
assert result["title"] == NAME
assert result["data"][CONF_NAME] == NAME
assert result["data"][CONF_HOST] == HOST
assert result["data"][CONF_USERNAME] == USERNAME
assert result["data"][CONF_PASSWORD] == PASSWORD
assert result["data"][CONF_PORT] == PORT
assert result["data"][CONF_SCAN_INTERVAL] == SCAN_INTERVAL | [
"async",
"def",
"test_import",
"(",
"hass",
",",
"api",
")",
":",
"flow",
"=",
"init_config_flow",
"(",
"hass",
")",
"# import with minimum fields only",
"result",
"=",
"await",
"flow",
".",
"async_step_import",
"(",
"{",
"CONF_NAME",
":",
"DEFAULT_NAME",
",",
"CONF_HOST",
":",
"HOST",
",",
"CONF_PORT",
":",
"DEFAULT_PORT",
",",
"CONF_SCAN_INTERVAL",
":",
"timedelta",
"(",
"seconds",
"=",
"DEFAULT_SCAN_INTERVAL",
")",
",",
"CONF_LIMIT",
":",
"DEFAULT_LIMIT",
",",
"CONF_ORDER",
":",
"DEFAULT_ORDER",
",",
"}",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_CREATE_ENTRY",
"assert",
"result",
"[",
"\"title\"",
"]",
"==",
"DEFAULT_NAME",
"assert",
"result",
"[",
"\"data\"",
"]",
"[",
"CONF_NAME",
"]",
"==",
"DEFAULT_NAME",
"assert",
"result",
"[",
"\"data\"",
"]",
"[",
"CONF_HOST",
"]",
"==",
"HOST",
"assert",
"result",
"[",
"\"data\"",
"]",
"[",
"CONF_PORT",
"]",
"==",
"DEFAULT_PORT",
"assert",
"result",
"[",
"\"data\"",
"]",
"[",
"CONF_SCAN_INTERVAL",
"]",
"==",
"DEFAULT_SCAN_INTERVAL",
"# import with all",
"result",
"=",
"await",
"flow",
".",
"async_step_import",
"(",
"{",
"CONF_NAME",
":",
"NAME",
",",
"CONF_HOST",
":",
"HOST",
",",
"CONF_USERNAME",
":",
"USERNAME",
",",
"CONF_PASSWORD",
":",
"PASSWORD",
",",
"CONF_PORT",
":",
"PORT",
",",
"CONF_SCAN_INTERVAL",
":",
"timedelta",
"(",
"seconds",
"=",
"SCAN_INTERVAL",
")",
",",
"CONF_LIMIT",
":",
"DEFAULT_LIMIT",
",",
"CONF_ORDER",
":",
"DEFAULT_ORDER",
",",
"}",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_CREATE_ENTRY",
"assert",
"result",
"[",
"\"title\"",
"]",
"==",
"NAME",
"assert",
"result",
"[",
"\"data\"",
"]",
"[",
"CONF_NAME",
"]",
"==",
"NAME",
"assert",
"result",
"[",
"\"data\"",
"]",
"[",
"CONF_HOST",
"]",
"==",
"HOST",
"assert",
"result",
"[",
"\"data\"",
"]",
"[",
"CONF_USERNAME",
"]",
"==",
"USERNAME",
"assert",
"result",
"[",
"\"data\"",
"]",
"[",
"CONF_PASSWORD",
"]",
"==",
"PASSWORD",
"assert",
"result",
"[",
"\"data\"",
"]",
"[",
"CONF_PORT",
"]",
"==",
"PORT",
"assert",
"result",
"[",
"\"data\"",
"]",
"[",
"CONF_SCAN_INTERVAL",
"]",
"==",
"SCAN_INTERVAL"
] | [
153,
0
] | [
195,
62
] | python | de | ['de', 'sd', 'en'] | False |
test_host_already_configured | (hass, api) | Test host is already configured. | Test host is already configured. | async def test_host_already_configured(hass, api):
"""Test host is already configured."""
entry = MockConfigEntry(
domain=transmission.DOMAIN,
data=MOCK_ENTRY,
options={CONF_SCAN_INTERVAL: DEFAULT_SCAN_INTERVAL},
)
entry.add_to_hass(hass)
mock_entry_unique_name = MOCK_ENTRY.copy()
mock_entry_unique_name[CONF_NAME] = "Transmission 1"
result = await hass.config_entries.flow.async_init(
transmission.DOMAIN, context={"source": "user"}, data=mock_entry_unique_name
)
assert result["type"] == "abort"
assert result["reason"] == "already_configured"
mock_entry_unique_port = MOCK_ENTRY.copy()
mock_entry_unique_port[CONF_PORT] = 9092
mock_entry_unique_port[CONF_NAME] = "Transmission 2"
result = await hass.config_entries.flow.async_init(
transmission.DOMAIN, context={"source": "user"}, data=mock_entry_unique_port
)
assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
mock_entry_unique_host = MOCK_ENTRY.copy()
mock_entry_unique_host[CONF_HOST] = "192.168.1.101"
mock_entry_unique_host[CONF_NAME] = "Transmission 3"
result = await hass.config_entries.flow.async_init(
transmission.DOMAIN, context={"source": "user"}, data=mock_entry_unique_host
)
assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY | [
"async",
"def",
"test_host_already_configured",
"(",
"hass",
",",
"api",
")",
":",
"entry",
"=",
"MockConfigEntry",
"(",
"domain",
"=",
"transmission",
".",
"DOMAIN",
",",
"data",
"=",
"MOCK_ENTRY",
",",
"options",
"=",
"{",
"CONF_SCAN_INTERVAL",
":",
"DEFAULT_SCAN_INTERVAL",
"}",
",",
")",
"entry",
".",
"add_to_hass",
"(",
"hass",
")",
"mock_entry_unique_name",
"=",
"MOCK_ENTRY",
".",
"copy",
"(",
")",
"mock_entry_unique_name",
"[",
"CONF_NAME",
"]",
"=",
"\"Transmission 1\"",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"transmission",
".",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"\"user\"",
"}",
",",
"data",
"=",
"mock_entry_unique_name",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"\"abort\"",
"assert",
"result",
"[",
"\"reason\"",
"]",
"==",
"\"already_configured\"",
"mock_entry_unique_port",
"=",
"MOCK_ENTRY",
".",
"copy",
"(",
")",
"mock_entry_unique_port",
"[",
"CONF_PORT",
"]",
"=",
"9092",
"mock_entry_unique_port",
"[",
"CONF_NAME",
"]",
"=",
"\"Transmission 2\"",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"transmission",
".",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"\"user\"",
"}",
",",
"data",
"=",
"mock_entry_unique_port",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_CREATE_ENTRY",
"mock_entry_unique_host",
"=",
"MOCK_ENTRY",
".",
"copy",
"(",
")",
"mock_entry_unique_host",
"[",
"CONF_HOST",
"]",
"=",
"\"192.168.1.101\"",
"mock_entry_unique_host",
"[",
"CONF_NAME",
"]",
"=",
"\"Transmission 3\"",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"transmission",
".",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"\"user\"",
"}",
",",
"data",
"=",
"mock_entry_unique_host",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_CREATE_ENTRY"
] | [
198,
0
] | [
229,
69
] | python | en | ['en', 'en', 'en'] | True |
test_name_already_configured | (hass, api) | Test name is already configured. | Test name is already configured. | async def test_name_already_configured(hass, api):
"""Test name is already configured."""
entry = MockConfigEntry(
domain=transmission.DOMAIN,
data=MOCK_ENTRY,
options={CONF_SCAN_INTERVAL: DEFAULT_SCAN_INTERVAL},
)
entry.add_to_hass(hass)
mock_entry = MOCK_ENTRY.copy()
mock_entry[CONF_HOST] = "0.0.0.0"
result = await hass.config_entries.flow.async_init(
transmission.DOMAIN, context={"source": "user"}, data=mock_entry
)
assert result["type"] == "form"
assert result["errors"] == {CONF_NAME: "name_exists"} | [
"async",
"def",
"test_name_already_configured",
"(",
"hass",
",",
"api",
")",
":",
"entry",
"=",
"MockConfigEntry",
"(",
"domain",
"=",
"transmission",
".",
"DOMAIN",
",",
"data",
"=",
"MOCK_ENTRY",
",",
"options",
"=",
"{",
"CONF_SCAN_INTERVAL",
":",
"DEFAULT_SCAN_INTERVAL",
"}",
",",
")",
"entry",
".",
"add_to_hass",
"(",
"hass",
")",
"mock_entry",
"=",
"MOCK_ENTRY",
".",
"copy",
"(",
")",
"mock_entry",
"[",
"CONF_HOST",
"]",
"=",
"\"0.0.0.0\"",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"transmission",
".",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"\"user\"",
"}",
",",
"data",
"=",
"mock_entry",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"\"form\"",
"assert",
"result",
"[",
"\"errors\"",
"]",
"==",
"{",
"CONF_NAME",
":",
"\"name_exists\"",
"}"
] | [
232,
0
] | [
248,
57
] | python | en | ['en', 'en', 'en'] | True |
test_error_on_wrong_credentials | (hass, auth_error) | Test with wrong credentials. | Test with wrong credentials. | async def test_error_on_wrong_credentials(hass, auth_error):
"""Test with wrong credentials."""
flow = init_config_flow(hass)
result = await flow.async_step_user(
{
CONF_NAME: NAME,
CONF_HOST: HOST,
CONF_USERNAME: USERNAME,
CONF_PASSWORD: PASSWORD,
CONF_PORT: PORT,
}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["errors"] == {
CONF_USERNAME: "invalid_auth",
CONF_PASSWORD: "invalid_auth",
} | [
"async",
"def",
"test_error_on_wrong_credentials",
"(",
"hass",
",",
"auth_error",
")",
":",
"flow",
"=",
"init_config_flow",
"(",
"hass",
")",
"result",
"=",
"await",
"flow",
".",
"async_step_user",
"(",
"{",
"CONF_NAME",
":",
"NAME",
",",
"CONF_HOST",
":",
"HOST",
",",
"CONF_USERNAME",
":",
"USERNAME",
",",
"CONF_PASSWORD",
":",
"PASSWORD",
",",
"CONF_PORT",
":",
"PORT",
",",
"}",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_FORM",
"assert",
"result",
"[",
"\"errors\"",
"]",
"==",
"{",
"CONF_USERNAME",
":",
"\"invalid_auth\"",
",",
"CONF_PASSWORD",
":",
"\"invalid_auth\"",
",",
"}"
] | [
251,
0
] | [
268,
5
] | python | en | ['en', 'en', 'en'] | True |
test_error_on_connection_failure | (hass, conn_error) | Test when connection to host fails. | Test when connection to host fails. | async def test_error_on_connection_failure(hass, conn_error):
"""Test when connection to host fails."""
flow = init_config_flow(hass)
result = await flow.async_step_user(
{
CONF_NAME: NAME,
CONF_HOST: HOST,
CONF_USERNAME: USERNAME,
CONF_PASSWORD: PASSWORD,
CONF_PORT: PORT,
}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["errors"] == {"base": "cannot_connect"} | [
"async",
"def",
"test_error_on_connection_failure",
"(",
"hass",
",",
"conn_error",
")",
":",
"flow",
"=",
"init_config_flow",
"(",
"hass",
")",
"result",
"=",
"await",
"flow",
".",
"async_step_user",
"(",
"{",
"CONF_NAME",
":",
"NAME",
",",
"CONF_HOST",
":",
"HOST",
",",
"CONF_USERNAME",
":",
"USERNAME",
",",
"CONF_PASSWORD",
":",
"PASSWORD",
",",
"CONF_PORT",
":",
"PORT",
",",
"}",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_FORM",
"assert",
"result",
"[",
"\"errors\"",
"]",
"==",
"{",
"\"base\"",
":",
"\"cannot_connect\"",
"}"
] | [
271,
0
] | [
285,
57
] | python | en | ['en', 'en', 'en'] | True |
test_error_on_unknwon_error | (hass, unknown_error) | Test when connection to host fails. | Test when connection to host fails. | async def test_error_on_unknwon_error(hass, unknown_error):
"""Test when connection to host fails."""
flow = init_config_flow(hass)
result = await flow.async_step_user(
{
CONF_NAME: NAME,
CONF_HOST: HOST,
CONF_USERNAME: USERNAME,
CONF_PASSWORD: PASSWORD,
CONF_PORT: PORT,
}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["errors"] == {"base": "cannot_connect"} | [
"async",
"def",
"test_error_on_unknwon_error",
"(",
"hass",
",",
"unknown_error",
")",
":",
"flow",
"=",
"init_config_flow",
"(",
"hass",
")",
"result",
"=",
"await",
"flow",
".",
"async_step_user",
"(",
"{",
"CONF_NAME",
":",
"NAME",
",",
"CONF_HOST",
":",
"HOST",
",",
"CONF_USERNAME",
":",
"USERNAME",
",",
"CONF_PASSWORD",
":",
"PASSWORD",
",",
"CONF_PORT",
":",
"PORT",
",",
"}",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_FORM",
"assert",
"result",
"[",
"\"errors\"",
"]",
"==",
"{",
"\"base\"",
":",
"\"cannot_connect\"",
"}"
] | [
288,
0
] | [
302,
57
] | python | en | ['en', 'en', 'en'] | True |
RetriBertPreTrainedModel._init_weights | (self, module) | Initialize the weights | Initialize the weights | def _init_weights(self, module):
""" Initialize the weights """
if isinstance(module, nn.Linear):
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
if module.bias is not None:
module.bias.data.zero_()
elif isinstance(module, nn.Embedding):
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
if module.padding_idx is not None:
module.weight.data[module.padding_idx].zero_()
elif isinstance(module, nn.LayerNorm):
module.bias.data.zero_()
module.weight.data.fill_(1.0) | [
"def",
"_init_weights",
"(",
"self",
",",
"module",
")",
":",
"if",
"isinstance",
"(",
"module",
",",
"nn",
".",
"Linear",
")",
":",
"module",
".",
"weight",
".",
"data",
".",
"normal_",
"(",
"mean",
"=",
"0.0",
",",
"std",
"=",
"self",
".",
"config",
".",
"initializer_range",
")",
"if",
"module",
".",
"bias",
"is",
"not",
"None",
":",
"module",
".",
"bias",
".",
"data",
".",
"zero_",
"(",
")",
"elif",
"isinstance",
"(",
"module",
",",
"nn",
".",
"Embedding",
")",
":",
"module",
".",
"weight",
".",
"data",
".",
"normal_",
"(",
"mean",
"=",
"0.0",
",",
"std",
"=",
"self",
".",
"config",
".",
"initializer_range",
")",
"if",
"module",
".",
"padding_idx",
"is",
"not",
"None",
":",
"module",
".",
"weight",
".",
"data",
"[",
"module",
".",
"padding_idx",
"]",
".",
"zero_",
"(",
")",
"elif",
"isinstance",
"(",
"module",
",",
"nn",
".",
"LayerNorm",
")",
":",
"module",
".",
"bias",
".",
"data",
".",
"zero_",
"(",
")",
"module",
".",
"weight",
".",
"data",
".",
"fill_",
"(",
"1.0",
")"
] | [
51,
4
] | [
63,
41
] | python | en | ['en', 'en', 'en'] | True |
VmSchedulingBusinessEngine.configs | (self) | dict: Current configuration. | dict: Current configuration. | def configs(self) -> dict:
"""dict: Current configuration."""
return self._config | [
"def",
"configs",
"(",
"self",
")",
"->",
"dict",
":",
"return",
"self",
".",
"_config"
] | [
94,
4
] | [
96,
27
] | python | en | ['en', 'la', 'en'] | True |
VmSchedulingBusinessEngine.frame | (self) | FrameBase: Current frame. | FrameBase: Current frame. | def frame(self) -> FrameBase:
"""FrameBase: Current frame."""
return self._frame | [
"def",
"frame",
"(",
"self",
")",
"->",
"FrameBase",
":",
"return",
"self",
".",
"_frame"
] | [
99,
4
] | [
101,
26
] | python | en | ['en', 'no', 'en'] | True |
VmSchedulingBusinessEngine.snapshots | (self) | SnapshotList: Current snapshot list. | SnapshotList: Current snapshot list. | def snapshots(self) -> SnapshotList:
"""SnapshotList: Current snapshot list."""
return self._snapshots | [
"def",
"snapshots",
"(",
"self",
")",
"->",
"SnapshotList",
":",
"return",
"self",
".",
"_snapshots"
] | [
104,
4
] | [
106,
30
] | python | en | ['en', 'de', 'en'] | True |
VmSchedulingBusinessEngine._load_configs | (self) | Load configurations. | Load configurations. | def _load_configs(self):
"""Load configurations."""
# Update self._config_path with current file path.
self.update_config_root_path(__file__)
with open(os.path.join(self._config_path, "config.yml")) as fp:
self._config = convert_dottable(safe_load(fp))
self._delay_duration: int = self._config.DELAY_DURATION
self._buffer_time_budget: int = self._config.BUFFER_TIME_BUDGET
self._ticks_per_hour: float = self._config.TICKS_PER_HOUR
# Oversubscription rate.
self._max_cpu_oversubscription_rate: float = self._config.MAX_CPU_OVERSUBSCRIPTION_RATE
self._max_memory_oversubscription_rate: float = self._config.MAX_MEM_OVERSUBSCRIPTION_RATE
self._max_utilization_rate: float = self._config.MAX_UTILIZATION_RATE
# Price parameters
self._price_per_cpu_cores_per_hour: float = self._config.PRICE_PER_CPU_CORES_PER_HOUR
self._price_per_memory_per_hour: float = self._config.PRICE_PER_MEMORY_PER_HOUR
self._unit_energy_price_per_kwh: float = self._config.UNIT_ENERGY_PRICE_PER_KWH
self._power_usage_efficiency: float = self._config.POWER_USAGE_EFFICIENCY
# Load PM related configs.
self._region_amount: int = sum(
len(item) for item in self._find_item(key="region", dictionary=self._config.architecture)
)
self._zone_amount: int = sum(
len(item) for item in self._find_item(key="zone", dictionary=self._config.architecture)
)
self._data_center_amount: int = sum(
len(item) for item in self._find_item(key="data_center", dictionary=self._config.architecture)
)
# Cluster amount dict.
cluster_amount_dict = {}
for cluster_list in self._find_item(key="cluster", dictionary=self._config.architecture):
for cluster in cluster_list:
cluster_amount_dict[cluster['type']] = (
cluster_amount_dict.get(cluster['type'], 0) + cluster['cluster_amount']
)
# Summation of cluster amount.
self._cluster_amount: int = sum(value for value in cluster_amount_dict.values())
# Rack amount dict.
rack_amount_dict = {}
for cluster_list in self._find_item(key="cluster", dictionary=self._config.components):
for cluster in cluster_list:
for rack in cluster['rack']:
rack_amount_dict[rack['rack_type']] = (
rack_amount_dict.get(rack['rack_type'], 0)
+ cluster_amount_dict[cluster['type']] * rack['rack_amount']
)
# Summation of rack amount.
self._rack_amount: int = sum(value for value in rack_amount_dict.values())
# PM amount dict.
pm_amount_dict = {}
for rack in self._config.components.rack:
for pm in rack['pm']:
pm_amount_dict[pm['pm_type']] = (
pm_amount_dict.get(pm['pm_type'], 0)
+ rack_amount_dict[rack['type']] * pm['pm_amount']
)
# Summation of pm amount.
self._pm_amount: int = sum(value for value in pm_amount_dict.values())
self._kill_all_vms_if_overload: bool = self._config.KILL_ALL_VMS_IF_OVERLOAD | [
"def",
"_load_configs",
"(",
"self",
")",
":",
"# Update self._config_path with current file path.",
"self",
".",
"update_config_root_path",
"(",
"__file__",
")",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_config_path",
",",
"\"config.yml\"",
")",
")",
"as",
"fp",
":",
"self",
".",
"_config",
"=",
"convert_dottable",
"(",
"safe_load",
"(",
"fp",
")",
")",
"self",
".",
"_delay_duration",
":",
"int",
"=",
"self",
".",
"_config",
".",
"DELAY_DURATION",
"self",
".",
"_buffer_time_budget",
":",
"int",
"=",
"self",
".",
"_config",
".",
"BUFFER_TIME_BUDGET",
"self",
".",
"_ticks_per_hour",
":",
"float",
"=",
"self",
".",
"_config",
".",
"TICKS_PER_HOUR",
"# Oversubscription rate.",
"self",
".",
"_max_cpu_oversubscription_rate",
":",
"float",
"=",
"self",
".",
"_config",
".",
"MAX_CPU_OVERSUBSCRIPTION_RATE",
"self",
".",
"_max_memory_oversubscription_rate",
":",
"float",
"=",
"self",
".",
"_config",
".",
"MAX_MEM_OVERSUBSCRIPTION_RATE",
"self",
".",
"_max_utilization_rate",
":",
"float",
"=",
"self",
".",
"_config",
".",
"MAX_UTILIZATION_RATE",
"# Price parameters",
"self",
".",
"_price_per_cpu_cores_per_hour",
":",
"float",
"=",
"self",
".",
"_config",
".",
"PRICE_PER_CPU_CORES_PER_HOUR",
"self",
".",
"_price_per_memory_per_hour",
":",
"float",
"=",
"self",
".",
"_config",
".",
"PRICE_PER_MEMORY_PER_HOUR",
"self",
".",
"_unit_energy_price_per_kwh",
":",
"float",
"=",
"self",
".",
"_config",
".",
"UNIT_ENERGY_PRICE_PER_KWH",
"self",
".",
"_power_usage_efficiency",
":",
"float",
"=",
"self",
".",
"_config",
".",
"POWER_USAGE_EFFICIENCY",
"# Load PM related configs.",
"self",
".",
"_region_amount",
":",
"int",
"=",
"sum",
"(",
"len",
"(",
"item",
")",
"for",
"item",
"in",
"self",
".",
"_find_item",
"(",
"key",
"=",
"\"region\"",
",",
"dictionary",
"=",
"self",
".",
"_config",
".",
"architecture",
")",
")",
"self",
".",
"_zone_amount",
":",
"int",
"=",
"sum",
"(",
"len",
"(",
"item",
")",
"for",
"item",
"in",
"self",
".",
"_find_item",
"(",
"key",
"=",
"\"zone\"",
",",
"dictionary",
"=",
"self",
".",
"_config",
".",
"architecture",
")",
")",
"self",
".",
"_data_center_amount",
":",
"int",
"=",
"sum",
"(",
"len",
"(",
"item",
")",
"for",
"item",
"in",
"self",
".",
"_find_item",
"(",
"key",
"=",
"\"data_center\"",
",",
"dictionary",
"=",
"self",
".",
"_config",
".",
"architecture",
")",
")",
"# Cluster amount dict.",
"cluster_amount_dict",
"=",
"{",
"}",
"for",
"cluster_list",
"in",
"self",
".",
"_find_item",
"(",
"key",
"=",
"\"cluster\"",
",",
"dictionary",
"=",
"self",
".",
"_config",
".",
"architecture",
")",
":",
"for",
"cluster",
"in",
"cluster_list",
":",
"cluster_amount_dict",
"[",
"cluster",
"[",
"'type'",
"]",
"]",
"=",
"(",
"cluster_amount_dict",
".",
"get",
"(",
"cluster",
"[",
"'type'",
"]",
",",
"0",
")",
"+",
"cluster",
"[",
"'cluster_amount'",
"]",
")",
"# Summation of cluster amount.",
"self",
".",
"_cluster_amount",
":",
"int",
"=",
"sum",
"(",
"value",
"for",
"value",
"in",
"cluster_amount_dict",
".",
"values",
"(",
")",
")",
"# Rack amount dict.",
"rack_amount_dict",
"=",
"{",
"}",
"for",
"cluster_list",
"in",
"self",
".",
"_find_item",
"(",
"key",
"=",
"\"cluster\"",
",",
"dictionary",
"=",
"self",
".",
"_config",
".",
"components",
")",
":",
"for",
"cluster",
"in",
"cluster_list",
":",
"for",
"rack",
"in",
"cluster",
"[",
"'rack'",
"]",
":",
"rack_amount_dict",
"[",
"rack",
"[",
"'rack_type'",
"]",
"]",
"=",
"(",
"rack_amount_dict",
".",
"get",
"(",
"rack",
"[",
"'rack_type'",
"]",
",",
"0",
")",
"+",
"cluster_amount_dict",
"[",
"cluster",
"[",
"'type'",
"]",
"]",
"*",
"rack",
"[",
"'rack_amount'",
"]",
")",
"# Summation of rack amount.",
"self",
".",
"_rack_amount",
":",
"int",
"=",
"sum",
"(",
"value",
"for",
"value",
"in",
"rack_amount_dict",
".",
"values",
"(",
")",
")",
"# PM amount dict.",
"pm_amount_dict",
"=",
"{",
"}",
"for",
"rack",
"in",
"self",
".",
"_config",
".",
"components",
".",
"rack",
":",
"for",
"pm",
"in",
"rack",
"[",
"'pm'",
"]",
":",
"pm_amount_dict",
"[",
"pm",
"[",
"'pm_type'",
"]",
"]",
"=",
"(",
"pm_amount_dict",
".",
"get",
"(",
"pm",
"[",
"'pm_type'",
"]",
",",
"0",
")",
"+",
"rack_amount_dict",
"[",
"rack",
"[",
"'type'",
"]",
"]",
"*",
"pm",
"[",
"'pm_amount'",
"]",
")",
"# Summation of pm amount.",
"self",
".",
"_pm_amount",
":",
"int",
"=",
"sum",
"(",
"value",
"for",
"value",
"in",
"pm_amount_dict",
".",
"values",
"(",
")",
")",
"self",
".",
"_kill_all_vms_if_overload",
":",
"bool",
"=",
"self",
".",
"_config",
".",
"KILL_ALL_VMS_IF_OVERLOAD"
] | [
108,
4
] | [
172,
84
] | python | en | ['en', 'ca', 'en'] | False |
VmSchedulingBusinessEngine._init_data | (self) | If the file does not exist, then trigger the short data pipeline to download the processed data. | If the file does not exist, then trigger the short data pipeline to download the processed data. | def _init_data(self):
"""If the file does not exist, then trigger the short data pipeline to download the processed data."""
vm_table_data_path = self._config.VM_TABLE
if vm_table_data_path.startswith("~"):
vm_table_data_path = os.path.expanduser(vm_table_data_path)
cpu_readings_data_path = self._config.CPU_READINGS
if cpu_readings_data_path.startswith("~"):
cpu_readings_data_path = os.path.expanduser(cpu_readings_data_path)
# Testing file.
if vm_table_data_path.startswith("tests") or cpu_readings_data_path.startswith("tests"):
pass
elif (not os.path.exists(vm_table_data_path)) or (not os.path.exists(cpu_readings_data_path)):
logger.info_green("Lack data. Start preparing data.")
self._download_processed_data()
logger.info_green("Data preparation is finished.") | [
"def",
"_init_data",
"(",
"self",
")",
":",
"vm_table_data_path",
"=",
"self",
".",
"_config",
".",
"VM_TABLE",
"if",
"vm_table_data_path",
".",
"startswith",
"(",
"\"~\"",
")",
":",
"vm_table_data_path",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"vm_table_data_path",
")",
"cpu_readings_data_path",
"=",
"self",
".",
"_config",
".",
"CPU_READINGS",
"if",
"cpu_readings_data_path",
".",
"startswith",
"(",
"\"~\"",
")",
":",
"cpu_readings_data_path",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"cpu_readings_data_path",
")",
"# Testing file.",
"if",
"vm_table_data_path",
".",
"startswith",
"(",
"\"tests\"",
")",
"or",
"cpu_readings_data_path",
".",
"startswith",
"(",
"\"tests\"",
")",
":",
"pass",
"elif",
"(",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"vm_table_data_path",
")",
")",
"or",
"(",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"cpu_readings_data_path",
")",
")",
":",
"logger",
".",
"info_green",
"(",
"\"Lack data. Start preparing data.\"",
")",
"self",
".",
"_download_processed_data",
"(",
")",
"logger",
".",
"info_green",
"(",
"\"Data preparation is finished.\"",
")"
] | [
190,
4
] | [
206,
62
] | python | en | ['en', 'en', 'en'] | True |
VmSchedulingBusinessEngine._init_structure | (self) | Initialize the whole pm structure. | Initialize the whole pm structure. | def _init_structure(self):
"""Initialize the whole pm structure."""
# TODO: Improve the scalability. Like the use of multiple PM sets.
self._regions = self._frame.regions
self._zones = self._frame.zones
self._data_centers = self._frame.data_centers
self._clusters = self._frame.clusters
self._racks = self._frame.racks
self._machines = self._frame.pms
# PM type dictionary.
self._cluster_config_dict = {
cluster['type']: {
rack['rack_type']: rack['rack_amount'] for rack in cluster['rack']
}
for cluster in self._config.components.cluster
}
self._rack_config_dict = {
rack['type']: {
pm['pm_type']: pm['pm_amount'] for pm in rack['pm']
}
for rack in self._config.components.rack
}
self._pm_config_dict: dict = {
pm_type: pm_dict for pm_type, pm_dict in enumerate(self._config.components.pm)
}
# Ids.
self._region_id = 0
self._zone_id = 0
self._data_center_id = 0
self._cluster_id = 0
self._rack_id = 0
self._pm_id = 0
# Initialize regions.
self._init_regions() | [
"def",
"_init_structure",
"(",
"self",
")",
":",
"# TODO: Improve the scalability. Like the use of multiple PM sets.",
"self",
".",
"_regions",
"=",
"self",
".",
"_frame",
".",
"regions",
"self",
".",
"_zones",
"=",
"self",
".",
"_frame",
".",
"zones",
"self",
".",
"_data_centers",
"=",
"self",
".",
"_frame",
".",
"data_centers",
"self",
".",
"_clusters",
"=",
"self",
".",
"_frame",
".",
"clusters",
"self",
".",
"_racks",
"=",
"self",
".",
"_frame",
".",
"racks",
"self",
".",
"_machines",
"=",
"self",
".",
"_frame",
".",
"pms",
"# PM type dictionary.",
"self",
".",
"_cluster_config_dict",
"=",
"{",
"cluster",
"[",
"'type'",
"]",
":",
"{",
"rack",
"[",
"'rack_type'",
"]",
":",
"rack",
"[",
"'rack_amount'",
"]",
"for",
"rack",
"in",
"cluster",
"[",
"'rack'",
"]",
"}",
"for",
"cluster",
"in",
"self",
".",
"_config",
".",
"components",
".",
"cluster",
"}",
"self",
".",
"_rack_config_dict",
"=",
"{",
"rack",
"[",
"'type'",
"]",
":",
"{",
"pm",
"[",
"'pm_type'",
"]",
":",
"pm",
"[",
"'pm_amount'",
"]",
"for",
"pm",
"in",
"rack",
"[",
"'pm'",
"]",
"}",
"for",
"rack",
"in",
"self",
".",
"_config",
".",
"components",
".",
"rack",
"}",
"self",
".",
"_pm_config_dict",
":",
"dict",
"=",
"{",
"pm_type",
":",
"pm_dict",
"for",
"pm_type",
",",
"pm_dict",
"in",
"enumerate",
"(",
"self",
".",
"_config",
".",
"components",
".",
"pm",
")",
"}",
"# Ids.",
"self",
".",
"_region_id",
"=",
"0",
"self",
".",
"_zone_id",
"=",
"0",
"self",
".",
"_data_center_id",
"=",
"0",
"self",
".",
"_cluster_id",
"=",
"0",
"self",
".",
"_rack_id",
"=",
"0",
"self",
".",
"_pm_id",
"=",
"0",
"# Initialize regions.",
"self",
".",
"_init_regions",
"(",
")"
] | [
220,
4
] | [
253,
28
] | python | en | ['en', 'en', 'en'] | True |
VmSchedulingBusinessEngine._init_regions | (self) | Initialize the regions based on the config setting. The regions id starts from 0. | Initialize the regions based on the config setting. The regions id starts from 0. | def _init_regions(self):
"""Initialize the regions based on the config setting. The regions id starts from 0."""
for region_list in self._find_item("region", self._config.architecture):
for region_dict in region_list:
# Initialize zones.
start_zone_id = self._init_zones(
zone_list=region_dict["zone"]
)
region = self._regions[self._region_id]
region.name = region_dict["name"]
region.zone_list = [id for id in range(start_zone_id, self._zone_id)]
total_machine_num = sum(
self._zones[id].total_machine_num for id in region.zone_list
)
region.set_init_state(
id=self._region_id,
total_machine_num=total_machine_num
)
self._region_id += 1 | [
"def",
"_init_regions",
"(",
"self",
")",
":",
"for",
"region_list",
"in",
"self",
".",
"_find_item",
"(",
"\"region\"",
",",
"self",
".",
"_config",
".",
"architecture",
")",
":",
"for",
"region_dict",
"in",
"region_list",
":",
"# Initialize zones.",
"start_zone_id",
"=",
"self",
".",
"_init_zones",
"(",
"zone_list",
"=",
"region_dict",
"[",
"\"zone\"",
"]",
")",
"region",
"=",
"self",
".",
"_regions",
"[",
"self",
".",
"_region_id",
"]",
"region",
".",
"name",
"=",
"region_dict",
"[",
"\"name\"",
"]",
"region",
".",
"zone_list",
"=",
"[",
"id",
"for",
"id",
"in",
"range",
"(",
"start_zone_id",
",",
"self",
".",
"_zone_id",
")",
"]",
"total_machine_num",
"=",
"sum",
"(",
"self",
".",
"_zones",
"[",
"id",
"]",
".",
"total_machine_num",
"for",
"id",
"in",
"region",
".",
"zone_list",
")",
"region",
".",
"set_init_state",
"(",
"id",
"=",
"self",
".",
"_region_id",
",",
"total_machine_num",
"=",
"total_machine_num",
")",
"self",
".",
"_region_id",
"+=",
"1"
] | [
255,
4
] | [
273,
36
] | python | en | ['en', 'en', 'en'] | True |
VmSchedulingBusinessEngine._init_zones | (self, zone_list: list) | Initialize the zones based on the config setting. The zone id starts from 0. | Initialize the zones based on the config setting. The zone id starts from 0. | def _init_zones(self, zone_list: list):
"""Initialize the zones based on the config setting. The zone id starts from 0."""
start_zone_id = self._zone_id
for zone_dict in zone_list:
# Initialize data centers.
start_data_center_id = self._init_data_centers(
data_center_list=zone_dict["data_center"]
)
zone = self._zones[self._zone_id]
zone.name = zone_dict["name"]
zone.data_center_list = [id for id in range(start_data_center_id, self._data_center_id)]
total_machine_num = sum(
self._data_centers[id].total_machine_num for id in zone.data_center_list
)
zone.set_init_state(
id=self._zone_id,
region_id=self._region_id,
total_machine_num=total_machine_num
)
self._zone_id += 1
return start_zone_id | [
"def",
"_init_zones",
"(",
"self",
",",
"zone_list",
":",
"list",
")",
":",
"start_zone_id",
"=",
"self",
".",
"_zone_id",
"for",
"zone_dict",
"in",
"zone_list",
":",
"# Initialize data centers.",
"start_data_center_id",
"=",
"self",
".",
"_init_data_centers",
"(",
"data_center_list",
"=",
"zone_dict",
"[",
"\"data_center\"",
"]",
")",
"zone",
"=",
"self",
".",
"_zones",
"[",
"self",
".",
"_zone_id",
"]",
"zone",
".",
"name",
"=",
"zone_dict",
"[",
"\"name\"",
"]",
"zone",
".",
"data_center_list",
"=",
"[",
"id",
"for",
"id",
"in",
"range",
"(",
"start_data_center_id",
",",
"self",
".",
"_data_center_id",
")",
"]",
"total_machine_num",
"=",
"sum",
"(",
"self",
".",
"_data_centers",
"[",
"id",
"]",
".",
"total_machine_num",
"for",
"id",
"in",
"zone",
".",
"data_center_list",
")",
"zone",
".",
"set_init_state",
"(",
"id",
"=",
"self",
".",
"_zone_id",
",",
"region_id",
"=",
"self",
".",
"_region_id",
",",
"total_machine_num",
"=",
"total_machine_num",
")",
"self",
".",
"_zone_id",
"+=",
"1",
"return",
"start_zone_id"
] | [
275,
4
] | [
297,
28
] | python | en | ['en', 'en', 'en'] | True |
VmSchedulingBusinessEngine._init_data_centers | (self, data_center_list: list) | Initialize the data_centers based on the config setting. The data_center id starts from 0. | Initialize the data_centers based on the config setting. The data_center id starts from 0. | def _init_data_centers(self, data_center_list: list):
"""Initialize the data_centers based on the config setting. The data_center id starts from 0."""
start_data_center_id = self._data_center_id
for data_center_dict in data_center_list:
# Initialize clusters.
start_cluster_id = self._init_clusters(
cluster_list=data_center_dict["cluster"]
)
data_center = self._data_centers[self._data_center_id]
data_center.name = data_center_dict["name"]
data_center.cluster_list = [id for id in range(start_cluster_id, self._cluster_id)]
total_machine_num = sum(
self._clusters[id].total_machine_num for id in data_center.cluster_list
)
data_center.set_init_state(
id=self._data_center_id,
region_id=self._region_id,
zone_id=self._zone_id,
total_machine_num=total_machine_num
)
self._data_center_id += 1
return start_data_center_id | [
"def",
"_init_data_centers",
"(",
"self",
",",
"data_center_list",
":",
"list",
")",
":",
"start_data_center_id",
"=",
"self",
".",
"_data_center_id",
"for",
"data_center_dict",
"in",
"data_center_list",
":",
"# Initialize clusters.",
"start_cluster_id",
"=",
"self",
".",
"_init_clusters",
"(",
"cluster_list",
"=",
"data_center_dict",
"[",
"\"cluster\"",
"]",
")",
"data_center",
"=",
"self",
".",
"_data_centers",
"[",
"self",
".",
"_data_center_id",
"]",
"data_center",
".",
"name",
"=",
"data_center_dict",
"[",
"\"name\"",
"]",
"data_center",
".",
"cluster_list",
"=",
"[",
"id",
"for",
"id",
"in",
"range",
"(",
"start_cluster_id",
",",
"self",
".",
"_cluster_id",
")",
"]",
"total_machine_num",
"=",
"sum",
"(",
"self",
".",
"_clusters",
"[",
"id",
"]",
".",
"total_machine_num",
"for",
"id",
"in",
"data_center",
".",
"cluster_list",
")",
"data_center",
".",
"set_init_state",
"(",
"id",
"=",
"self",
".",
"_data_center_id",
",",
"region_id",
"=",
"self",
".",
"_region_id",
",",
"zone_id",
"=",
"self",
".",
"_zone_id",
",",
"total_machine_num",
"=",
"total_machine_num",
")",
"self",
".",
"_data_center_id",
"+=",
"1",
"return",
"start_data_center_id"
] | [
299,
4
] | [
321,
35
] | python | en | ['en', 'en', 'en'] | True |
VmSchedulingBusinessEngine._init_clusters | (self, cluster_list: list) | Initialize the clusters based on the config setting. The cluster id starts from 0. | Initialize the clusters based on the config setting. The cluster id starts from 0. | def _init_clusters(self, cluster_list: list):
"""Initialize the clusters based on the config setting. The cluster id starts from 0."""
start_cluster_id = self._cluster_id
for cluster in cluster_list:
cluster_type = cluster['type']
cluster_amount = cluster['cluster_amount']
while cluster_amount > 0:
# Init racks.
start_rack_id = self._init_racks(
rack_amount_dict=self._cluster_config_dict[cluster_type]
)
cluster = self._clusters[self._cluster_id]
cluster.cluster_type = cluster_type
cluster.rack_list = [id for id in range(start_rack_id, self._rack_id)]
total_machine_num = sum(
self._racks[id].total_machine_num for id in cluster.rack_list
)
cluster.set_init_state(
id=self._cluster_id,
region_id=self._region_id,
zone_id=self._zone_id,
data_center_id=self._data_center_id,
total_machine_num=total_machine_num
)
cluster_amount -= 1
self._cluster_id += 1
return start_cluster_id | [
"def",
"_init_clusters",
"(",
"self",
",",
"cluster_list",
":",
"list",
")",
":",
"start_cluster_id",
"=",
"self",
".",
"_cluster_id",
"for",
"cluster",
"in",
"cluster_list",
":",
"cluster_type",
"=",
"cluster",
"[",
"'type'",
"]",
"cluster_amount",
"=",
"cluster",
"[",
"'cluster_amount'",
"]",
"while",
"cluster_amount",
">",
"0",
":",
"# Init racks.",
"start_rack_id",
"=",
"self",
".",
"_init_racks",
"(",
"rack_amount_dict",
"=",
"self",
".",
"_cluster_config_dict",
"[",
"cluster_type",
"]",
")",
"cluster",
"=",
"self",
".",
"_clusters",
"[",
"self",
".",
"_cluster_id",
"]",
"cluster",
".",
"cluster_type",
"=",
"cluster_type",
"cluster",
".",
"rack_list",
"=",
"[",
"id",
"for",
"id",
"in",
"range",
"(",
"start_rack_id",
",",
"self",
".",
"_rack_id",
")",
"]",
"total_machine_num",
"=",
"sum",
"(",
"self",
".",
"_racks",
"[",
"id",
"]",
".",
"total_machine_num",
"for",
"id",
"in",
"cluster",
".",
"rack_list",
")",
"cluster",
".",
"set_init_state",
"(",
"id",
"=",
"self",
".",
"_cluster_id",
",",
"region_id",
"=",
"self",
".",
"_region_id",
",",
"zone_id",
"=",
"self",
".",
"_zone_id",
",",
"data_center_id",
"=",
"self",
".",
"_data_center_id",
",",
"total_machine_num",
"=",
"total_machine_num",
")",
"cluster_amount",
"-=",
"1",
"self",
".",
"_cluster_id",
"+=",
"1",
"return",
"start_cluster_id"
] | [
323,
4
] | [
351,
31
] | python | en | ['en', 'en', 'en'] | True |
VmSchedulingBusinessEngine._init_racks | (self, rack_amount_dict: dict) | Initialize the racks based on the config setting. The rack id starts from 0. | Initialize the racks based on the config setting. The rack id starts from 0. | def _init_racks(self, rack_amount_dict: dict):
"""Initialize the racks based on the config setting. The rack id starts from 0."""
start_rack_id = self._rack_id
for rack_type, rack_amount in rack_amount_dict.items():
while rack_amount > 0:
# Initialize pms.
start_pm_id = self._init_pms(
pm_dict=self._rack_config_dict[rack_type]
)
rack = self._racks[self._rack_id]
rack.type = rack_type
rack.pm_list = [id for id in range(start_pm_id, self._pm_id)]
total_machine_num = len(rack.pm_list)
rack.set_init_state(
id=self._rack_id,
region_id=self._region_id,
zone_id=self._zone_id,
data_center_id=self._data_center_id,
cluster_id=self._cluster_id,
total_machine_num=total_machine_num
)
rack_amount -= 1
self._rack_id += 1
return start_rack_id | [
"def",
"_init_racks",
"(",
"self",
",",
"rack_amount_dict",
":",
"dict",
")",
":",
"start_rack_id",
"=",
"self",
".",
"_rack_id",
"for",
"rack_type",
",",
"rack_amount",
"in",
"rack_amount_dict",
".",
"items",
"(",
")",
":",
"while",
"rack_amount",
">",
"0",
":",
"# Initialize pms.",
"start_pm_id",
"=",
"self",
".",
"_init_pms",
"(",
"pm_dict",
"=",
"self",
".",
"_rack_config_dict",
"[",
"rack_type",
"]",
")",
"rack",
"=",
"self",
".",
"_racks",
"[",
"self",
".",
"_rack_id",
"]",
"rack",
".",
"type",
"=",
"rack_type",
"rack",
".",
"pm_list",
"=",
"[",
"id",
"for",
"id",
"in",
"range",
"(",
"start_pm_id",
",",
"self",
".",
"_pm_id",
")",
"]",
"total_machine_num",
"=",
"len",
"(",
"rack",
".",
"pm_list",
")",
"rack",
".",
"set_init_state",
"(",
"id",
"=",
"self",
".",
"_rack_id",
",",
"region_id",
"=",
"self",
".",
"_region_id",
",",
"zone_id",
"=",
"self",
".",
"_zone_id",
",",
"data_center_id",
"=",
"self",
".",
"_data_center_id",
",",
"cluster_id",
"=",
"self",
".",
"_cluster_id",
",",
"total_machine_num",
"=",
"total_machine_num",
")",
"rack_amount",
"-=",
"1",
"self",
".",
"_rack_id",
"+=",
"1",
"return",
"start_rack_id"
] | [
353,
4
] | [
377,
28
] | python | en | ['en', 'en', 'en'] | True |
VmSchedulingBusinessEngine._init_pms | (self, pm_dict: dict) | Initialize the pms based on the config setting. The pm id starts from 0. | Initialize the pms based on the config setting. The pm id starts from 0. | def _init_pms(self, pm_dict: dict):
"""Initialize the pms based on the config setting. The pm id starts from 0."""
start_pm_id = self._pm_id
for pm_type, pm_amount in pm_dict.items():
while pm_amount > 0:
pm = self._machines[self._pm_id]
pm.set_init_state(
id=self._pm_id,
cpu_cores_capacity=self._pm_config_dict[pm_type]["cpu"],
memory_capacity=self._pm_config_dict[pm_type]["memory"],
pm_type=pm_type,
region_id=self._region_id,
zone_id=self._zone_id,
data_center_id=self._data_center_id,
cluster_id=self._cluster_id,
rack_id=self._rack_id,
oversubscribable=PmState.EMPTY,
idle_energy_consumption=self._cpu_utilization_to_energy_consumption(
pm_type=self._pm_config_dict[pm_type],
cpu_utilization=0
)
)
pm_amount -= 1
self._pm_id += 1
return start_pm_id | [
"def",
"_init_pms",
"(",
"self",
",",
"pm_dict",
":",
"dict",
")",
":",
"start_pm_id",
"=",
"self",
".",
"_pm_id",
"for",
"pm_type",
",",
"pm_amount",
"in",
"pm_dict",
".",
"items",
"(",
")",
":",
"while",
"pm_amount",
">",
"0",
":",
"pm",
"=",
"self",
".",
"_machines",
"[",
"self",
".",
"_pm_id",
"]",
"pm",
".",
"set_init_state",
"(",
"id",
"=",
"self",
".",
"_pm_id",
",",
"cpu_cores_capacity",
"=",
"self",
".",
"_pm_config_dict",
"[",
"pm_type",
"]",
"[",
"\"cpu\"",
"]",
",",
"memory_capacity",
"=",
"self",
".",
"_pm_config_dict",
"[",
"pm_type",
"]",
"[",
"\"memory\"",
"]",
",",
"pm_type",
"=",
"pm_type",
",",
"region_id",
"=",
"self",
".",
"_region_id",
",",
"zone_id",
"=",
"self",
".",
"_zone_id",
",",
"data_center_id",
"=",
"self",
".",
"_data_center_id",
",",
"cluster_id",
"=",
"self",
".",
"_cluster_id",
",",
"rack_id",
"=",
"self",
".",
"_rack_id",
",",
"oversubscribable",
"=",
"PmState",
".",
"EMPTY",
",",
"idle_energy_consumption",
"=",
"self",
".",
"_cpu_utilization_to_energy_consumption",
"(",
"pm_type",
"=",
"self",
".",
"_pm_config_dict",
"[",
"pm_type",
"]",
",",
"cpu_utilization",
"=",
"0",
")",
")",
"pm_amount",
"-=",
"1",
"self",
".",
"_pm_id",
"+=",
"1",
"return",
"start_pm_id"
] | [
379,
4
] | [
405,
26
] | python | en | ['en', 'en', 'en'] | True |
VmSchedulingBusinessEngine.reset | (self) | Reset internal states for episode. | Reset internal states for episode. | def reset(self):
"""Reset internal states for episode."""
self._init_metrics()
self._frame.reset()
self._snapshots.reset()
for pm in self._machines:
pm.reset()
for rack in self._racks:
rack.reset()
for cluster in self._clusters:
cluster.reset()
for data_center in self._data_centers:
data_center.reset()
for zone in self._zones:
zone.reset()
for region in self._regions:
region.reset()
self._live_vms.clear()
self._pending_vm_request_payload.clear()
self._vm_reader.reset()
self._vm_item_picker = self._vm_reader.items_tick_picker(self._start_tick, self._max_tick, time_unit="s")
self._cpu_reader.reset() | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"_init_metrics",
"(",
")",
"self",
".",
"_frame",
".",
"reset",
"(",
")",
"self",
".",
"_snapshots",
".",
"reset",
"(",
")",
"for",
"pm",
"in",
"self",
".",
"_machines",
":",
"pm",
".",
"reset",
"(",
")",
"for",
"rack",
"in",
"self",
".",
"_racks",
":",
"rack",
".",
"reset",
"(",
")",
"for",
"cluster",
"in",
"self",
".",
"_clusters",
":",
"cluster",
".",
"reset",
"(",
")",
"for",
"data_center",
"in",
"self",
".",
"_data_centers",
":",
"data_center",
".",
"reset",
"(",
")",
"for",
"zone",
"in",
"self",
".",
"_zones",
":",
"zone",
".",
"reset",
"(",
")",
"for",
"region",
"in",
"self",
".",
"_regions",
":",
"region",
".",
"reset",
"(",
")",
"self",
".",
"_live_vms",
".",
"clear",
"(",
")",
"self",
".",
"_pending_vm_request_payload",
".",
"clear",
"(",
")",
"self",
".",
"_vm_reader",
".",
"reset",
"(",
")",
"self",
".",
"_vm_item_picker",
"=",
"self",
".",
"_vm_reader",
".",
"items_tick_picker",
"(",
"self",
".",
"_start_tick",
",",
"self",
".",
"_max_tick",
",",
"time_unit",
"=",
"\"s\"",
")",
"self",
".",
"_cpu_reader",
".",
"reset",
"(",
")"
] | [
407,
4
] | [
438,
32
] | python | en | ['en', 'en', 'en'] | True |
VmSchedulingBusinessEngine.step | (self, tick: int) | Push business to next step.
Args:
tick (int): Current tick to process.
| Push business to next step. | def step(self, tick: int):
"""Push business to next step.
Args:
tick (int): Current tick to process.
"""
self._tick = tick
# All vm's cpu utilization at current tick.
cur_tick_cpu_utilization = self._cpu_reader.items(tick=tick)
# Process finished VMs.
self._process_finished_vm()
# Update all live VMs CPU utilization.
self._update_vm_workload(cur_tick_cpu_utilization=cur_tick_cpu_utilization)
# Update all PM CPU utilization.
self._update_pm_workload()
self._update_upper_level_metrics()
for vm in self._vm_item_picker.items(tick):
# TODO: Batch request support.
unit_price = self._get_unit_price(vm.vm_cpu_cores, vm.vm_memory)
vm_info = VirtualMachine(
id=vm.vm_id,
cpu_cores_requirement=vm.vm_cpu_cores,
memory_requirement=vm.vm_memory,
lifetime=vm.vm_lifetime,
sub_id=vm.sub_id,
deployment_id=vm.deploy_id,
category=VmCategory(vm.vm_category),
unit_price=unit_price
)
if vm.vm_id not in cur_tick_cpu_utilization:
raise Exception(f"The VM id: '{vm.vm_id}' does not exist at this tick.")
vm_info.add_utilization(cpu_utilization=cur_tick_cpu_utilization[vm.vm_id])
vm_req_payload: VmRequestPayload = VmRequestPayload(
vm_info=vm_info,
remaining_buffer_time=self._buffer_time_budget
)
vm_request_event = self._event_buffer.gen_cascade_event(
tick=tick,
event_type=Events.REQUEST,
payload=vm_req_payload
)
self._event_buffer.insert_event(event=vm_request_event)
self._total_vm_requests += 1 | [
"def",
"step",
"(",
"self",
",",
"tick",
":",
"int",
")",
":",
"self",
".",
"_tick",
"=",
"tick",
"# All vm's cpu utilization at current tick.",
"cur_tick_cpu_utilization",
"=",
"self",
".",
"_cpu_reader",
".",
"items",
"(",
"tick",
"=",
"tick",
")",
"# Process finished VMs.",
"self",
".",
"_process_finished_vm",
"(",
")",
"# Update all live VMs CPU utilization.",
"self",
".",
"_update_vm_workload",
"(",
"cur_tick_cpu_utilization",
"=",
"cur_tick_cpu_utilization",
")",
"# Update all PM CPU utilization.",
"self",
".",
"_update_pm_workload",
"(",
")",
"self",
".",
"_update_upper_level_metrics",
"(",
")",
"for",
"vm",
"in",
"self",
".",
"_vm_item_picker",
".",
"items",
"(",
"tick",
")",
":",
"# TODO: Batch request support.",
"unit_price",
"=",
"self",
".",
"_get_unit_price",
"(",
"vm",
".",
"vm_cpu_cores",
",",
"vm",
".",
"vm_memory",
")",
"vm_info",
"=",
"VirtualMachine",
"(",
"id",
"=",
"vm",
".",
"vm_id",
",",
"cpu_cores_requirement",
"=",
"vm",
".",
"vm_cpu_cores",
",",
"memory_requirement",
"=",
"vm",
".",
"vm_memory",
",",
"lifetime",
"=",
"vm",
".",
"vm_lifetime",
",",
"sub_id",
"=",
"vm",
".",
"sub_id",
",",
"deployment_id",
"=",
"vm",
".",
"deploy_id",
",",
"category",
"=",
"VmCategory",
"(",
"vm",
".",
"vm_category",
")",
",",
"unit_price",
"=",
"unit_price",
")",
"if",
"vm",
".",
"vm_id",
"not",
"in",
"cur_tick_cpu_utilization",
":",
"raise",
"Exception",
"(",
"f\"The VM id: '{vm.vm_id}' does not exist at this tick.\"",
")",
"vm_info",
".",
"add_utilization",
"(",
"cpu_utilization",
"=",
"cur_tick_cpu_utilization",
"[",
"vm",
".",
"vm_id",
"]",
")",
"vm_req_payload",
":",
"VmRequestPayload",
"=",
"VmRequestPayload",
"(",
"vm_info",
"=",
"vm_info",
",",
"remaining_buffer_time",
"=",
"self",
".",
"_buffer_time_budget",
")",
"vm_request_event",
"=",
"self",
".",
"_event_buffer",
".",
"gen_cascade_event",
"(",
"tick",
"=",
"tick",
",",
"event_type",
"=",
"Events",
".",
"REQUEST",
",",
"payload",
"=",
"vm_req_payload",
")",
"self",
".",
"_event_buffer",
".",
"insert_event",
"(",
"event",
"=",
"vm_request_event",
")",
"self",
".",
"_total_vm_requests",
"+=",
"1"
] | [
452,
4
] | [
499,
40
] | python | en | ['en', 'en', 'en'] | True |
VmSchedulingBusinessEngine.get_event_payload_detail | (self) | dict: Event payload details of current scenario. | dict: Event payload details of current scenario. | def get_event_payload_detail(self) -> dict:
"""dict: Event payload details of current scenario."""
return {
Events.REQUEST.name: VmRequestPayload.summary_key,
MaroEvents.PENDING_DECISION.name: DecisionPayload.summary_key
} | [
"def",
"get_event_payload_detail",
"(",
"self",
")",
"->",
"dict",
":",
"return",
"{",
"Events",
".",
"REQUEST",
".",
"name",
":",
"VmRequestPayload",
".",
"summary_key",
",",
"MaroEvents",
".",
"PENDING_DECISION",
".",
"name",
":",
"DecisionPayload",
".",
"summary_key",
"}"
] | [
534,
4
] | [
539,
9
] | python | en | ['en', 'en', 'en'] | True |
VmSchedulingBusinessEngine.get_agent_idx_list | (self) | Get a list of agent index. | Get a list of agent index. | def get_agent_idx_list(self) -> List[int]:
"""Get a list of agent index."""
pass | [
"def",
"get_agent_idx_list",
"(",
"self",
")",
"->",
"List",
"[",
"int",
"]",
":",
"pass"
] | [
541,
4
] | [
543,
12
] | python | en | ['en', 'en', 'en'] | True |
VmSchedulingBusinessEngine.get_node_mapping | (self) | dict: Node mapping. | dict: Node mapping. | def get_node_mapping(self) -> dict:
"""dict: Node mapping."""
node_mapping = {}
return node_mapping | [
"def",
"get_node_mapping",
"(",
"self",
")",
"->",
"dict",
":",
"node_mapping",
"=",
"{",
"}",
"return",
"node_mapping"
] | [
545,
4
] | [
549,
27
] | python | en | ['en', 'en', 'en'] | True |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.