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 |
---|---|---|---|---|---|---|---|---|---|---|---|
HassEventLoopPolicy.new_event_loop | (self) | Get the event loop. | Get the event loop. | def new_event_loop(self) -> asyncio.AbstractEventLoop:
"""Get the event loop."""
loop: asyncio.AbstractEventLoop = super().new_event_loop()
loop.set_exception_handler(_async_loop_exception_handler)
if self.debug:
loop.set_debug(True)
executor = ThreadPoolExecutor(
thread_name_prefix="SyncWorker", max_workers=MAX_EXECUTOR_WORKERS
)
loop.set_default_executor(executor)
loop.set_default_executor = warn_use( # type: ignore
loop.set_default_executor, "sets default executor on the event loop"
)
# Shut down executor when we shut down loop
orig_close = loop.close
def close() -> None:
executor.shutdown(wait=True)
orig_close()
loop.close = close # type: ignore
return loop | [
"def",
"new_event_loop",
"(",
"self",
")",
"->",
"asyncio",
".",
"AbstractEventLoop",
":",
"loop",
":",
"asyncio",
".",
"AbstractEventLoop",
"=",
"super",
"(",
")",
".",
"new_event_loop",
"(",
")",
"loop",
".",
"set_exception_handler",
"(",
"_async_loop_exception_handler",
")",
"if",
"self",
".",
"debug",
":",
"loop",
".",
"set_debug",
"(",
"True",
")",
"executor",
"=",
"ThreadPoolExecutor",
"(",
"thread_name_prefix",
"=",
"\"SyncWorker\"",
",",
"max_workers",
"=",
"MAX_EXECUTOR_WORKERS",
")",
"loop",
".",
"set_default_executor",
"(",
"executor",
")",
"loop",
".",
"set_default_executor",
"=",
"warn_use",
"(",
"# type: ignore",
"loop",
".",
"set_default_executor",
",",
"\"sets default executor on the event loop\"",
")",
"# Shut down executor when we shut down loop",
"orig_close",
"=",
"loop",
".",
"close",
"def",
"close",
"(",
")",
"->",
"None",
":",
"executor",
".",
"shutdown",
"(",
"wait",
"=",
"True",
")",
"orig_close",
"(",
")",
"loop",
".",
"close",
"=",
"close",
"# type: ignore",
"return",
"loop"
] | [
63,
4
] | [
87,
19
] | 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.august.config_flow.AugustGateway.async_authenticate",
return_value=True,
), patch(
"homeassistant.components.august.async_setup", return_value=True
) as mock_setup, patch(
"homeassistant.components.august.async_setup_entry",
return_value=True,
) as mock_setup_entry:
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_LOGIN_METHOD: "email",
CONF_USERNAME: "[email protected]",
CONF_PASSWORD: "test-password",
},
)
await hass.async_block_till_done()
assert result2["type"] == "create_entry"
assert result2["title"] == "[email protected]"
assert result2["data"] == {
CONF_LOGIN_METHOD: "email",
CONF_USERNAME: "[email protected]",
CONF_PASSWORD: "test-password",
CONF_INSTALL_ID: None,
CONF_TIMEOUT: 10,
CONF_ACCESS_TOKEN_CACHE_FILE: "[email protected]",
}
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.august.config_flow.AugustGateway.async_authenticate\"",
",",
"return_value",
"=",
"True",
",",
")",
",",
"patch",
"(",
"\"homeassistant.components.august.async_setup\"",
",",
"return_value",
"=",
"True",
")",
"as",
"mock_setup",
",",
"patch",
"(",
"\"homeassistant.components.august.async_setup_entry\"",
",",
"return_value",
"=",
"True",
",",
")",
"as",
"mock_setup_entry",
":",
"result2",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_configure",
"(",
"result",
"[",
"\"flow_id\"",
"]",
",",
"{",
"CONF_LOGIN_METHOD",
":",
"\"email\"",
",",
"CONF_USERNAME",
":",
"\"[email protected]\"",
",",
"CONF_PASSWORD",
":",
"\"test-password\"",
",",
"}",
",",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"result2",
"[",
"\"type\"",
"]",
"==",
"\"create_entry\"",
"assert",
"result2",
"[",
"\"title\"",
"]",
"==",
"\"[email protected]\"",
"assert",
"result2",
"[",
"\"data\"",
"]",
"==",
"{",
"CONF_LOGIN_METHOD",
":",
"\"email\"",
",",
"CONF_USERNAME",
":",
"\"[email protected]\"",
",",
"CONF_PASSWORD",
":",
"\"test-password\"",
",",
"CONF_INSTALL_ID",
":",
"None",
",",
"CONF_TIMEOUT",
":",
"10",
",",
"CONF_ACCESS_TOKEN_CACHE_FILE",
":",
"\"[email protected]\"",
",",
"}",
"assert",
"len",
"(",
"mock_setup",
".",
"mock_calls",
")",
"==",
"1",
"assert",
"len",
"(",
"mock_setup_entry",
".",
"mock_calls",
")",
"==",
"1"
] | [
22,
0
] | [
61,
48
] | python | en | ['en', 'en', '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.august.config_flow.AugustGateway.async_authenticate",
side_effect=InvalidAuth,
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_LOGIN_METHOD: "email",
CONF_USERNAME: "[email protected]",
CONF_PASSWORD: "test-password",
},
)
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.august.config_flow.AugustGateway.async_authenticate\"",
",",
"side_effect",
"=",
"InvalidAuth",
",",
")",
":",
"result2",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_configure",
"(",
"result",
"[",
"\"flow_id\"",
"]",
",",
"{",
"CONF_LOGIN_METHOD",
":",
"\"email\"",
",",
"CONF_USERNAME",
":",
"\"[email protected]\"",
",",
"CONF_PASSWORD",
":",
"\"test-password\"",
",",
"}",
",",
")",
"assert",
"result2",
"[",
"\"type\"",
"]",
"==",
"\"form\"",
"assert",
"result2",
"[",
"\"errors\"",
"]",
"==",
"{",
"\"base\"",
":",
"\"invalid_auth\"",
"}"
] | [
64,
0
] | [
84,
56
] | python | en | ['en', 'en', 'en'] | True |
test_user_unexpected_exception | (hass) | Test we handle an unexpected exception. | Test we handle an unexpected exception. | async def test_user_unexpected_exception(hass):
"""Test we handle an unexpected exception."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
with patch(
"homeassistant.components.august.config_flow.AugustGateway.async_authenticate",
side_effect=ValueError,
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_LOGIN_METHOD: "email",
CONF_USERNAME: "[email protected]",
CONF_PASSWORD: "test-password",
},
)
assert result2["type"] == "form"
assert result2["errors"] == {"base": "unknown"} | [
"async",
"def",
"test_user_unexpected_exception",
"(",
"hass",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"config_entries",
".",
"SOURCE_USER",
"}",
")",
"with",
"patch",
"(",
"\"homeassistant.components.august.config_flow.AugustGateway.async_authenticate\"",
",",
"side_effect",
"=",
"ValueError",
",",
")",
":",
"result2",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_configure",
"(",
"result",
"[",
"\"flow_id\"",
"]",
",",
"{",
"CONF_LOGIN_METHOD",
":",
"\"email\"",
",",
"CONF_USERNAME",
":",
"\"[email protected]\"",
",",
"CONF_PASSWORD",
":",
"\"test-password\"",
",",
"}",
",",
")",
"assert",
"result2",
"[",
"\"type\"",
"]",
"==",
"\"form\"",
"assert",
"result2",
"[",
"\"errors\"",
"]",
"==",
"{",
"\"base\"",
":",
"\"unknown\"",
"}"
] | [
87,
0
] | [
107,
51
] | 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.august.config_flow.AugustGateway.async_authenticate",
side_effect=CannotConnect,
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_LOGIN_METHOD: "email",
CONF_USERNAME: "[email protected]",
CONF_PASSWORD: "test-password",
},
)
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.august.config_flow.AugustGateway.async_authenticate\"",
",",
"side_effect",
"=",
"CannotConnect",
",",
")",
":",
"result2",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_configure",
"(",
"result",
"[",
"\"flow_id\"",
"]",
",",
"{",
"CONF_LOGIN_METHOD",
":",
"\"email\"",
",",
"CONF_USERNAME",
":",
"\"[email protected]\"",
",",
"CONF_PASSWORD",
":",
"\"test-password\"",
",",
"}",
",",
")",
"assert",
"result2",
"[",
"\"type\"",
"]",
"==",
"\"form\"",
"assert",
"result2",
"[",
"\"errors\"",
"]",
"==",
"{",
"\"base\"",
":",
"\"cannot_connect\"",
"}"
] | [
110,
0
] | [
130,
58
] | python | en | ['en', 'en', 'en'] | True |
test_form_needs_validate | (hass) | Test we present validation when we need to validate. | Test we present validation when we need to validate. | async def test_form_needs_validate(hass):
"""Test we present validation when we need to validate."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
with patch(
"homeassistant.components.august.config_flow.AugustGateway.async_authenticate",
side_effect=RequireValidation,
), patch(
"homeassistant.components.august.gateway.AuthenticatorAsync.async_send_verification_code",
return_value=True,
) as mock_send_verification_code:
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_LOGIN_METHOD: "email",
CONF_USERNAME: "[email protected]",
CONF_PASSWORD: "test-password",
},
)
assert len(mock_send_verification_code.mock_calls) == 1
assert result2["type"] == "form"
assert result2["errors"] is None
assert result2["step_id"] == "validation"
# Try with the WRONG verification code give us the form back again
with patch(
"homeassistant.components.august.config_flow.AugustGateway.async_authenticate",
side_effect=RequireValidation,
), patch(
"homeassistant.components.august.gateway.AuthenticatorAsync.async_validate_verification_code",
return_value=ValidationResult.INVALID_VERIFICATION_CODE,
) as mock_validate_verification_code, patch(
"homeassistant.components.august.gateway.AuthenticatorAsync.async_send_verification_code",
return_value=True,
) as mock_send_verification_code, patch(
"homeassistant.components.august.async_setup", return_value=True
) as mock_setup, patch(
"homeassistant.components.august.async_setup_entry", return_value=True
) as mock_setup_entry:
result3 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{VERIFICATION_CODE_KEY: "incorrect"},
)
# Make sure we do not resend the code again
# so they have a chance to retry
assert len(mock_send_verification_code.mock_calls) == 0
assert len(mock_validate_verification_code.mock_calls) == 1
assert result3["type"] == "form"
assert result3["errors"] is None
assert result3["step_id"] == "validation"
# Try with the CORRECT verification code and we setup
with patch(
"homeassistant.components.august.config_flow.AugustGateway.async_authenticate",
return_value=True,
), patch(
"homeassistant.components.august.gateway.AuthenticatorAsync.async_validate_verification_code",
return_value=ValidationResult.VALIDATED,
) as mock_validate_verification_code, patch(
"homeassistant.components.august.gateway.AuthenticatorAsync.async_send_verification_code",
return_value=True,
) as mock_send_verification_code, patch(
"homeassistant.components.august.async_setup", return_value=True
) as mock_setup, patch(
"homeassistant.components.august.async_setup_entry", return_value=True
) as mock_setup_entry:
result4 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{VERIFICATION_CODE_KEY: "correct"},
)
await hass.async_block_till_done()
assert len(mock_send_verification_code.mock_calls) == 0
assert len(mock_validate_verification_code.mock_calls) == 1
assert result4["type"] == "create_entry"
assert result4["title"] == "[email protected]"
assert result4["data"] == {
CONF_LOGIN_METHOD: "email",
CONF_USERNAME: "[email protected]",
CONF_PASSWORD: "test-password",
CONF_INSTALL_ID: None,
CONF_TIMEOUT: 10,
CONF_ACCESS_TOKEN_CACHE_FILE: "[email protected]",
}
assert len(mock_setup.mock_calls) == 1
assert len(mock_setup_entry.mock_calls) == 1 | [
"async",
"def",
"test_form_needs_validate",
"(",
"hass",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"config_entries",
".",
"SOURCE_USER",
"}",
")",
"with",
"patch",
"(",
"\"homeassistant.components.august.config_flow.AugustGateway.async_authenticate\"",
",",
"side_effect",
"=",
"RequireValidation",
",",
")",
",",
"patch",
"(",
"\"homeassistant.components.august.gateway.AuthenticatorAsync.async_send_verification_code\"",
",",
"return_value",
"=",
"True",
",",
")",
"as",
"mock_send_verification_code",
":",
"result2",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_configure",
"(",
"result",
"[",
"\"flow_id\"",
"]",
",",
"{",
"CONF_LOGIN_METHOD",
":",
"\"email\"",
",",
"CONF_USERNAME",
":",
"\"[email protected]\"",
",",
"CONF_PASSWORD",
":",
"\"test-password\"",
",",
"}",
",",
")",
"assert",
"len",
"(",
"mock_send_verification_code",
".",
"mock_calls",
")",
"==",
"1",
"assert",
"result2",
"[",
"\"type\"",
"]",
"==",
"\"form\"",
"assert",
"result2",
"[",
"\"errors\"",
"]",
"is",
"None",
"assert",
"result2",
"[",
"\"step_id\"",
"]",
"==",
"\"validation\"",
"# Try with the WRONG verification code give us the form back again",
"with",
"patch",
"(",
"\"homeassistant.components.august.config_flow.AugustGateway.async_authenticate\"",
",",
"side_effect",
"=",
"RequireValidation",
",",
")",
",",
"patch",
"(",
"\"homeassistant.components.august.gateway.AuthenticatorAsync.async_validate_verification_code\"",
",",
"return_value",
"=",
"ValidationResult",
".",
"INVALID_VERIFICATION_CODE",
",",
")",
"as",
"mock_validate_verification_code",
",",
"patch",
"(",
"\"homeassistant.components.august.gateway.AuthenticatorAsync.async_send_verification_code\"",
",",
"return_value",
"=",
"True",
",",
")",
"as",
"mock_send_verification_code",
",",
"patch",
"(",
"\"homeassistant.components.august.async_setup\"",
",",
"return_value",
"=",
"True",
")",
"as",
"mock_setup",
",",
"patch",
"(",
"\"homeassistant.components.august.async_setup_entry\"",
",",
"return_value",
"=",
"True",
")",
"as",
"mock_setup_entry",
":",
"result3",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_configure",
"(",
"result",
"[",
"\"flow_id\"",
"]",
",",
"{",
"VERIFICATION_CODE_KEY",
":",
"\"incorrect\"",
"}",
",",
")",
"# Make sure we do not resend the code again",
"# so they have a chance to retry",
"assert",
"len",
"(",
"mock_send_verification_code",
".",
"mock_calls",
")",
"==",
"0",
"assert",
"len",
"(",
"mock_validate_verification_code",
".",
"mock_calls",
")",
"==",
"1",
"assert",
"result3",
"[",
"\"type\"",
"]",
"==",
"\"form\"",
"assert",
"result3",
"[",
"\"errors\"",
"]",
"is",
"None",
"assert",
"result3",
"[",
"\"step_id\"",
"]",
"==",
"\"validation\"",
"# Try with the CORRECT verification code and we setup",
"with",
"patch",
"(",
"\"homeassistant.components.august.config_flow.AugustGateway.async_authenticate\"",
",",
"return_value",
"=",
"True",
",",
")",
",",
"patch",
"(",
"\"homeassistant.components.august.gateway.AuthenticatorAsync.async_validate_verification_code\"",
",",
"return_value",
"=",
"ValidationResult",
".",
"VALIDATED",
",",
")",
"as",
"mock_validate_verification_code",
",",
"patch",
"(",
"\"homeassistant.components.august.gateway.AuthenticatorAsync.async_send_verification_code\"",
",",
"return_value",
"=",
"True",
",",
")",
"as",
"mock_send_verification_code",
",",
"patch",
"(",
"\"homeassistant.components.august.async_setup\"",
",",
"return_value",
"=",
"True",
")",
"as",
"mock_setup",
",",
"patch",
"(",
"\"homeassistant.components.august.async_setup_entry\"",
",",
"return_value",
"=",
"True",
")",
"as",
"mock_setup_entry",
":",
"result4",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_configure",
"(",
"result",
"[",
"\"flow_id\"",
"]",
",",
"{",
"VERIFICATION_CODE_KEY",
":",
"\"correct\"",
"}",
",",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"len",
"(",
"mock_send_verification_code",
".",
"mock_calls",
")",
"==",
"0",
"assert",
"len",
"(",
"mock_validate_verification_code",
".",
"mock_calls",
")",
"==",
"1",
"assert",
"result4",
"[",
"\"type\"",
"]",
"==",
"\"create_entry\"",
"assert",
"result4",
"[",
"\"title\"",
"]",
"==",
"\"[email protected]\"",
"assert",
"result4",
"[",
"\"data\"",
"]",
"==",
"{",
"CONF_LOGIN_METHOD",
":",
"\"email\"",
",",
"CONF_USERNAME",
":",
"\"[email protected]\"",
",",
"CONF_PASSWORD",
":",
"\"test-password\"",
",",
"CONF_INSTALL_ID",
":",
"None",
",",
"CONF_TIMEOUT",
":",
"10",
",",
"CONF_ACCESS_TOKEN_CACHE_FILE",
":",
"\"[email protected]\"",
",",
"}",
"assert",
"len",
"(",
"mock_setup",
".",
"mock_calls",
")",
"==",
"1",
"assert",
"len",
"(",
"mock_setup_entry",
".",
"mock_calls",
")",
"==",
"1"
] | [
133,
0
] | [
222,
48
] | python | en | ['en', 'en', 'en'] | True |
test_form_reauth | (hass) | Test reauthenticate. | Test reauthenticate. | async def test_form_reauth(hass):
"""Test reauthenticate."""
entry = MockConfigEntry(
domain=DOMAIN,
data={
CONF_LOGIN_METHOD: "email",
CONF_USERNAME: "[email protected]",
CONF_PASSWORD: "test-password",
CONF_INSTALL_ID: None,
CONF_TIMEOUT: 10,
CONF_ACCESS_TOKEN_CACHE_FILE: "[email protected]",
},
unique_id="[email protected]",
)
entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": "reauth"}, data=entry.data
)
assert result["type"] == "form"
assert result["errors"] == {}
with patch(
"homeassistant.components.august.config_flow.AugustGateway.async_authenticate",
return_value=True,
), patch(
"homeassistant.components.august.async_setup", return_value=True
) as mock_setup, patch(
"homeassistant.components.august.async_setup_entry",
return_value=True,
) as mock_setup_entry:
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_PASSWORD: "new-test-password",
},
)
await hass.async_block_till_done()
assert result2["type"] == "abort"
assert result2["reason"] == "reauth_successful"
assert len(mock_setup.mock_calls) == 1
assert len(mock_setup_entry.mock_calls) == 1 | [
"async",
"def",
"test_form_reauth",
"(",
"hass",
")",
":",
"entry",
"=",
"MockConfigEntry",
"(",
"domain",
"=",
"DOMAIN",
",",
"data",
"=",
"{",
"CONF_LOGIN_METHOD",
":",
"\"email\"",
",",
"CONF_USERNAME",
":",
"\"[email protected]\"",
",",
"CONF_PASSWORD",
":",
"\"test-password\"",
",",
"CONF_INSTALL_ID",
":",
"None",
",",
"CONF_TIMEOUT",
":",
"10",
",",
"CONF_ACCESS_TOKEN_CACHE_FILE",
":",
"\"[email protected]\"",
",",
"}",
",",
"unique_id",
"=",
"\"[email protected]\"",
",",
")",
"entry",
".",
"add_to_hass",
"(",
"hass",
")",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"\"reauth\"",
"}",
",",
"data",
"=",
"entry",
".",
"data",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"\"form\"",
"assert",
"result",
"[",
"\"errors\"",
"]",
"==",
"{",
"}",
"with",
"patch",
"(",
"\"homeassistant.components.august.config_flow.AugustGateway.async_authenticate\"",
",",
"return_value",
"=",
"True",
",",
")",
",",
"patch",
"(",
"\"homeassistant.components.august.async_setup\"",
",",
"return_value",
"=",
"True",
")",
"as",
"mock_setup",
",",
"patch",
"(",
"\"homeassistant.components.august.async_setup_entry\"",
",",
"return_value",
"=",
"True",
",",
")",
"as",
"mock_setup_entry",
":",
"result2",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_configure",
"(",
"result",
"[",
"\"flow_id\"",
"]",
",",
"{",
"CONF_PASSWORD",
":",
"\"new-test-password\"",
",",
"}",
",",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"result2",
"[",
"\"type\"",
"]",
"==",
"\"abort\"",
"assert",
"result2",
"[",
"\"reason\"",
"]",
"==",
"\"reauth_successful\"",
"assert",
"len",
"(",
"mock_setup",
".",
"mock_calls",
")",
"==",
"1",
"assert",
"len",
"(",
"mock_setup_entry",
".",
"mock_calls",
")",
"==",
"1"
] | [
225,
0
] | [
268,
48
] | python | de | ['de', 'en', 'it'] | False |
mirobo_is_got_error_fixture | () | Mock mock_mirobo. | Mock mock_mirobo. | def mirobo_is_got_error_fixture():
"""Mock mock_mirobo."""
mock_vacuum = MagicMock()
mock_vacuum.status().data = {"test": "raw"}
mock_vacuum.status().is_on = False
mock_vacuum.status().fanspeed = 38
mock_vacuum.status().got_error = True
mock_vacuum.status().error = "Error message"
mock_vacuum.status().battery = 82
mock_vacuum.status().clean_area = 123.43218
mock_vacuum.status().clean_time = timedelta(hours=2, minutes=35, seconds=34)
mock_vacuum.consumable_status().main_brush_left = timedelta(
hours=12, minutes=35, seconds=34
)
mock_vacuum.consumable_status().side_brush_left = timedelta(
hours=12, minutes=35, seconds=34
)
mock_vacuum.consumable_status().filter_left = timedelta(
hours=12, minutes=35, seconds=34
)
mock_vacuum.clean_history().count = "35"
mock_vacuum.clean_history().total_area = 123.43218
mock_vacuum.clean_history().total_duration = timedelta(
hours=11, minutes=35, seconds=34
)
mock_vacuum.status().state = "Test Xiaomi Charging"
mock_vacuum.dnd_status().enabled = True
mock_vacuum.dnd_status().start = time(hour=22, minute=0)
mock_vacuum.dnd_status().end = time(hour=6, minute=0)
mock_timer_1 = MagicMock()
mock_timer_1.enabled = True
mock_timer_1.cron = "5 5 1 8 1"
mock_timer_1.next_schedule = datetime(2020, 5, 23, 13, 21, 10, tzinfo=utc)
mock_timer_2 = MagicMock()
mock_timer_2.enabled = False
mock_timer_2.cron = "5 5 1 8 2"
mock_timer_2.next_schedule = datetime(2020, 5, 23, 13, 21, 10, tzinfo=utc)
mock_vacuum.timer.return_value = [mock_timer_1, mock_timer_2]
with patch("homeassistant.components.xiaomi_miio.vacuum.Vacuum") as mock_vaccum_cls:
mock_vaccum_cls.return_value = mock_vacuum
yield mock_vacuum | [
"def",
"mirobo_is_got_error_fixture",
"(",
")",
":",
"mock_vacuum",
"=",
"MagicMock",
"(",
")",
"mock_vacuum",
".",
"status",
"(",
")",
".",
"data",
"=",
"{",
"\"test\"",
":",
"\"raw\"",
"}",
"mock_vacuum",
".",
"status",
"(",
")",
".",
"is_on",
"=",
"False",
"mock_vacuum",
".",
"status",
"(",
")",
".",
"fanspeed",
"=",
"38",
"mock_vacuum",
".",
"status",
"(",
")",
".",
"got_error",
"=",
"True",
"mock_vacuum",
".",
"status",
"(",
")",
".",
"error",
"=",
"\"Error message\"",
"mock_vacuum",
".",
"status",
"(",
")",
".",
"battery",
"=",
"82",
"mock_vacuum",
".",
"status",
"(",
")",
".",
"clean_area",
"=",
"123.43218",
"mock_vacuum",
".",
"status",
"(",
")",
".",
"clean_time",
"=",
"timedelta",
"(",
"hours",
"=",
"2",
",",
"minutes",
"=",
"35",
",",
"seconds",
"=",
"34",
")",
"mock_vacuum",
".",
"consumable_status",
"(",
")",
".",
"main_brush_left",
"=",
"timedelta",
"(",
"hours",
"=",
"12",
",",
"minutes",
"=",
"35",
",",
"seconds",
"=",
"34",
")",
"mock_vacuum",
".",
"consumable_status",
"(",
")",
".",
"side_brush_left",
"=",
"timedelta",
"(",
"hours",
"=",
"12",
",",
"minutes",
"=",
"35",
",",
"seconds",
"=",
"34",
")",
"mock_vacuum",
".",
"consumable_status",
"(",
")",
".",
"filter_left",
"=",
"timedelta",
"(",
"hours",
"=",
"12",
",",
"minutes",
"=",
"35",
",",
"seconds",
"=",
"34",
")",
"mock_vacuum",
".",
"clean_history",
"(",
")",
".",
"count",
"=",
"\"35\"",
"mock_vacuum",
".",
"clean_history",
"(",
")",
".",
"total_area",
"=",
"123.43218",
"mock_vacuum",
".",
"clean_history",
"(",
")",
".",
"total_duration",
"=",
"timedelta",
"(",
"hours",
"=",
"11",
",",
"minutes",
"=",
"35",
",",
"seconds",
"=",
"34",
")",
"mock_vacuum",
".",
"status",
"(",
")",
".",
"state",
"=",
"\"Test Xiaomi Charging\"",
"mock_vacuum",
".",
"dnd_status",
"(",
")",
".",
"enabled",
"=",
"True",
"mock_vacuum",
".",
"dnd_status",
"(",
")",
".",
"start",
"=",
"time",
"(",
"hour",
"=",
"22",
",",
"minute",
"=",
"0",
")",
"mock_vacuum",
".",
"dnd_status",
"(",
")",
".",
"end",
"=",
"time",
"(",
"hour",
"=",
"6",
",",
"minute",
"=",
"0",
")",
"mock_timer_1",
"=",
"MagicMock",
"(",
")",
"mock_timer_1",
".",
"enabled",
"=",
"True",
"mock_timer_1",
".",
"cron",
"=",
"\"5 5 1 8 1\"",
"mock_timer_1",
".",
"next_schedule",
"=",
"datetime",
"(",
"2020",
",",
"5",
",",
"23",
",",
"13",
",",
"21",
",",
"10",
",",
"tzinfo",
"=",
"utc",
")",
"mock_timer_2",
"=",
"MagicMock",
"(",
")",
"mock_timer_2",
".",
"enabled",
"=",
"False",
"mock_timer_2",
".",
"cron",
"=",
"\"5 5 1 8 2\"",
"mock_timer_2",
".",
"next_schedule",
"=",
"datetime",
"(",
"2020",
",",
"5",
",",
"23",
",",
"13",
",",
"21",
",",
"10",
",",
"tzinfo",
"=",
"utc",
")",
"mock_vacuum",
".",
"timer",
".",
"return_value",
"=",
"[",
"mock_timer_1",
",",
"mock_timer_2",
"]",
"with",
"patch",
"(",
"\"homeassistant.components.xiaomi_miio.vacuum.Vacuum\"",
")",
"as",
"mock_vaccum_cls",
":",
"mock_vaccum_cls",
".",
"return_value",
"=",
"mock_vacuum",
"yield",
"mock_vacuum"
] | [
74,
0
] | [
118,
25
] | python | en | ['en', 'xh', 'pl'] | False |
mirobo_old_speeds_fixture | (request) | Fixture for testing both types of fanspeeds. | Fixture for testing both types of fanspeeds. | def mirobo_old_speeds_fixture(request):
"""Fixture for testing both types of fanspeeds."""
mock_vacuum = MagicMock()
mock_vacuum.status().battery = 32
mock_vacuum.fan_speed_presets.return_value = request.param
mock_vacuum.status().fanspeed = list(request.param.values())[0]
with patch("homeassistant.components.xiaomi_miio.vacuum.Vacuum") as mock_vaccum_cls:
mock_vaccum_cls.return_value = mock_vacuum
yield mock_vacuum | [
"def",
"mirobo_old_speeds_fixture",
"(",
"request",
")",
":",
"mock_vacuum",
"=",
"MagicMock",
"(",
")",
"mock_vacuum",
".",
"status",
"(",
")",
".",
"battery",
"=",
"32",
"mock_vacuum",
".",
"fan_speed_presets",
".",
"return_value",
"=",
"request",
".",
"param",
"mock_vacuum",
".",
"status",
"(",
")",
".",
"fanspeed",
"=",
"list",
"(",
"request",
".",
"param",
".",
"values",
"(",
")",
")",
"[",
"0",
"]",
"with",
"patch",
"(",
"\"homeassistant.components.xiaomi_miio.vacuum.Vacuum\"",
")",
"as",
"mock_vaccum_cls",
":",
"mock_vaccum_cls",
".",
"return_value",
"=",
"mock_vacuum",
"yield",
"mock_vacuum"
] | [
137,
0
] | [
146,
25
] | python | en | ['en', 'en', 'en'] | True |
mirobo_is_on_fixture | () | Mock mock_mirobo. | Mock mock_mirobo. | def mirobo_is_on_fixture():
"""Mock mock_mirobo."""
mock_vacuum = MagicMock()
mock_vacuum.status().data = {"test": "raw"}
mock_vacuum.status().is_on = True
mock_vacuum.status().fanspeed = 99
mock_vacuum.status().got_error = False
mock_vacuum.status().battery = 32
mock_vacuum.status().clean_area = 133.43218
mock_vacuum.status().clean_time = timedelta(hours=2, minutes=55, seconds=34)
mock_vacuum.consumable_status().main_brush_left = timedelta(
hours=11, minutes=35, seconds=34
)
mock_vacuum.consumable_status().side_brush_left = timedelta(
hours=11, minutes=35, seconds=34
)
mock_vacuum.consumable_status().filter_left = timedelta(
hours=11, minutes=35, seconds=34
)
mock_vacuum.clean_history().count = "41"
mock_vacuum.clean_history().total_area = 323.43218
mock_vacuum.clean_history().total_duration = timedelta(
hours=11, minutes=15, seconds=34
)
mock_vacuum.status().state = "Test Xiaomi Cleaning"
mock_vacuum.status().state_code = 5
mock_vacuum.dnd_status().enabled = False
mock_timer_1 = MagicMock()
mock_timer_1.enabled = True
mock_timer_1.cron = "5 5 1 8 1"
mock_timer_1.next_schedule = datetime(2020, 5, 23, 13, 21, 10, tzinfo=utc)
mock_timer_2 = MagicMock()
mock_timer_2.enabled = False
mock_timer_2.cron = "5 5 1 8 2"
mock_timer_2.next_schedule = datetime(2020, 5, 23, 13, 21, 10, tzinfo=utc)
mock_vacuum.timer.return_value = [mock_timer_1, mock_timer_2]
with patch("homeassistant.components.xiaomi_miio.vacuum.Vacuum") as mock_vaccum_cls:
mock_vaccum_cls.return_value = mock_vacuum
yield mock_vacuum | [
"def",
"mirobo_is_on_fixture",
"(",
")",
":",
"mock_vacuum",
"=",
"MagicMock",
"(",
")",
"mock_vacuum",
".",
"status",
"(",
")",
".",
"data",
"=",
"{",
"\"test\"",
":",
"\"raw\"",
"}",
"mock_vacuum",
".",
"status",
"(",
")",
".",
"is_on",
"=",
"True",
"mock_vacuum",
".",
"status",
"(",
")",
".",
"fanspeed",
"=",
"99",
"mock_vacuum",
".",
"status",
"(",
")",
".",
"got_error",
"=",
"False",
"mock_vacuum",
".",
"status",
"(",
")",
".",
"battery",
"=",
"32",
"mock_vacuum",
".",
"status",
"(",
")",
".",
"clean_area",
"=",
"133.43218",
"mock_vacuum",
".",
"status",
"(",
")",
".",
"clean_time",
"=",
"timedelta",
"(",
"hours",
"=",
"2",
",",
"minutes",
"=",
"55",
",",
"seconds",
"=",
"34",
")",
"mock_vacuum",
".",
"consumable_status",
"(",
")",
".",
"main_brush_left",
"=",
"timedelta",
"(",
"hours",
"=",
"11",
",",
"minutes",
"=",
"35",
",",
"seconds",
"=",
"34",
")",
"mock_vacuum",
".",
"consumable_status",
"(",
")",
".",
"side_brush_left",
"=",
"timedelta",
"(",
"hours",
"=",
"11",
",",
"minutes",
"=",
"35",
",",
"seconds",
"=",
"34",
")",
"mock_vacuum",
".",
"consumable_status",
"(",
")",
".",
"filter_left",
"=",
"timedelta",
"(",
"hours",
"=",
"11",
",",
"minutes",
"=",
"35",
",",
"seconds",
"=",
"34",
")",
"mock_vacuum",
".",
"clean_history",
"(",
")",
".",
"count",
"=",
"\"41\"",
"mock_vacuum",
".",
"clean_history",
"(",
")",
".",
"total_area",
"=",
"323.43218",
"mock_vacuum",
".",
"clean_history",
"(",
")",
".",
"total_duration",
"=",
"timedelta",
"(",
"hours",
"=",
"11",
",",
"minutes",
"=",
"15",
",",
"seconds",
"=",
"34",
")",
"mock_vacuum",
".",
"status",
"(",
")",
".",
"state",
"=",
"\"Test Xiaomi Cleaning\"",
"mock_vacuum",
".",
"status",
"(",
")",
".",
"state_code",
"=",
"5",
"mock_vacuum",
".",
"dnd_status",
"(",
")",
".",
"enabled",
"=",
"False",
"mock_timer_1",
"=",
"MagicMock",
"(",
")",
"mock_timer_1",
".",
"enabled",
"=",
"True",
"mock_timer_1",
".",
"cron",
"=",
"\"5 5 1 8 1\"",
"mock_timer_1",
".",
"next_schedule",
"=",
"datetime",
"(",
"2020",
",",
"5",
",",
"23",
",",
"13",
",",
"21",
",",
"10",
",",
"tzinfo",
"=",
"utc",
")",
"mock_timer_2",
"=",
"MagicMock",
"(",
")",
"mock_timer_2",
".",
"enabled",
"=",
"False",
"mock_timer_2",
".",
"cron",
"=",
"\"5 5 1 8 2\"",
"mock_timer_2",
".",
"next_schedule",
"=",
"datetime",
"(",
"2020",
",",
"5",
",",
"23",
",",
"13",
",",
"21",
",",
"10",
",",
"tzinfo",
"=",
"utc",
")",
"mock_vacuum",
".",
"timer",
".",
"return_value",
"=",
"[",
"mock_timer_1",
",",
"mock_timer_2",
"]",
"with",
"patch",
"(",
"\"homeassistant.components.xiaomi_miio.vacuum.Vacuum\"",
")",
"as",
"mock_vaccum_cls",
":",
"mock_vaccum_cls",
".",
"return_value",
"=",
"mock_vacuum",
"yield",
"mock_vacuum"
] | [
150,
0
] | [
192,
25
] | python | en | ['en', 'xh', 'pl'] | False |
test_xiaomi_exceptions | (hass, caplog, mock_mirobo_is_on) | Test error logging on exceptions. | Test error logging on exceptions. | async def test_xiaomi_exceptions(hass, caplog, mock_mirobo_is_on):
"""Test error logging on exceptions."""
entity_name = "test_vacuum_cleaner_error"
entity_id = await setup_component(hass, entity_name)
def is_available():
state = hass.states.get(entity_id)
return state.state != STATE_UNAVAILABLE
# The initial setup has to be done successfully
assert "Initializing with host 192.168.1.100 (token 12345...)" in caplog.text
assert "WARNING" not in caplog.text
assert is_available()
# Second update causes an exception, which should be logged
mock_mirobo_is_on.status.side_effect = DeviceException("dummy exception")
await hass.helpers.entity_component.async_update_entity(entity_id)
assert "WARNING" in caplog.text
assert "Got exception while fetching the state" in caplog.text
assert not is_available()
# Third update does not get logged as the device is already unavailable,
# so we clear the log and reset the status to test that
caplog.clear()
mock_mirobo_is_on.status.reset_mock()
await hass.helpers.entity_component.async_update_entity(entity_id)
assert "Got exception while fetching the state" not in caplog.text
assert not is_available()
assert mock_mirobo_is_on.status.call_count == 1 | [
"async",
"def",
"test_xiaomi_exceptions",
"(",
"hass",
",",
"caplog",
",",
"mock_mirobo_is_on",
")",
":",
"entity_name",
"=",
"\"test_vacuum_cleaner_error\"",
"entity_id",
"=",
"await",
"setup_component",
"(",
"hass",
",",
"entity_name",
")",
"def",
"is_available",
"(",
")",
":",
"state",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"entity_id",
")",
"return",
"state",
".",
"state",
"!=",
"STATE_UNAVAILABLE",
"# The initial setup has to be done successfully",
"assert",
"\"Initializing with host 192.168.1.100 (token 12345...)\"",
"in",
"caplog",
".",
"text",
"assert",
"\"WARNING\"",
"not",
"in",
"caplog",
".",
"text",
"assert",
"is_available",
"(",
")",
"# Second update causes an exception, which should be logged",
"mock_mirobo_is_on",
".",
"status",
".",
"side_effect",
"=",
"DeviceException",
"(",
"\"dummy exception\"",
")",
"await",
"hass",
".",
"helpers",
".",
"entity_component",
".",
"async_update_entity",
"(",
"entity_id",
")",
"assert",
"\"WARNING\"",
"in",
"caplog",
".",
"text",
"assert",
"\"Got exception while fetching the state\"",
"in",
"caplog",
".",
"text",
"assert",
"not",
"is_available",
"(",
")",
"# Third update does not get logged as the device is already unavailable,",
"# so we clear the log and reset the status to test that",
"caplog",
".",
"clear",
"(",
")",
"mock_mirobo_is_on",
".",
"status",
".",
"reset_mock",
"(",
")",
"await",
"hass",
".",
"helpers",
".",
"entity_component",
".",
"async_update_entity",
"(",
"entity_id",
")",
"assert",
"\"Got exception while fetching the state\"",
"not",
"in",
"caplog",
".",
"text",
"assert",
"not",
"is_available",
"(",
")",
"assert",
"mock_mirobo_is_on",
".",
"status",
".",
"call_count",
"==",
"1"
] | [
195,
0
] | [
224,
51
] | python | en | ['en', 'de', 'en'] | True |
test_xiaomi_vacuum_services | (hass, caplog, mock_mirobo_is_got_error) | Test vacuum supported features. | Test vacuum supported features. | async def test_xiaomi_vacuum_services(hass, caplog, mock_mirobo_is_got_error):
"""Test vacuum supported features."""
entity_name = "test_vacuum_cleaner_1"
entity_id = await setup_component(hass, entity_name)
assert "Initializing with host 192.168.1.100 (token 12345...)" in caplog.text
# Check state attributes
state = hass.states.get(entity_id)
assert state.state == STATE_ERROR
assert state.attributes.get(ATTR_SUPPORTED_FEATURES) == 14204
assert state.attributes.get(ATTR_DO_NOT_DISTURB) == STATE_ON
assert state.attributes.get(ATTR_DO_NOT_DISTURB_START) == "22:00:00"
assert state.attributes.get(ATTR_DO_NOT_DISTURB_END) == "06:00:00"
assert state.attributes.get(ATTR_ERROR) == "Error message"
assert state.attributes.get(ATTR_BATTERY_ICON) == "mdi:battery-80"
assert state.attributes.get(ATTR_CLEANING_TIME) == 155
assert state.attributes.get(ATTR_CLEANED_AREA) == 123
assert state.attributes.get(ATTR_MAIN_BRUSH_LEFT) == 12
assert state.attributes.get(ATTR_SIDE_BRUSH_LEFT) == 12
assert state.attributes.get(ATTR_FILTER_LEFT) == 12
assert state.attributes.get(ATTR_CLEANING_COUNT) == 35
assert state.attributes.get(ATTR_CLEANED_TOTAL_AREA) == 123
assert state.attributes.get(ATTR_CLEANING_TOTAL_TIME) == 695
assert state.attributes.get(ATTR_TIMERS) == [
{
"enabled": True,
"cron": "5 5 1 8 1",
"next_schedule": datetime(2020, 5, 23, 13, 21, 10, tzinfo=utc),
},
{
"enabled": False,
"cron": "5 5 1 8 2",
"next_schedule": datetime(2020, 5, 23, 13, 21, 10, tzinfo=utc),
},
]
# Call services
await hass.services.async_call(
DOMAIN, SERVICE_START, {"entity_id": entity_id}, blocking=True
)
mock_mirobo_is_got_error.assert_has_calls(
[mock.call.resume_or_start()], any_order=True
)
mock_mirobo_is_got_error.assert_has_calls(STATUS_CALLS, any_order=True)
mock_mirobo_is_got_error.reset_mock()
await hass.services.async_call(
DOMAIN, SERVICE_STOP, {"entity_id": entity_id}, blocking=True
)
mock_mirobo_is_got_error.assert_has_calls([mock.call.stop()], any_order=True)
mock_mirobo_is_got_error.assert_has_calls(STATUS_CALLS, any_order=True)
mock_mirobo_is_got_error.reset_mock()
await hass.services.async_call(
DOMAIN, SERVICE_RETURN_TO_BASE, {"entity_id": entity_id}, blocking=True
)
mock_mirobo_is_got_error.assert_has_calls([mock.call.home()], any_order=True)
mock_mirobo_is_got_error.assert_has_calls(STATUS_CALLS, any_order=True)
mock_mirobo_is_got_error.reset_mock()
await hass.services.async_call(
DOMAIN, SERVICE_LOCATE, {"entity_id": entity_id}, blocking=True
)
mock_mirobo_is_got_error.assert_has_calls([mock.call.find()], any_order=True)
mock_mirobo_is_got_error.assert_has_calls(STATUS_CALLS, any_order=True)
mock_mirobo_is_got_error.reset_mock()
await hass.services.async_call(
DOMAIN, SERVICE_CLEAN_SPOT, {"entity_id": entity_id}, blocking=True
)
mock_mirobo_is_got_error.assert_has_calls([mock.call.spot()], any_order=True)
mock_mirobo_is_got_error.assert_has_calls(STATUS_CALLS, any_order=True)
mock_mirobo_is_got_error.reset_mock()
await hass.services.async_call(
DOMAIN,
SERVICE_SEND_COMMAND,
{"entity_id": entity_id, "command": "raw"},
blocking=True,
)
mock_mirobo_is_got_error.assert_has_calls(
[mock.call.raw_command("raw", None)], any_order=True
)
mock_mirobo_is_got_error.assert_has_calls(STATUS_CALLS, any_order=True)
mock_mirobo_is_got_error.reset_mock()
await hass.services.async_call(
DOMAIN,
SERVICE_SEND_COMMAND,
{"entity_id": entity_id, "command": "raw", "params": {"k1": 2}},
blocking=True,
)
mock_mirobo_is_got_error.assert_has_calls(
[mock.call.raw_command("raw", {"k1": 2})], any_order=True
)
mock_mirobo_is_got_error.assert_has_calls(STATUS_CALLS, any_order=True)
mock_mirobo_is_got_error.reset_mock() | [
"async",
"def",
"test_xiaomi_vacuum_services",
"(",
"hass",
",",
"caplog",
",",
"mock_mirobo_is_got_error",
")",
":",
"entity_name",
"=",
"\"test_vacuum_cleaner_1\"",
"entity_id",
"=",
"await",
"setup_component",
"(",
"hass",
",",
"entity_name",
")",
"assert",
"\"Initializing with host 192.168.1.100 (token 12345...)\"",
"in",
"caplog",
".",
"text",
"# Check state attributes",
"state",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"entity_id",
")",
"assert",
"state",
".",
"state",
"==",
"STATE_ERROR",
"assert",
"state",
".",
"attributes",
".",
"get",
"(",
"ATTR_SUPPORTED_FEATURES",
")",
"==",
"14204",
"assert",
"state",
".",
"attributes",
".",
"get",
"(",
"ATTR_DO_NOT_DISTURB",
")",
"==",
"STATE_ON",
"assert",
"state",
".",
"attributes",
".",
"get",
"(",
"ATTR_DO_NOT_DISTURB_START",
")",
"==",
"\"22:00:00\"",
"assert",
"state",
".",
"attributes",
".",
"get",
"(",
"ATTR_DO_NOT_DISTURB_END",
")",
"==",
"\"06:00:00\"",
"assert",
"state",
".",
"attributes",
".",
"get",
"(",
"ATTR_ERROR",
")",
"==",
"\"Error message\"",
"assert",
"state",
".",
"attributes",
".",
"get",
"(",
"ATTR_BATTERY_ICON",
")",
"==",
"\"mdi:battery-80\"",
"assert",
"state",
".",
"attributes",
".",
"get",
"(",
"ATTR_CLEANING_TIME",
")",
"==",
"155",
"assert",
"state",
".",
"attributes",
".",
"get",
"(",
"ATTR_CLEANED_AREA",
")",
"==",
"123",
"assert",
"state",
".",
"attributes",
".",
"get",
"(",
"ATTR_MAIN_BRUSH_LEFT",
")",
"==",
"12",
"assert",
"state",
".",
"attributes",
".",
"get",
"(",
"ATTR_SIDE_BRUSH_LEFT",
")",
"==",
"12",
"assert",
"state",
".",
"attributes",
".",
"get",
"(",
"ATTR_FILTER_LEFT",
")",
"==",
"12",
"assert",
"state",
".",
"attributes",
".",
"get",
"(",
"ATTR_CLEANING_COUNT",
")",
"==",
"35",
"assert",
"state",
".",
"attributes",
".",
"get",
"(",
"ATTR_CLEANED_TOTAL_AREA",
")",
"==",
"123",
"assert",
"state",
".",
"attributes",
".",
"get",
"(",
"ATTR_CLEANING_TOTAL_TIME",
")",
"==",
"695",
"assert",
"state",
".",
"attributes",
".",
"get",
"(",
"ATTR_TIMERS",
")",
"==",
"[",
"{",
"\"enabled\"",
":",
"True",
",",
"\"cron\"",
":",
"\"5 5 1 8 1\"",
",",
"\"next_schedule\"",
":",
"datetime",
"(",
"2020",
",",
"5",
",",
"23",
",",
"13",
",",
"21",
",",
"10",
",",
"tzinfo",
"=",
"utc",
")",
",",
"}",
",",
"{",
"\"enabled\"",
":",
"False",
",",
"\"cron\"",
":",
"\"5 5 1 8 2\"",
",",
"\"next_schedule\"",
":",
"datetime",
"(",
"2020",
",",
"5",
",",
"23",
",",
"13",
",",
"21",
",",
"10",
",",
"tzinfo",
"=",
"utc",
")",
",",
"}",
",",
"]",
"# Call services",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"DOMAIN",
",",
"SERVICE_START",
",",
"{",
"\"entity_id\"",
":",
"entity_id",
"}",
",",
"blocking",
"=",
"True",
")",
"mock_mirobo_is_got_error",
".",
"assert_has_calls",
"(",
"[",
"mock",
".",
"call",
".",
"resume_or_start",
"(",
")",
"]",
",",
"any_order",
"=",
"True",
")",
"mock_mirobo_is_got_error",
".",
"assert_has_calls",
"(",
"STATUS_CALLS",
",",
"any_order",
"=",
"True",
")",
"mock_mirobo_is_got_error",
".",
"reset_mock",
"(",
")",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"DOMAIN",
",",
"SERVICE_STOP",
",",
"{",
"\"entity_id\"",
":",
"entity_id",
"}",
",",
"blocking",
"=",
"True",
")",
"mock_mirobo_is_got_error",
".",
"assert_has_calls",
"(",
"[",
"mock",
".",
"call",
".",
"stop",
"(",
")",
"]",
",",
"any_order",
"=",
"True",
")",
"mock_mirobo_is_got_error",
".",
"assert_has_calls",
"(",
"STATUS_CALLS",
",",
"any_order",
"=",
"True",
")",
"mock_mirobo_is_got_error",
".",
"reset_mock",
"(",
")",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"DOMAIN",
",",
"SERVICE_RETURN_TO_BASE",
",",
"{",
"\"entity_id\"",
":",
"entity_id",
"}",
",",
"blocking",
"=",
"True",
")",
"mock_mirobo_is_got_error",
".",
"assert_has_calls",
"(",
"[",
"mock",
".",
"call",
".",
"home",
"(",
")",
"]",
",",
"any_order",
"=",
"True",
")",
"mock_mirobo_is_got_error",
".",
"assert_has_calls",
"(",
"STATUS_CALLS",
",",
"any_order",
"=",
"True",
")",
"mock_mirobo_is_got_error",
".",
"reset_mock",
"(",
")",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"DOMAIN",
",",
"SERVICE_LOCATE",
",",
"{",
"\"entity_id\"",
":",
"entity_id",
"}",
",",
"blocking",
"=",
"True",
")",
"mock_mirobo_is_got_error",
".",
"assert_has_calls",
"(",
"[",
"mock",
".",
"call",
".",
"find",
"(",
")",
"]",
",",
"any_order",
"=",
"True",
")",
"mock_mirobo_is_got_error",
".",
"assert_has_calls",
"(",
"STATUS_CALLS",
",",
"any_order",
"=",
"True",
")",
"mock_mirobo_is_got_error",
".",
"reset_mock",
"(",
")",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"DOMAIN",
",",
"SERVICE_CLEAN_SPOT",
",",
"{",
"\"entity_id\"",
":",
"entity_id",
"}",
",",
"blocking",
"=",
"True",
")",
"mock_mirobo_is_got_error",
".",
"assert_has_calls",
"(",
"[",
"mock",
".",
"call",
".",
"spot",
"(",
")",
"]",
",",
"any_order",
"=",
"True",
")",
"mock_mirobo_is_got_error",
".",
"assert_has_calls",
"(",
"STATUS_CALLS",
",",
"any_order",
"=",
"True",
")",
"mock_mirobo_is_got_error",
".",
"reset_mock",
"(",
")",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"DOMAIN",
",",
"SERVICE_SEND_COMMAND",
",",
"{",
"\"entity_id\"",
":",
"entity_id",
",",
"\"command\"",
":",
"\"raw\"",
"}",
",",
"blocking",
"=",
"True",
",",
")",
"mock_mirobo_is_got_error",
".",
"assert_has_calls",
"(",
"[",
"mock",
".",
"call",
".",
"raw_command",
"(",
"\"raw\"",
",",
"None",
")",
"]",
",",
"any_order",
"=",
"True",
")",
"mock_mirobo_is_got_error",
".",
"assert_has_calls",
"(",
"STATUS_CALLS",
",",
"any_order",
"=",
"True",
")",
"mock_mirobo_is_got_error",
".",
"reset_mock",
"(",
")",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"DOMAIN",
",",
"SERVICE_SEND_COMMAND",
",",
"{",
"\"entity_id\"",
":",
"entity_id",
",",
"\"command\"",
":",
"\"raw\"",
",",
"\"params\"",
":",
"{",
"\"k1\"",
":",
"2",
"}",
"}",
",",
"blocking",
"=",
"True",
",",
")",
"mock_mirobo_is_got_error",
".",
"assert_has_calls",
"(",
"[",
"mock",
".",
"call",
".",
"raw_command",
"(",
"\"raw\"",
",",
"{",
"\"k1\"",
":",
"2",
"}",
")",
"]",
",",
"any_order",
"=",
"True",
")",
"mock_mirobo_is_got_error",
".",
"assert_has_calls",
"(",
"STATUS_CALLS",
",",
"any_order",
"=",
"True",
")",
"mock_mirobo_is_got_error",
".",
"reset_mock",
"(",
")"
] | [
227,
0
] | [
325,
41
] | python | en | ['en', 'en', 'en'] | True |
test_xiaomi_specific_services | (hass, caplog, mock_mirobo_is_on) | Test vacuum supported features. | Test vacuum supported features. | async def test_xiaomi_specific_services(hass, caplog, mock_mirobo_is_on):
"""Test vacuum supported features."""
entity_name = "test_vacuum_cleaner_2"
entity_id = await setup_component(hass, entity_name)
assert "Initializing with host 192.168.1.100 (token 12345" in caplog.text
# Check state attributes
state = hass.states.get(entity_id)
assert state.state == STATE_CLEANING
assert state.attributes.get(ATTR_SUPPORTED_FEATURES) == 14204
assert state.attributes.get(ATTR_DO_NOT_DISTURB) == STATE_OFF
assert state.attributes.get(ATTR_ERROR) is None
assert state.attributes.get(ATTR_BATTERY_ICON) == "mdi:battery-30"
assert state.attributes.get(ATTR_CLEANING_TIME) == 175
assert state.attributes.get(ATTR_CLEANED_AREA) == 133
assert state.attributes.get(ATTR_MAIN_BRUSH_LEFT) == 11
assert state.attributes.get(ATTR_SIDE_BRUSH_LEFT) == 11
assert state.attributes.get(ATTR_FILTER_LEFT) == 11
assert state.attributes.get(ATTR_CLEANING_COUNT) == 41
assert state.attributes.get(ATTR_CLEANED_TOTAL_AREA) == 323
assert state.attributes.get(ATTR_CLEANING_TOTAL_TIME) == 675
assert state.attributes.get(ATTR_TIMERS) == [
{
"enabled": True,
"cron": "5 5 1 8 1",
"next_schedule": datetime(2020, 5, 23, 13, 21, 10, tzinfo=utc),
},
{
"enabled": False,
"cron": "5 5 1 8 2",
"next_schedule": datetime(2020, 5, 23, 13, 21, 10, tzinfo=utc),
},
]
# Xiaomi vacuum specific services:
await hass.services.async_call(
XIAOMI_DOMAIN,
SERVICE_START_REMOTE_CONTROL,
{ATTR_ENTITY_ID: entity_id},
blocking=True,
)
mock_mirobo_is_on.assert_has_calls([mock.call.manual_start()], any_order=True)
mock_mirobo_is_on.assert_has_calls(STATUS_CALLS, any_order=True)
mock_mirobo_is_on.reset_mock()
control = {"duration": 1000, "rotation": -40, "velocity": -0.1}
await hass.services.async_call(
XIAOMI_DOMAIN,
SERVICE_MOVE_REMOTE_CONTROL,
{**control, ATTR_ENTITY_ID: entity_id},
blocking=True,
)
mock_mirobo_is_on.manual_control.assert_has_calls(
[mock.call(**control)], any_order=True
)
mock_mirobo_is_on.assert_has_calls(STATUS_CALLS, any_order=True)
mock_mirobo_is_on.reset_mock()
await hass.services.async_call(
XIAOMI_DOMAIN,
SERVICE_STOP_REMOTE_CONTROL,
{ATTR_ENTITY_ID: entity_id},
blocking=True,
)
mock_mirobo_is_on.assert_has_calls([mock.call.manual_stop()], any_order=True)
mock_mirobo_is_on.assert_has_calls(STATUS_CALLS, any_order=True)
mock_mirobo_is_on.reset_mock()
control_once = {"duration": 2000, "rotation": 120, "velocity": 0.1}
await hass.services.async_call(
XIAOMI_DOMAIN,
SERVICE_MOVE_REMOTE_CONTROL_STEP,
{**control_once, ATTR_ENTITY_ID: entity_id},
blocking=True,
)
mock_mirobo_is_on.manual_control_once.assert_has_calls(
[mock.call(**control_once)], any_order=True
)
mock_mirobo_is_on.assert_has_calls(STATUS_CALLS, any_order=True)
mock_mirobo_is_on.reset_mock()
control = {"zone": [[123, 123, 123, 123]], "repeats": 2}
await hass.services.async_call(
XIAOMI_DOMAIN,
SERVICE_CLEAN_ZONE,
{**control, ATTR_ENTITY_ID: entity_id},
blocking=True,
)
mock_mirobo_is_on.zoned_clean.assert_has_calls(
[mock.call([[123, 123, 123, 123, 2]])], any_order=True
)
mock_mirobo_is_on.assert_has_calls(STATUS_CALLS, any_order=True)
mock_mirobo_is_on.reset_mock() | [
"async",
"def",
"test_xiaomi_specific_services",
"(",
"hass",
",",
"caplog",
",",
"mock_mirobo_is_on",
")",
":",
"entity_name",
"=",
"\"test_vacuum_cleaner_2\"",
"entity_id",
"=",
"await",
"setup_component",
"(",
"hass",
",",
"entity_name",
")",
"assert",
"\"Initializing with host 192.168.1.100 (token 12345\"",
"in",
"caplog",
".",
"text",
"# Check state attributes",
"state",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"entity_id",
")",
"assert",
"state",
".",
"state",
"==",
"STATE_CLEANING",
"assert",
"state",
".",
"attributes",
".",
"get",
"(",
"ATTR_SUPPORTED_FEATURES",
")",
"==",
"14204",
"assert",
"state",
".",
"attributes",
".",
"get",
"(",
"ATTR_DO_NOT_DISTURB",
")",
"==",
"STATE_OFF",
"assert",
"state",
".",
"attributes",
".",
"get",
"(",
"ATTR_ERROR",
")",
"is",
"None",
"assert",
"state",
".",
"attributes",
".",
"get",
"(",
"ATTR_BATTERY_ICON",
")",
"==",
"\"mdi:battery-30\"",
"assert",
"state",
".",
"attributes",
".",
"get",
"(",
"ATTR_CLEANING_TIME",
")",
"==",
"175",
"assert",
"state",
".",
"attributes",
".",
"get",
"(",
"ATTR_CLEANED_AREA",
")",
"==",
"133",
"assert",
"state",
".",
"attributes",
".",
"get",
"(",
"ATTR_MAIN_BRUSH_LEFT",
")",
"==",
"11",
"assert",
"state",
".",
"attributes",
".",
"get",
"(",
"ATTR_SIDE_BRUSH_LEFT",
")",
"==",
"11",
"assert",
"state",
".",
"attributes",
".",
"get",
"(",
"ATTR_FILTER_LEFT",
")",
"==",
"11",
"assert",
"state",
".",
"attributes",
".",
"get",
"(",
"ATTR_CLEANING_COUNT",
")",
"==",
"41",
"assert",
"state",
".",
"attributes",
".",
"get",
"(",
"ATTR_CLEANED_TOTAL_AREA",
")",
"==",
"323",
"assert",
"state",
".",
"attributes",
".",
"get",
"(",
"ATTR_CLEANING_TOTAL_TIME",
")",
"==",
"675",
"assert",
"state",
".",
"attributes",
".",
"get",
"(",
"ATTR_TIMERS",
")",
"==",
"[",
"{",
"\"enabled\"",
":",
"True",
",",
"\"cron\"",
":",
"\"5 5 1 8 1\"",
",",
"\"next_schedule\"",
":",
"datetime",
"(",
"2020",
",",
"5",
",",
"23",
",",
"13",
",",
"21",
",",
"10",
",",
"tzinfo",
"=",
"utc",
")",
",",
"}",
",",
"{",
"\"enabled\"",
":",
"False",
",",
"\"cron\"",
":",
"\"5 5 1 8 2\"",
",",
"\"next_schedule\"",
":",
"datetime",
"(",
"2020",
",",
"5",
",",
"23",
",",
"13",
",",
"21",
",",
"10",
",",
"tzinfo",
"=",
"utc",
")",
",",
"}",
",",
"]",
"# Xiaomi vacuum specific services:",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"XIAOMI_DOMAIN",
",",
"SERVICE_START_REMOTE_CONTROL",
",",
"{",
"ATTR_ENTITY_ID",
":",
"entity_id",
"}",
",",
"blocking",
"=",
"True",
",",
")",
"mock_mirobo_is_on",
".",
"assert_has_calls",
"(",
"[",
"mock",
".",
"call",
".",
"manual_start",
"(",
")",
"]",
",",
"any_order",
"=",
"True",
")",
"mock_mirobo_is_on",
".",
"assert_has_calls",
"(",
"STATUS_CALLS",
",",
"any_order",
"=",
"True",
")",
"mock_mirobo_is_on",
".",
"reset_mock",
"(",
")",
"control",
"=",
"{",
"\"duration\"",
":",
"1000",
",",
"\"rotation\"",
":",
"-",
"40",
",",
"\"velocity\"",
":",
"-",
"0.1",
"}",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"XIAOMI_DOMAIN",
",",
"SERVICE_MOVE_REMOTE_CONTROL",
",",
"{",
"*",
"*",
"control",
",",
"ATTR_ENTITY_ID",
":",
"entity_id",
"}",
",",
"blocking",
"=",
"True",
",",
")",
"mock_mirobo_is_on",
".",
"manual_control",
".",
"assert_has_calls",
"(",
"[",
"mock",
".",
"call",
"(",
"*",
"*",
"control",
")",
"]",
",",
"any_order",
"=",
"True",
")",
"mock_mirobo_is_on",
".",
"assert_has_calls",
"(",
"STATUS_CALLS",
",",
"any_order",
"=",
"True",
")",
"mock_mirobo_is_on",
".",
"reset_mock",
"(",
")",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"XIAOMI_DOMAIN",
",",
"SERVICE_STOP_REMOTE_CONTROL",
",",
"{",
"ATTR_ENTITY_ID",
":",
"entity_id",
"}",
",",
"blocking",
"=",
"True",
",",
")",
"mock_mirobo_is_on",
".",
"assert_has_calls",
"(",
"[",
"mock",
".",
"call",
".",
"manual_stop",
"(",
")",
"]",
",",
"any_order",
"=",
"True",
")",
"mock_mirobo_is_on",
".",
"assert_has_calls",
"(",
"STATUS_CALLS",
",",
"any_order",
"=",
"True",
")",
"mock_mirobo_is_on",
".",
"reset_mock",
"(",
")",
"control_once",
"=",
"{",
"\"duration\"",
":",
"2000",
",",
"\"rotation\"",
":",
"120",
",",
"\"velocity\"",
":",
"0.1",
"}",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"XIAOMI_DOMAIN",
",",
"SERVICE_MOVE_REMOTE_CONTROL_STEP",
",",
"{",
"*",
"*",
"control_once",
",",
"ATTR_ENTITY_ID",
":",
"entity_id",
"}",
",",
"blocking",
"=",
"True",
",",
")",
"mock_mirobo_is_on",
".",
"manual_control_once",
".",
"assert_has_calls",
"(",
"[",
"mock",
".",
"call",
"(",
"*",
"*",
"control_once",
")",
"]",
",",
"any_order",
"=",
"True",
")",
"mock_mirobo_is_on",
".",
"assert_has_calls",
"(",
"STATUS_CALLS",
",",
"any_order",
"=",
"True",
")",
"mock_mirobo_is_on",
".",
"reset_mock",
"(",
")",
"control",
"=",
"{",
"\"zone\"",
":",
"[",
"[",
"123",
",",
"123",
",",
"123",
",",
"123",
"]",
"]",
",",
"\"repeats\"",
":",
"2",
"}",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"XIAOMI_DOMAIN",
",",
"SERVICE_CLEAN_ZONE",
",",
"{",
"*",
"*",
"control",
",",
"ATTR_ENTITY_ID",
":",
"entity_id",
"}",
",",
"blocking",
"=",
"True",
",",
")",
"mock_mirobo_is_on",
".",
"zoned_clean",
".",
"assert_has_calls",
"(",
"[",
"mock",
".",
"call",
"(",
"[",
"[",
"123",
",",
"123",
",",
"123",
",",
"123",
",",
"2",
"]",
"]",
")",
"]",
",",
"any_order",
"=",
"True",
")",
"mock_mirobo_is_on",
".",
"assert_has_calls",
"(",
"STATUS_CALLS",
",",
"any_order",
"=",
"True",
")",
"mock_mirobo_is_on",
".",
"reset_mock",
"(",
")"
] | [
328,
0
] | [
422,
34
] | python | en | ['en', 'en', 'en'] | True |
test_xiaomi_vacuum_fanspeeds | (hass, caplog, mock_mirobo_fanspeeds) | Test Xiaomi vacuum fanspeeds. | Test Xiaomi vacuum fanspeeds. | async def test_xiaomi_vacuum_fanspeeds(hass, caplog, mock_mirobo_fanspeeds):
"""Test Xiaomi vacuum fanspeeds."""
entity_name = "test_vacuum_cleaner_2"
entity_id = await setup_component(hass, entity_name)
assert "Initializing with host 192.168.1.100 (token 12345" in caplog.text
state = hass.states.get(entity_id)
assert state.attributes.get(ATTR_FAN_SPEED) == "Silent"
fanspeeds = state.attributes.get(ATTR_FAN_SPEED_LIST)
for speed in ["Silent", "Standard", "Medium", "Turbo"]:
assert speed in fanspeeds
# Set speed service:
await hass.services.async_call(
DOMAIN,
SERVICE_SET_FAN_SPEED,
{"entity_id": entity_id, "fan_speed": 60},
blocking=True,
)
mock_mirobo_fanspeeds.assert_has_calls(
[mock.call.set_fan_speed(60)], any_order=True
)
mock_mirobo_fanspeeds.assert_has_calls(STATUS_CALLS, any_order=True)
mock_mirobo_fanspeeds.reset_mock()
fan_speed_dict = mock_mirobo_fanspeeds.fan_speed_presets()
await hass.services.async_call(
DOMAIN,
SERVICE_SET_FAN_SPEED,
{"entity_id": entity_id, "fan_speed": "Medium"},
blocking=True,
)
mock_mirobo_fanspeeds.assert_has_calls(
[mock.call.set_fan_speed(fan_speed_dict["Medium"])], any_order=True
)
mock_mirobo_fanspeeds.assert_has_calls(STATUS_CALLS, any_order=True)
mock_mirobo_fanspeeds.reset_mock()
assert "ERROR" not in caplog.text
await hass.services.async_call(
DOMAIN,
SERVICE_SET_FAN_SPEED,
{"entity_id": entity_id, "fan_speed": "invent"},
blocking=True,
)
assert "Fan speed step not recognized" in caplog.text | [
"async",
"def",
"test_xiaomi_vacuum_fanspeeds",
"(",
"hass",
",",
"caplog",
",",
"mock_mirobo_fanspeeds",
")",
":",
"entity_name",
"=",
"\"test_vacuum_cleaner_2\"",
"entity_id",
"=",
"await",
"setup_component",
"(",
"hass",
",",
"entity_name",
")",
"assert",
"\"Initializing with host 192.168.1.100 (token 12345\"",
"in",
"caplog",
".",
"text",
"state",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"entity_id",
")",
"assert",
"state",
".",
"attributes",
".",
"get",
"(",
"ATTR_FAN_SPEED",
")",
"==",
"\"Silent\"",
"fanspeeds",
"=",
"state",
".",
"attributes",
".",
"get",
"(",
"ATTR_FAN_SPEED_LIST",
")",
"for",
"speed",
"in",
"[",
"\"Silent\"",
",",
"\"Standard\"",
",",
"\"Medium\"",
",",
"\"Turbo\"",
"]",
":",
"assert",
"speed",
"in",
"fanspeeds",
"# Set speed service:",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"DOMAIN",
",",
"SERVICE_SET_FAN_SPEED",
",",
"{",
"\"entity_id\"",
":",
"entity_id",
",",
"\"fan_speed\"",
":",
"60",
"}",
",",
"blocking",
"=",
"True",
",",
")",
"mock_mirobo_fanspeeds",
".",
"assert_has_calls",
"(",
"[",
"mock",
".",
"call",
".",
"set_fan_speed",
"(",
"60",
")",
"]",
",",
"any_order",
"=",
"True",
")",
"mock_mirobo_fanspeeds",
".",
"assert_has_calls",
"(",
"STATUS_CALLS",
",",
"any_order",
"=",
"True",
")",
"mock_mirobo_fanspeeds",
".",
"reset_mock",
"(",
")",
"fan_speed_dict",
"=",
"mock_mirobo_fanspeeds",
".",
"fan_speed_presets",
"(",
")",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"DOMAIN",
",",
"SERVICE_SET_FAN_SPEED",
",",
"{",
"\"entity_id\"",
":",
"entity_id",
",",
"\"fan_speed\"",
":",
"\"Medium\"",
"}",
",",
"blocking",
"=",
"True",
",",
")",
"mock_mirobo_fanspeeds",
".",
"assert_has_calls",
"(",
"[",
"mock",
".",
"call",
".",
"set_fan_speed",
"(",
"fan_speed_dict",
"[",
"\"Medium\"",
"]",
")",
"]",
",",
"any_order",
"=",
"True",
")",
"mock_mirobo_fanspeeds",
".",
"assert_has_calls",
"(",
"STATUS_CALLS",
",",
"any_order",
"=",
"True",
")",
"mock_mirobo_fanspeeds",
".",
"reset_mock",
"(",
")",
"assert",
"\"ERROR\"",
"not",
"in",
"caplog",
".",
"text",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"DOMAIN",
",",
"SERVICE_SET_FAN_SPEED",
",",
"{",
"\"entity_id\"",
":",
"entity_id",
",",
"\"fan_speed\"",
":",
"\"invent\"",
"}",
",",
"blocking",
"=",
"True",
",",
")",
"assert",
"\"Fan speed step not recognized\"",
"in",
"caplog",
".",
"text"
] | [
425,
0
] | [
472,
57
] | python | nl | ['de', 'nl', 'nl'] | True |
test_xiaomi_vacuum_goto_service | (hass, caplog, mock_mirobo_is_on) | Test vacuum supported features. | Test vacuum supported features. | async def test_xiaomi_vacuum_goto_service(hass, caplog, mock_mirobo_is_on):
"""Test vacuum supported features."""
entity_name = "test_vacuum_cleaner_2"
entity_id = await setup_component(hass, entity_name)
data = {"entity_id": entity_id, "x_coord": 25500, "y_coord": 25500}
await hass.services.async_call(XIAOMI_DOMAIN, SERVICE_GOTO, data, blocking=True)
mock_mirobo_is_on.goto.assert_has_calls(
[mock.call(x_coord=data["x_coord"], y_coord=data["y_coord"])], any_order=True
)
mock_mirobo_is_on.assert_has_calls(STATUS_CALLS, any_order=True) | [
"async",
"def",
"test_xiaomi_vacuum_goto_service",
"(",
"hass",
",",
"caplog",
",",
"mock_mirobo_is_on",
")",
":",
"entity_name",
"=",
"\"test_vacuum_cleaner_2\"",
"entity_id",
"=",
"await",
"setup_component",
"(",
"hass",
",",
"entity_name",
")",
"data",
"=",
"{",
"\"entity_id\"",
":",
"entity_id",
",",
"\"x_coord\"",
":",
"25500",
",",
"\"y_coord\"",
":",
"25500",
"}",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"XIAOMI_DOMAIN",
",",
"SERVICE_GOTO",
",",
"data",
",",
"blocking",
"=",
"True",
")",
"mock_mirobo_is_on",
".",
"goto",
".",
"assert_has_calls",
"(",
"[",
"mock",
".",
"call",
"(",
"x_coord",
"=",
"data",
"[",
"\"x_coord\"",
"]",
",",
"y_coord",
"=",
"data",
"[",
"\"y_coord\"",
"]",
")",
"]",
",",
"any_order",
"=",
"True",
")",
"mock_mirobo_is_on",
".",
"assert_has_calls",
"(",
"STATUS_CALLS",
",",
"any_order",
"=",
"True",
")"
] | [
475,
0
] | [
485,
68
] | python | en | ['en', 'en', 'en'] | True |
test_xiaomi_vacuum_clean_segment_service | (hass, caplog, mock_mirobo_is_on) | Test vacuum supported features. | Test vacuum supported features. | async def test_xiaomi_vacuum_clean_segment_service(hass, caplog, mock_mirobo_is_on):
"""Test vacuum supported features."""
entity_name = "test_vacuum_cleaner_2"
entity_id = await setup_component(hass, entity_name)
data = {"entity_id": entity_id, "segments": ["1", "2"]}
await hass.services.async_call(
XIAOMI_DOMAIN, SERVICE_CLEAN_SEGMENT, data, blocking=True
)
mock_mirobo_is_on.segment_clean.assert_has_calls(
[mock.call(segments=[int(i) for i in data["segments"]])], any_order=True
)
mock_mirobo_is_on.assert_has_calls(STATUS_CALLS, any_order=True) | [
"async",
"def",
"test_xiaomi_vacuum_clean_segment_service",
"(",
"hass",
",",
"caplog",
",",
"mock_mirobo_is_on",
")",
":",
"entity_name",
"=",
"\"test_vacuum_cleaner_2\"",
"entity_id",
"=",
"await",
"setup_component",
"(",
"hass",
",",
"entity_name",
")",
"data",
"=",
"{",
"\"entity_id\"",
":",
"entity_id",
",",
"\"segments\"",
":",
"[",
"\"1\"",
",",
"\"2\"",
"]",
"}",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"XIAOMI_DOMAIN",
",",
"SERVICE_CLEAN_SEGMENT",
",",
"data",
",",
"blocking",
"=",
"True",
")",
"mock_mirobo_is_on",
".",
"segment_clean",
".",
"assert_has_calls",
"(",
"[",
"mock",
".",
"call",
"(",
"segments",
"=",
"[",
"int",
"(",
"i",
")",
"for",
"i",
"in",
"data",
"[",
"\"segments\"",
"]",
"]",
")",
"]",
",",
"any_order",
"=",
"True",
")",
"mock_mirobo_is_on",
".",
"assert_has_calls",
"(",
"STATUS_CALLS",
",",
"any_order",
"=",
"True",
")"
] | [
488,
0
] | [
500,
68
] | python | en | ['en', 'en', 'en'] | True |
test_xiaomi_vacuum_clean_segment_service_single_segment | (
hass, caplog, mock_mirobo_is_on
) | Test vacuum supported features. | Test vacuum supported features. | async def test_xiaomi_vacuum_clean_segment_service_single_segment(
hass, caplog, mock_mirobo_is_on
):
"""Test vacuum supported features."""
entity_name = "test_vacuum_cleaner_2"
entity_id = await setup_component(hass, entity_name)
data = {"entity_id": entity_id, "segments": 1}
await hass.services.async_call(
XIAOMI_DOMAIN, SERVICE_CLEAN_SEGMENT, data, blocking=True
)
mock_mirobo_is_on.segment_clean.assert_has_calls(
[mock.call(segments=[data["segments"]])], any_order=True
)
mock_mirobo_is_on.assert_has_calls(STATUS_CALLS, any_order=True) | [
"async",
"def",
"test_xiaomi_vacuum_clean_segment_service_single_segment",
"(",
"hass",
",",
"caplog",
",",
"mock_mirobo_is_on",
")",
":",
"entity_name",
"=",
"\"test_vacuum_cleaner_2\"",
"entity_id",
"=",
"await",
"setup_component",
"(",
"hass",
",",
"entity_name",
")",
"data",
"=",
"{",
"\"entity_id\"",
":",
"entity_id",
",",
"\"segments\"",
":",
"1",
"}",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"XIAOMI_DOMAIN",
",",
"SERVICE_CLEAN_SEGMENT",
",",
"data",
",",
"blocking",
"=",
"True",
")",
"mock_mirobo_is_on",
".",
"segment_clean",
".",
"assert_has_calls",
"(",
"[",
"mock",
".",
"call",
"(",
"segments",
"=",
"[",
"data",
"[",
"\"segments\"",
"]",
"]",
")",
"]",
",",
"any_order",
"=",
"True",
")",
"mock_mirobo_is_on",
".",
"assert_has_calls",
"(",
"STATUS_CALLS",
",",
"any_order",
"=",
"True",
")"
] | [
503,
0
] | [
517,
68
] | python | en | ['en', 'en', 'en'] | True |
setup_component | (hass, entity_name) | Set up vacuum component. | Set up vacuum component. | async def setup_component(hass, entity_name):
"""Set up vacuum component."""
entity_id = f"{DOMAIN}.{entity_name}"
await async_setup_component(
hass,
DOMAIN,
{
DOMAIN: {
CONF_PLATFORM: PLATFORM,
CONF_HOST: "192.168.1.100",
CONF_NAME: entity_name,
CONF_TOKEN: "12345678901234567890123456789012",
}
},
)
await hass.async_block_till_done()
return entity_id | [
"async",
"def",
"setup_component",
"(",
"hass",
",",
"entity_name",
")",
":",
"entity_id",
"=",
"f\"{DOMAIN}.{entity_name}\"",
"await",
"async_setup_component",
"(",
"hass",
",",
"DOMAIN",
",",
"{",
"DOMAIN",
":",
"{",
"CONF_PLATFORM",
":",
"PLATFORM",
",",
"CONF_HOST",
":",
"\"192.168.1.100\"",
",",
"CONF_NAME",
":",
"entity_name",
",",
"CONF_TOKEN",
":",
"\"12345678901234567890123456789012\"",
",",
"}",
"}",
",",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"return",
"entity_id"
] | [
520,
0
] | [
537,
20
] | python | en | ['en', 'la', 'en'] | True |
meraki_client | (loop, hass, hass_client) | Meraki mock client. | Meraki mock client. | def meraki_client(loop, hass, hass_client):
"""Meraki mock client."""
assert loop.run_until_complete(
async_setup_component(
hass,
device_tracker.DOMAIN,
{
device_tracker.DOMAIN: {
CONF_PLATFORM: "meraki",
CONF_VALIDATOR: "validator",
CONF_SECRET: "secret",
}
},
)
)
yield loop.run_until_complete(hass_client()) | [
"def",
"meraki_client",
"(",
"loop",
",",
"hass",
",",
"hass_client",
")",
":",
"assert",
"loop",
".",
"run_until_complete",
"(",
"async_setup_component",
"(",
"hass",
",",
"device_tracker",
".",
"DOMAIN",
",",
"{",
"device_tracker",
".",
"DOMAIN",
":",
"{",
"CONF_PLATFORM",
":",
"\"meraki\"",
",",
"CONF_VALIDATOR",
":",
"\"validator\"",
",",
"CONF_SECRET",
":",
"\"secret\"",
",",
"}",
"}",
",",
")",
")",
"yield",
"loop",
".",
"run_until_complete",
"(",
"hass_client",
"(",
")",
")"
] | [
16,
0
] | [
32,
48
] | python | eu | ['pl', 'eu', 'hi'] | False |
test_invalid_or_missing_data | (mock_device_tracker_conf, meraki_client) | Test validator with invalid or missing data. | Test validator with invalid or missing data. | async def test_invalid_or_missing_data(mock_device_tracker_conf, meraki_client):
"""Test validator with invalid or missing data."""
req = await meraki_client.get(URL)
text = await req.text()
assert req.status == 200
assert text == "validator"
req = await meraki_client.post(URL, data=b"invalid")
text = await req.json()
assert req.status == 400
assert text["message"] == "Invalid JSON"
req = await meraki_client.post(URL, data=b"{}")
text = await req.json()
assert req.status == 422
assert text["message"] == "No secret"
data = {"version": "1.0", "secret": "secret"}
req = await meraki_client.post(URL, data=json.dumps(data))
text = await req.json()
assert req.status == 422
assert text["message"] == "Invalid version"
data = {"version": "2.0", "secret": "invalid"}
req = await meraki_client.post(URL, data=json.dumps(data))
text = await req.json()
assert req.status == 422
assert text["message"] == "Invalid secret"
data = {"version": "2.0", "secret": "secret", "type": "InvalidType"}
req = await meraki_client.post(URL, data=json.dumps(data))
text = await req.json()
assert req.status == 422
assert text["message"] == "Invalid device type"
data = {
"version": "2.0",
"secret": "secret",
"type": "BluetoothDevicesSeen",
"data": {"observations": []},
}
req = await meraki_client.post(URL, data=json.dumps(data))
assert req.status == 200 | [
"async",
"def",
"test_invalid_or_missing_data",
"(",
"mock_device_tracker_conf",
",",
"meraki_client",
")",
":",
"req",
"=",
"await",
"meraki_client",
".",
"get",
"(",
"URL",
")",
"text",
"=",
"await",
"req",
".",
"text",
"(",
")",
"assert",
"req",
".",
"status",
"==",
"200",
"assert",
"text",
"==",
"\"validator\"",
"req",
"=",
"await",
"meraki_client",
".",
"post",
"(",
"URL",
",",
"data",
"=",
"b\"invalid\"",
")",
"text",
"=",
"await",
"req",
".",
"json",
"(",
")",
"assert",
"req",
".",
"status",
"==",
"400",
"assert",
"text",
"[",
"\"message\"",
"]",
"==",
"\"Invalid JSON\"",
"req",
"=",
"await",
"meraki_client",
".",
"post",
"(",
"URL",
",",
"data",
"=",
"b\"{}\"",
")",
"text",
"=",
"await",
"req",
".",
"json",
"(",
")",
"assert",
"req",
".",
"status",
"==",
"422",
"assert",
"text",
"[",
"\"message\"",
"]",
"==",
"\"No secret\"",
"data",
"=",
"{",
"\"version\"",
":",
"\"1.0\"",
",",
"\"secret\"",
":",
"\"secret\"",
"}",
"req",
"=",
"await",
"meraki_client",
".",
"post",
"(",
"URL",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"data",
")",
")",
"text",
"=",
"await",
"req",
".",
"json",
"(",
")",
"assert",
"req",
".",
"status",
"==",
"422",
"assert",
"text",
"[",
"\"message\"",
"]",
"==",
"\"Invalid version\"",
"data",
"=",
"{",
"\"version\"",
":",
"\"2.0\"",
",",
"\"secret\"",
":",
"\"invalid\"",
"}",
"req",
"=",
"await",
"meraki_client",
".",
"post",
"(",
"URL",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"data",
")",
")",
"text",
"=",
"await",
"req",
".",
"json",
"(",
")",
"assert",
"req",
".",
"status",
"==",
"422",
"assert",
"text",
"[",
"\"message\"",
"]",
"==",
"\"Invalid secret\"",
"data",
"=",
"{",
"\"version\"",
":",
"\"2.0\"",
",",
"\"secret\"",
":",
"\"secret\"",
",",
"\"type\"",
":",
"\"InvalidType\"",
"}",
"req",
"=",
"await",
"meraki_client",
".",
"post",
"(",
"URL",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"data",
")",
")",
"text",
"=",
"await",
"req",
".",
"json",
"(",
")",
"assert",
"req",
".",
"status",
"==",
"422",
"assert",
"text",
"[",
"\"message\"",
"]",
"==",
"\"Invalid device type\"",
"data",
"=",
"{",
"\"version\"",
":",
"\"2.0\"",
",",
"\"secret\"",
":",
"\"secret\"",
",",
"\"type\"",
":",
"\"BluetoothDevicesSeen\"",
",",
"\"data\"",
":",
"{",
"\"observations\"",
":",
"[",
"]",
"}",
",",
"}",
"req",
"=",
"await",
"meraki_client",
".",
"post",
"(",
"URL",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"data",
")",
")",
"assert",
"req",
".",
"status",
"==",
"200"
] | [
35,
0
] | [
77,
28
] | python | en | ['en', 'en', 'en'] | True |
test_data_will_be_saved | (mock_device_tracker_conf, hass, meraki_client) | Test with valid data. | Test with valid data. | async def test_data_will_be_saved(mock_device_tracker_conf, hass, meraki_client):
"""Test with valid data."""
data = {
"version": "2.0",
"secret": "secret",
"type": "DevicesSeen",
"data": {
"observations": [
{
"location": {
"lat": "51.5355157",
"lng": "21.0699035",
"unc": "46.3610585",
},
"seenTime": "2016-09-12T16:23:13Z",
"ssid": "ssid",
"os": "HA",
"ipv6": "2607:f0d0:1002:51::4/64",
"clientMac": "00:26:ab:b8:a9:a4",
"seenEpoch": "147369739",
"rssi": "20",
"manufacturer": "Seiko Epson",
},
{
"location": {
"lat": "51.5355357",
"lng": "21.0699635",
"unc": "46.3610585",
},
"seenTime": "2016-09-12T16:21:13Z",
"ssid": "ssid",
"os": "HA",
"ipv4": "192.168.0.1",
"clientMac": "00:26:ab:b8:a9:a5",
"seenEpoch": "147369750",
"rssi": "20",
"manufacturer": "Seiko Epson",
},
]
},
}
req = await meraki_client.post(URL, data=json.dumps(data))
assert req.status == 200
await hass.async_block_till_done()
state_name = hass.states.get(
"{}.{}".format("device_tracker", "00_26_ab_b8_a9_a4")
).state
assert "home" == state_name
state_name = hass.states.get(
"{}.{}".format("device_tracker", "00_26_ab_b8_a9_a5")
).state
assert "home" == state_name | [
"async",
"def",
"test_data_will_be_saved",
"(",
"mock_device_tracker_conf",
",",
"hass",
",",
"meraki_client",
")",
":",
"data",
"=",
"{",
"\"version\"",
":",
"\"2.0\"",
",",
"\"secret\"",
":",
"\"secret\"",
",",
"\"type\"",
":",
"\"DevicesSeen\"",
",",
"\"data\"",
":",
"{",
"\"observations\"",
":",
"[",
"{",
"\"location\"",
":",
"{",
"\"lat\"",
":",
"\"51.5355157\"",
",",
"\"lng\"",
":",
"\"21.0699035\"",
",",
"\"unc\"",
":",
"\"46.3610585\"",
",",
"}",
",",
"\"seenTime\"",
":",
"\"2016-09-12T16:23:13Z\"",
",",
"\"ssid\"",
":",
"\"ssid\"",
",",
"\"os\"",
":",
"\"HA\"",
",",
"\"ipv6\"",
":",
"\"2607:f0d0:1002:51::4/64\"",
",",
"\"clientMac\"",
":",
"\"00:26:ab:b8:a9:a4\"",
",",
"\"seenEpoch\"",
":",
"\"147369739\"",
",",
"\"rssi\"",
":",
"\"20\"",
",",
"\"manufacturer\"",
":",
"\"Seiko Epson\"",
",",
"}",
",",
"{",
"\"location\"",
":",
"{",
"\"lat\"",
":",
"\"51.5355357\"",
",",
"\"lng\"",
":",
"\"21.0699635\"",
",",
"\"unc\"",
":",
"\"46.3610585\"",
",",
"}",
",",
"\"seenTime\"",
":",
"\"2016-09-12T16:21:13Z\"",
",",
"\"ssid\"",
":",
"\"ssid\"",
",",
"\"os\"",
":",
"\"HA\"",
",",
"\"ipv4\"",
":",
"\"192.168.0.1\"",
",",
"\"clientMac\"",
":",
"\"00:26:ab:b8:a9:a5\"",
",",
"\"seenEpoch\"",
":",
"\"147369750\"",
",",
"\"rssi\"",
":",
"\"20\"",
",",
"\"manufacturer\"",
":",
"\"Seiko Epson\"",
",",
"}",
",",
"]",
"}",
",",
"}",
"req",
"=",
"await",
"meraki_client",
".",
"post",
"(",
"URL",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"data",
")",
")",
"assert",
"req",
".",
"status",
"==",
"200",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"state_name",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"\"{}.{}\"",
".",
"format",
"(",
"\"device_tracker\"",
",",
"\"00_26_ab_b8_a9_a4\"",
")",
")",
".",
"state",
"assert",
"\"home\"",
"==",
"state_name",
"state_name",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"\"{}.{}\"",
".",
"format",
"(",
"\"device_tracker\"",
",",
"\"00_26_ab_b8_a9_a5\"",
")",
")",
".",
"state",
"assert",
"\"home\"",
"==",
"state_name"
] | [
80,
0
] | [
132,
31
] | python | en | ['en', 'en', 'en'] | True |
async_setup | (hass, data, store) | Set up the onboarding view. | Set up the onboarding view. | async def async_setup(hass, data, store):
"""Set up the onboarding view."""
hass.http.register_view(OnboardingView(data, store))
hass.http.register_view(UserOnboardingView(data, store))
hass.http.register_view(CoreConfigOnboardingView(data, store))
hass.http.register_view(IntegrationOnboardingView(data, store)) | [
"async",
"def",
"async_setup",
"(",
"hass",
",",
"data",
",",
"store",
")",
":",
"hass",
".",
"http",
".",
"register_view",
"(",
"OnboardingView",
"(",
"data",
",",
"store",
")",
")",
"hass",
".",
"http",
".",
"register_view",
"(",
"UserOnboardingView",
"(",
"data",
",",
"store",
")",
")",
"hass",
".",
"http",
".",
"register_view",
"(",
"CoreConfigOnboardingView",
"(",
"data",
",",
"store",
")",
")",
"hass",
".",
"http",
".",
"register_view",
"(",
"IntegrationOnboardingView",
"(",
"data",
",",
"store",
")",
")"
] | [
22,
0
] | [
27,
67
] | python | en | ['en', 'en', 'en'] | True |
_async_get_hass_provider | (hass) | Get the Home Assistant auth provider. | Get the Home Assistant auth provider. | def _async_get_hass_provider(hass):
"""Get the Home Assistant auth provider."""
for prv in hass.auth.auth_providers:
if prv.type == "homeassistant":
return prv
raise RuntimeError("No Home Assistant provider found") | [
"def",
"_async_get_hass_provider",
"(",
"hass",
")",
":",
"for",
"prv",
"in",
"hass",
".",
"auth",
".",
"auth_providers",
":",
"if",
"prv",
".",
"type",
"==",
"\"homeassistant\"",
":",
"return",
"prv",
"raise",
"RuntimeError",
"(",
"\"No Home Assistant provider found\"",
")"
] | [
209,
0
] | [
215,
58
] | python | en | ['en', 'en', 'en'] | True |
OnboardingView.__init__ | (self, data, store) | Initialize the onboarding view. | Initialize the onboarding view. | def __init__(self, data, store):
"""Initialize the onboarding view."""
self._store = store
self._data = data | [
"def",
"__init__",
"(",
"self",
",",
"data",
",",
"store",
")",
":",
"self",
".",
"_store",
"=",
"store",
"self",
".",
"_data",
"=",
"data"
] | [
37,
4
] | [
40,
25
] | python | en | ['en', 'en', 'en'] | True |
OnboardingView.get | (self, request) | Return the onboarding status. | Return the onboarding status. | async def get(self, request):
"""Return the onboarding status."""
return self.json(
[{"step": key, "done": key in self._data["done"]} for key in STEPS]
) | [
"async",
"def",
"get",
"(",
"self",
",",
"request",
")",
":",
"return",
"self",
".",
"json",
"(",
"[",
"{",
"\"step\"",
":",
"key",
",",
"\"done\"",
":",
"key",
"in",
"self",
".",
"_data",
"[",
"\"done\"",
"]",
"}",
"for",
"key",
"in",
"STEPS",
"]",
")"
] | [
42,
4
] | [
46,
9
] | python | en | ['en', 'af', 'en'] | True |
_BaseOnboardingView.__init__ | (self, data, store) | Initialize the onboarding view. | Initialize the onboarding view. | def __init__(self, data, store):
"""Initialize the onboarding view."""
self._store = store
self._data = data
self._lock = asyncio.Lock() | [
"def",
"__init__",
"(",
"self",
",",
"data",
",",
"store",
")",
":",
"self",
".",
"_store",
"=",
"store",
"self",
".",
"_data",
"=",
"data",
"self",
".",
"_lock",
"=",
"asyncio",
".",
"Lock",
"(",
")"
] | [
54,
4
] | [
58,
35
] | python | en | ['en', 'en', 'en'] | True |
_BaseOnboardingView._async_is_done | (self) | Return if this step is done. | Return if this step is done. | def _async_is_done(self):
"""Return if this step is done."""
return self.step in self._data["done"] | [
"def",
"_async_is_done",
"(",
"self",
")",
":",
"return",
"self",
".",
"step",
"in",
"self",
".",
"_data",
"[",
"\"done\"",
"]"
] | [
61,
4
] | [
63,
46
] | python | en | ['en', 'en', 'en'] | True |
_BaseOnboardingView._async_mark_done | (self, hass) | Mark step as done. | Mark step as done. | async def _async_mark_done(self, hass):
"""Mark step as done."""
self._data["done"].append(self.step)
await self._store.async_save(self._data)
if set(self._data["done"]) == set(STEPS):
hass.data[DOMAIN] = True | [
"async",
"def",
"_async_mark_done",
"(",
"self",
",",
"hass",
")",
":",
"self",
".",
"_data",
"[",
"\"done\"",
"]",
".",
"append",
"(",
"self",
".",
"step",
")",
"await",
"self",
".",
"_store",
".",
"async_save",
"(",
"self",
".",
"_data",
")",
"if",
"set",
"(",
"self",
".",
"_data",
"[",
"\"done\"",
"]",
")",
"==",
"set",
"(",
"STEPS",
")",
":",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"=",
"True"
] | [
65,
4
] | [
71,
36
] | python | en | ['pt', 'en', 'en'] | True |
UserOnboardingView.post | (self, request, data) | Handle user creation, area creation. | Handle user creation, area creation. | async def post(self, request, data):
"""Handle user creation, area creation."""
hass = request.app["hass"]
async with self._lock:
if self._async_is_done():
return self.json_message("User step already done", HTTP_FORBIDDEN)
provider = _async_get_hass_provider(hass)
await provider.async_initialize()
user = await hass.auth.async_create_user(data["name"], [GROUP_ID_ADMIN])
await hass.async_add_executor_job(
provider.data.add_auth, data["username"], data["password"]
)
credentials = await provider.async_get_or_create_credentials(
{"username": data["username"]}
)
await provider.data.async_save()
await hass.auth.async_link_user(user, credentials)
if "person" in hass.config.components:
await hass.components.person.async_create_person(
data["name"], user_id=user.id
)
# Create default areas using the users supplied language.
translations = await hass.helpers.translation.async_get_translations(
data["language"], "area", DOMAIN
)
area_registry = await hass.helpers.area_registry.async_get_registry()
for area in DEFAULT_AREAS:
area_registry.async_create(
translations[f"component.onboarding.area.{area}"]
)
await self._async_mark_done(hass)
# Return authorization code for fetching tokens and connect
# during onboarding.
auth_code = hass.components.auth.create_auth_code(data["client_id"], user)
return self.json({"auth_code": auth_code}) | [
"async",
"def",
"post",
"(",
"self",
",",
"request",
",",
"data",
")",
":",
"hass",
"=",
"request",
".",
"app",
"[",
"\"hass\"",
"]",
"async",
"with",
"self",
".",
"_lock",
":",
"if",
"self",
".",
"_async_is_done",
"(",
")",
":",
"return",
"self",
".",
"json_message",
"(",
"\"User step already done\"",
",",
"HTTP_FORBIDDEN",
")",
"provider",
"=",
"_async_get_hass_provider",
"(",
"hass",
")",
"await",
"provider",
".",
"async_initialize",
"(",
")",
"user",
"=",
"await",
"hass",
".",
"auth",
".",
"async_create_user",
"(",
"data",
"[",
"\"name\"",
"]",
",",
"[",
"GROUP_ID_ADMIN",
"]",
")",
"await",
"hass",
".",
"async_add_executor_job",
"(",
"provider",
".",
"data",
".",
"add_auth",
",",
"data",
"[",
"\"username\"",
"]",
",",
"data",
"[",
"\"password\"",
"]",
")",
"credentials",
"=",
"await",
"provider",
".",
"async_get_or_create_credentials",
"(",
"{",
"\"username\"",
":",
"data",
"[",
"\"username\"",
"]",
"}",
")",
"await",
"provider",
".",
"data",
".",
"async_save",
"(",
")",
"await",
"hass",
".",
"auth",
".",
"async_link_user",
"(",
"user",
",",
"credentials",
")",
"if",
"\"person\"",
"in",
"hass",
".",
"config",
".",
"components",
":",
"await",
"hass",
".",
"components",
".",
"person",
".",
"async_create_person",
"(",
"data",
"[",
"\"name\"",
"]",
",",
"user_id",
"=",
"user",
".",
"id",
")",
"# Create default areas using the users supplied language.",
"translations",
"=",
"await",
"hass",
".",
"helpers",
".",
"translation",
".",
"async_get_translations",
"(",
"data",
"[",
"\"language\"",
"]",
",",
"\"area\"",
",",
"DOMAIN",
")",
"area_registry",
"=",
"await",
"hass",
".",
"helpers",
".",
"area_registry",
".",
"async_get_registry",
"(",
")",
"for",
"area",
"in",
"DEFAULT_AREAS",
":",
"area_registry",
".",
"async_create",
"(",
"translations",
"[",
"f\"component.onboarding.area.{area}\"",
"]",
")",
"await",
"self",
".",
"_async_mark_done",
"(",
"hass",
")",
"# Return authorization code for fetching tokens and connect",
"# during onboarding.",
"auth_code",
"=",
"hass",
".",
"components",
".",
"auth",
".",
"create_auth_code",
"(",
"data",
"[",
"\"client_id\"",
"]",
",",
"user",
")",
"return",
"self",
".",
"json",
"(",
"{",
"\"auth_code\"",
":",
"auth_code",
"}",
")"
] | [
93,
4
] | [
135,
54
] | python | en | ['en', 'tg', 'en'] | True |
CoreConfigOnboardingView.post | (self, request) | Handle finishing core config step. | Handle finishing core config step. | async def post(self, request):
"""Handle finishing core config step."""
hass = request.app["hass"]
async with self._lock:
if self._async_is_done():
return self.json_message(
"Core config step already done", HTTP_FORBIDDEN
)
await self._async_mark_done(hass)
await hass.config_entries.flow.async_init(
"met", context={"source": "onboarding"}
)
if (
hass.components.hassio.is_hassio()
and "raspberrypi" in hass.components.hassio.get_core_info()["machine"]
):
await hass.config_entries.flow.async_init(
"rpi_power", context={"source": "onboarding"}
)
return self.json({}) | [
"async",
"def",
"post",
"(",
"self",
",",
"request",
")",
":",
"hass",
"=",
"request",
".",
"app",
"[",
"\"hass\"",
"]",
"async",
"with",
"self",
".",
"_lock",
":",
"if",
"self",
".",
"_async_is_done",
"(",
")",
":",
"return",
"self",
".",
"json_message",
"(",
"\"Core config step already done\"",
",",
"HTTP_FORBIDDEN",
")",
"await",
"self",
".",
"_async_mark_done",
"(",
"hass",
")",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"\"met\"",
",",
"context",
"=",
"{",
"\"source\"",
":",
"\"onboarding\"",
"}",
")",
"if",
"(",
"hass",
".",
"components",
".",
"hassio",
".",
"is_hassio",
"(",
")",
"and",
"\"raspberrypi\"",
"in",
"hass",
".",
"components",
".",
"hassio",
".",
"get_core_info",
"(",
")",
"[",
"\"machine\"",
"]",
")",
":",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"\"rpi_power\"",
",",
"context",
"=",
"{",
"\"source\"",
":",
"\"onboarding\"",
"}",
")",
"return",
"self",
".",
"json",
"(",
"{",
"}",
")"
] | [
145,
4
] | [
169,
32
] | python | en | ['en', 'en', 'en'] | True |
IntegrationOnboardingView.post | (self, request, data) | Handle token creation. | Handle token creation. | async def post(self, request, data):
"""Handle token creation."""
hass = request.app["hass"]
user = request["hass_user"]
async with self._lock:
if self._async_is_done():
return self.json_message(
"Integration step already done", HTTP_FORBIDDEN
)
await self._async_mark_done(hass)
# Validate client ID and redirect uri
if not await indieauth.verify_redirect_uri(
request.app["hass"], data["client_id"], data["redirect_uri"]
):
return self.json_message(
"invalid client id or redirect uri", HTTP_BAD_REQUEST
)
# Return authorization code so we can redirect user and log them in
auth_code = hass.components.auth.create_auth_code(data["client_id"], user)
return self.json({"auth_code": auth_code}) | [
"async",
"def",
"post",
"(",
"self",
",",
"request",
",",
"data",
")",
":",
"hass",
"=",
"request",
".",
"app",
"[",
"\"hass\"",
"]",
"user",
"=",
"request",
"[",
"\"hass_user\"",
"]",
"async",
"with",
"self",
".",
"_lock",
":",
"if",
"self",
".",
"_async_is_done",
"(",
")",
":",
"return",
"self",
".",
"json_message",
"(",
"\"Integration step already done\"",
",",
"HTTP_FORBIDDEN",
")",
"await",
"self",
".",
"_async_mark_done",
"(",
"hass",
")",
"# Validate client ID and redirect uri",
"if",
"not",
"await",
"indieauth",
".",
"verify_redirect_uri",
"(",
"request",
".",
"app",
"[",
"\"hass\"",
"]",
",",
"data",
"[",
"\"client_id\"",
"]",
",",
"data",
"[",
"\"redirect_uri\"",
"]",
")",
":",
"return",
"self",
".",
"json_message",
"(",
"\"invalid client id or redirect uri\"",
",",
"HTTP_BAD_REQUEST",
")",
"# Return authorization code so we can redirect user and log them in",
"auth_code",
"=",
"hass",
".",
"components",
".",
"auth",
".",
"create_auth_code",
"(",
"data",
"[",
"\"client_id\"",
"]",
",",
"user",
")",
"return",
"self",
".",
"json",
"(",
"{",
"\"auth_code\"",
":",
"auth_code",
"}",
")"
] | [
182,
4
] | [
205,
54
] | python | nl | ['nl', 'nl', 'en'] | True |
DataProcessor.get_example_from_tensor_dict | (self, tensor_dict) |
Gets an example from a dict with tensorflow tensors.
Args:
tensor_dict: Keys and values should match the corresponding Glue
tensorflow_dataset examples.
|
Gets an example from a dict with tensorflow tensors. | def get_example_from_tensor_dict(self, tensor_dict):
"""
Gets an example from a dict with tensorflow tensors.
Args:
tensor_dict: Keys and values should match the corresponding Glue
tensorflow_dataset examples.
"""
raise NotImplementedError() | [
"def",
"get_example_from_tensor_dict",
"(",
"self",
",",
"tensor_dict",
")",
":",
"raise",
"NotImplementedError",
"(",
")"
] | [
83,
4
] | [
91,
35
] | python | en | ['en', 'error', 'th'] | False |
DataProcessor.get_train_examples | (self, data_dir) | Gets a collection of :class:`InputExample` for the train set. | Gets a collection of :class:`InputExample` for the train set. | def get_train_examples(self, data_dir):
"""Gets a collection of :class:`InputExample` for the train set."""
raise NotImplementedError() | [
"def",
"get_train_examples",
"(",
"self",
",",
"data_dir",
")",
":",
"raise",
"NotImplementedError",
"(",
")"
] | [
93,
4
] | [
95,
35
] | python | en | ['en', 'en', 'en'] | True |
DataProcessor.get_dev_examples | (self, data_dir) | Gets a collection of :class:`InputExample` for the dev set. | Gets a collection of :class:`InputExample` for the dev set. | def get_dev_examples(self, data_dir):
"""Gets a collection of :class:`InputExample` for the dev set."""
raise NotImplementedError() | [
"def",
"get_dev_examples",
"(",
"self",
",",
"data_dir",
")",
":",
"raise",
"NotImplementedError",
"(",
")"
] | [
97,
4
] | [
99,
35
] | python | en | ['en', 'en', 'en'] | True |
DataProcessor.get_test_examples | (self, data_dir) | Gets a collection of :class:`InputExample` for the test set. | Gets a collection of :class:`InputExample` for the test set. | def get_test_examples(self, data_dir):
"""Gets a collection of :class:`InputExample` for the test set."""
raise NotImplementedError() | [
"def",
"get_test_examples",
"(",
"self",
",",
"data_dir",
")",
":",
"raise",
"NotImplementedError",
"(",
")"
] | [
101,
4
] | [
103,
35
] | python | en | ['en', 'en', 'en'] | True |
DataProcessor.get_labels | (self) | Gets the list of labels for this data set. | Gets the list of labels for this data set. | def get_labels(self):
"""Gets the list of labels for this data set."""
raise NotImplementedError() | [
"def",
"get_labels",
"(",
"self",
")",
":",
"raise",
"NotImplementedError",
"(",
")"
] | [
105,
4
] | [
107,
35
] | python | en | ['en', 'en', 'en'] | True |
DataProcessor.tfds_map | (self, example) |
Some tensorflow_datasets datasets are not formatted the same way the GLUE datasets are. This method converts
examples to the correct format.
|
Some tensorflow_datasets datasets are not formatted the same way the GLUE datasets are. This method converts
examples to the correct format.
| def tfds_map(self, example):
"""
Some tensorflow_datasets datasets are not formatted the same way the GLUE datasets are. This method converts
examples to the correct format.
"""
if len(self.get_labels()) > 1:
example.label = self.get_labels()[int(example.label)]
return example | [
"def",
"tfds_map",
"(",
"self",
",",
"example",
")",
":",
"if",
"len",
"(",
"self",
".",
"get_labels",
"(",
")",
")",
">",
"1",
":",
"example",
".",
"label",
"=",
"self",
".",
"get_labels",
"(",
")",
"[",
"int",
"(",
"example",
".",
"label",
")",
"]",
"return",
"example"
] | [
109,
4
] | [
116,
22
] | python | en | ['en', 'error', 'th'] | False |
DataProcessor._read_tsv | (cls, input_file, quotechar=None) | Reads a tab separated value file. | Reads a tab separated value file. | def _read_tsv(cls, input_file, quotechar=None):
"""Reads a tab separated value file."""
with open(input_file, "r", encoding="utf-8-sig") as f:
return list(csv.reader(f, delimiter="\t", quotechar=quotechar)) | [
"def",
"_read_tsv",
"(",
"cls",
",",
"input_file",
",",
"quotechar",
"=",
"None",
")",
":",
"with",
"open",
"(",
"input_file",
",",
"\"r\"",
",",
"encoding",
"=",
"\"utf-8-sig\"",
")",
"as",
"f",
":",
"return",
"list",
"(",
"csv",
".",
"reader",
"(",
"f",
",",
"delimiter",
"=",
"\"\\t\"",
",",
"quotechar",
"=",
"quotechar",
")",
")"
] | [
119,
4
] | [
122,
75
] | python | en | ['en', 'en', 'en'] | True |
SingleSentenceClassificationProcessor.get_features | (
self,
tokenizer,
max_length=None,
pad_on_left=False,
pad_token=0,
mask_padding_with_zero=True,
return_tensors=None,
) |
Convert examples in a list of ``InputFeatures``
Args:
tokenizer: Instance of a tokenizer that will tokenize the examples
max_length: Maximum example length
pad_on_left: If set to ``True``, the examples will be padded on the left rather than on the right (default)
pad_token: Padding token
mask_padding_with_zero: If set to ``True``, the attention mask will be filled by ``1`` for actual values
and by ``0`` for padded values. If set to ``False``, inverts it (``1`` for padded values, ``0`` for
actual values)
Returns:
If the ``examples`` input is a ``tf.data.Dataset``, will return a ``tf.data.Dataset`` containing the
task-specific features. If the input is a list of ``InputExamples``, will return a list of task-specific
``InputFeatures`` which can be fed to the model.
|
Convert examples in a list of ``InputFeatures`` | def get_features(
self,
tokenizer,
max_length=None,
pad_on_left=False,
pad_token=0,
mask_padding_with_zero=True,
return_tensors=None,
):
"""
Convert examples in a list of ``InputFeatures``
Args:
tokenizer: Instance of a tokenizer that will tokenize the examples
max_length: Maximum example length
pad_on_left: If set to ``True``, the examples will be padded on the left rather than on the right (default)
pad_token: Padding token
mask_padding_with_zero: If set to ``True``, the attention mask will be filled by ``1`` for actual values
and by ``0`` for padded values. If set to ``False``, inverts it (``1`` for padded values, ``0`` for
actual values)
Returns:
If the ``examples`` input is a ``tf.data.Dataset``, will return a ``tf.data.Dataset`` containing the
task-specific features. If the input is a list of ``InputExamples``, will return a list of task-specific
``InputFeatures`` which can be fed to the model.
"""
if max_length is None:
max_length = tokenizer.max_len
label_map = {label: i for i, label in enumerate(self.labels)}
all_input_ids = []
for (ex_index, example) in enumerate(self.examples):
if ex_index % 10000 == 0:
logger.info("Tokenizing example %d", ex_index)
input_ids = tokenizer.encode(
example.text_a,
add_special_tokens=True,
max_length=min(max_length, tokenizer.max_len),
)
all_input_ids.append(input_ids)
batch_length = max(len(input_ids) for input_ids in all_input_ids)
features = []
for (ex_index, (input_ids, example)) in enumerate(zip(all_input_ids, self.examples)):
if ex_index % 10000 == 0:
logger.info("Writing example %d/%d" % (ex_index, len(self.examples)))
# The mask has 1 for real tokens and 0 for padding tokens. Only real
# tokens are attended to.
attention_mask = [1 if mask_padding_with_zero else 0] * len(input_ids)
# Zero-pad up to the sequence length.
padding_length = batch_length - len(input_ids)
if pad_on_left:
input_ids = ([pad_token] * padding_length) + input_ids
attention_mask = ([0 if mask_padding_with_zero else 1] * padding_length) + attention_mask
else:
input_ids = input_ids + ([pad_token] * padding_length)
attention_mask = attention_mask + ([0 if mask_padding_with_zero else 1] * padding_length)
assert len(input_ids) == batch_length, "Error with input length {} vs {}".format(
len(input_ids), batch_length
)
assert len(attention_mask) == batch_length, "Error with input length {} vs {}".format(
len(attention_mask), batch_length
)
if self.mode == "classification":
label = label_map[example.label]
elif self.mode == "regression":
label = float(example.label)
else:
raise ValueError(self.mode)
if ex_index < 5 and self.verbose:
logger.info("*** Example ***")
logger.info("guid: %s" % (example.guid))
logger.info("input_ids: %s" % " ".join([str(x) for x in input_ids]))
logger.info("attention_mask: %s" % " ".join([str(x) for x in attention_mask]))
logger.info("label: %s (id = %d)" % (example.label, label))
features.append(InputFeatures(input_ids=input_ids, attention_mask=attention_mask, label=label))
if return_tensors is None:
return features
elif return_tensors == "tf":
if not is_tf_available():
raise RuntimeError("return_tensors set to 'tf' but TensorFlow 2.0 can't be imported")
import tensorflow as tf
def gen():
for ex in features:
yield ({"input_ids": ex.input_ids, "attention_mask": ex.attention_mask}, ex.label)
dataset = tf.data.Dataset.from_generator(
gen,
({"input_ids": tf.int32, "attention_mask": tf.int32}, tf.int64),
({"input_ids": tf.TensorShape([None]), "attention_mask": tf.TensorShape([None])}, tf.TensorShape([])),
)
return dataset
elif return_tensors == "pt":
if not is_torch_available():
raise RuntimeError("return_tensors set to 'pt' but PyTorch can't be imported")
import torch
from torch.utils.data import TensorDataset
all_input_ids = torch.tensor([f.input_ids for f in features], dtype=torch.long)
all_attention_mask = torch.tensor([f.attention_mask for f in features], dtype=torch.long)
if self.mode == "classification":
all_labels = torch.tensor([f.label for f in features], dtype=torch.long)
elif self.mode == "regression":
all_labels = torch.tensor([f.label for f in features], dtype=torch.float)
dataset = TensorDataset(all_input_ids, all_attention_mask, all_labels)
return dataset
else:
raise ValueError("return_tensors should be one of 'tf' or 'pt'") | [
"def",
"get_features",
"(",
"self",
",",
"tokenizer",
",",
"max_length",
"=",
"None",
",",
"pad_on_left",
"=",
"False",
",",
"pad_token",
"=",
"0",
",",
"mask_padding_with_zero",
"=",
"True",
",",
"return_tensors",
"=",
"None",
",",
")",
":",
"if",
"max_length",
"is",
"None",
":",
"max_length",
"=",
"tokenizer",
".",
"max_len",
"label_map",
"=",
"{",
"label",
":",
"i",
"for",
"i",
",",
"label",
"in",
"enumerate",
"(",
"self",
".",
"labels",
")",
"}",
"all_input_ids",
"=",
"[",
"]",
"for",
"(",
"ex_index",
",",
"example",
")",
"in",
"enumerate",
"(",
"self",
".",
"examples",
")",
":",
"if",
"ex_index",
"%",
"10000",
"==",
"0",
":",
"logger",
".",
"info",
"(",
"\"Tokenizing example %d\"",
",",
"ex_index",
")",
"input_ids",
"=",
"tokenizer",
".",
"encode",
"(",
"example",
".",
"text_a",
",",
"add_special_tokens",
"=",
"True",
",",
"max_length",
"=",
"min",
"(",
"max_length",
",",
"tokenizer",
".",
"max_len",
")",
",",
")",
"all_input_ids",
".",
"append",
"(",
"input_ids",
")",
"batch_length",
"=",
"max",
"(",
"len",
"(",
"input_ids",
")",
"for",
"input_ids",
"in",
"all_input_ids",
")",
"features",
"=",
"[",
"]",
"for",
"(",
"ex_index",
",",
"(",
"input_ids",
",",
"example",
")",
")",
"in",
"enumerate",
"(",
"zip",
"(",
"all_input_ids",
",",
"self",
".",
"examples",
")",
")",
":",
"if",
"ex_index",
"%",
"10000",
"==",
"0",
":",
"logger",
".",
"info",
"(",
"\"Writing example %d/%d\"",
"%",
"(",
"ex_index",
",",
"len",
"(",
"self",
".",
"examples",
")",
")",
")",
"# The mask has 1 for real tokens and 0 for padding tokens. Only real",
"# tokens are attended to.",
"attention_mask",
"=",
"[",
"1",
"if",
"mask_padding_with_zero",
"else",
"0",
"]",
"*",
"len",
"(",
"input_ids",
")",
"# Zero-pad up to the sequence length.",
"padding_length",
"=",
"batch_length",
"-",
"len",
"(",
"input_ids",
")",
"if",
"pad_on_left",
":",
"input_ids",
"=",
"(",
"[",
"pad_token",
"]",
"*",
"padding_length",
")",
"+",
"input_ids",
"attention_mask",
"=",
"(",
"[",
"0",
"if",
"mask_padding_with_zero",
"else",
"1",
"]",
"*",
"padding_length",
")",
"+",
"attention_mask",
"else",
":",
"input_ids",
"=",
"input_ids",
"+",
"(",
"[",
"pad_token",
"]",
"*",
"padding_length",
")",
"attention_mask",
"=",
"attention_mask",
"+",
"(",
"[",
"0",
"if",
"mask_padding_with_zero",
"else",
"1",
"]",
"*",
"padding_length",
")",
"assert",
"len",
"(",
"input_ids",
")",
"==",
"batch_length",
",",
"\"Error with input length {} vs {}\"",
".",
"format",
"(",
"len",
"(",
"input_ids",
")",
",",
"batch_length",
")",
"assert",
"len",
"(",
"attention_mask",
")",
"==",
"batch_length",
",",
"\"Error with input length {} vs {}\"",
".",
"format",
"(",
"len",
"(",
"attention_mask",
")",
",",
"batch_length",
")",
"if",
"self",
".",
"mode",
"==",
"\"classification\"",
":",
"label",
"=",
"label_map",
"[",
"example",
".",
"label",
"]",
"elif",
"self",
".",
"mode",
"==",
"\"regression\"",
":",
"label",
"=",
"float",
"(",
"example",
".",
"label",
")",
"else",
":",
"raise",
"ValueError",
"(",
"self",
".",
"mode",
")",
"if",
"ex_index",
"<",
"5",
"and",
"self",
".",
"verbose",
":",
"logger",
".",
"info",
"(",
"\"*** Example ***\"",
")",
"logger",
".",
"info",
"(",
"\"guid: %s\"",
"%",
"(",
"example",
".",
"guid",
")",
")",
"logger",
".",
"info",
"(",
"\"input_ids: %s\"",
"%",
"\" \"",
".",
"join",
"(",
"[",
"str",
"(",
"x",
")",
"for",
"x",
"in",
"input_ids",
"]",
")",
")",
"logger",
".",
"info",
"(",
"\"attention_mask: %s\"",
"%",
"\" \"",
".",
"join",
"(",
"[",
"str",
"(",
"x",
")",
"for",
"x",
"in",
"attention_mask",
"]",
")",
")",
"logger",
".",
"info",
"(",
"\"label: %s (id = %d)\"",
"%",
"(",
"example",
".",
"label",
",",
"label",
")",
")",
"features",
".",
"append",
"(",
"InputFeatures",
"(",
"input_ids",
"=",
"input_ids",
",",
"attention_mask",
"=",
"attention_mask",
",",
"label",
"=",
"label",
")",
")",
"if",
"return_tensors",
"is",
"None",
":",
"return",
"features",
"elif",
"return_tensors",
"==",
"\"tf\"",
":",
"if",
"not",
"is_tf_available",
"(",
")",
":",
"raise",
"RuntimeError",
"(",
"\"return_tensors set to 'tf' but TensorFlow 2.0 can't be imported\"",
")",
"import",
"tensorflow",
"as",
"tf",
"def",
"gen",
"(",
")",
":",
"for",
"ex",
"in",
"features",
":",
"yield",
"(",
"{",
"\"input_ids\"",
":",
"ex",
".",
"input_ids",
",",
"\"attention_mask\"",
":",
"ex",
".",
"attention_mask",
"}",
",",
"ex",
".",
"label",
")",
"dataset",
"=",
"tf",
".",
"data",
".",
"Dataset",
".",
"from_generator",
"(",
"gen",
",",
"(",
"{",
"\"input_ids\"",
":",
"tf",
".",
"int32",
",",
"\"attention_mask\"",
":",
"tf",
".",
"int32",
"}",
",",
"tf",
".",
"int64",
")",
",",
"(",
"{",
"\"input_ids\"",
":",
"tf",
".",
"TensorShape",
"(",
"[",
"None",
"]",
")",
",",
"\"attention_mask\"",
":",
"tf",
".",
"TensorShape",
"(",
"[",
"None",
"]",
")",
"}",
",",
"tf",
".",
"TensorShape",
"(",
"[",
"]",
")",
")",
",",
")",
"return",
"dataset",
"elif",
"return_tensors",
"==",
"\"pt\"",
":",
"if",
"not",
"is_torch_available",
"(",
")",
":",
"raise",
"RuntimeError",
"(",
"\"return_tensors set to 'pt' but PyTorch can't be imported\"",
")",
"import",
"torch",
"from",
"torch",
".",
"utils",
".",
"data",
"import",
"TensorDataset",
"all_input_ids",
"=",
"torch",
".",
"tensor",
"(",
"[",
"f",
".",
"input_ids",
"for",
"f",
"in",
"features",
"]",
",",
"dtype",
"=",
"torch",
".",
"long",
")",
"all_attention_mask",
"=",
"torch",
".",
"tensor",
"(",
"[",
"f",
".",
"attention_mask",
"for",
"f",
"in",
"features",
"]",
",",
"dtype",
"=",
"torch",
".",
"long",
")",
"if",
"self",
".",
"mode",
"==",
"\"classification\"",
":",
"all_labels",
"=",
"torch",
".",
"tensor",
"(",
"[",
"f",
".",
"label",
"for",
"f",
"in",
"features",
"]",
",",
"dtype",
"=",
"torch",
".",
"long",
")",
"elif",
"self",
".",
"mode",
"==",
"\"regression\"",
":",
"all_labels",
"=",
"torch",
".",
"tensor",
"(",
"[",
"f",
".",
"label",
"for",
"f",
"in",
"features",
"]",
",",
"dtype",
"=",
"torch",
".",
"float",
")",
"dataset",
"=",
"TensorDataset",
"(",
"all_input_ids",
",",
"all_attention_mask",
",",
"all_labels",
")",
"return",
"dataset",
"else",
":",
"raise",
"ValueError",
"(",
"\"return_tensors should be one of 'tf' or 'pt'\"",
")"
] | [
232,
4
] | [
351,
76
] | python | en | ['en', 'error', 'th'] | False |
init_logger | () |
This function will (and should only) get invoked on the first time of importing nni (no matter which submodule).
It will try to detect the running environment and setup logger accordingly.
The detection should work in most cases but for `nnictl` and `nni.experiment`.
They will be identified as "standalone" mode and must configure the logger by themselves.
|
This function will (and should only) get invoked on the first time of importing nni (no matter which submodule).
It will try to detect the running environment and setup logger accordingly. | def init_logger() -> None:
"""
This function will (and should only) get invoked on the first time of importing nni (no matter which submodule).
It will try to detect the running environment and setup logger accordingly.
The detection should work in most cases but for `nnictl` and `nni.experiment`.
They will be identified as "standalone" mode and must configure the logger by themselves.
"""
colorama.init()
if dispatcher_env_vars.SDK_PROCESS == 'dispatcher':
_init_logger_dispatcher()
return
trial_platform = trial_env_vars.NNI_PLATFORM
if trial_platform == 'unittest':
return
if trial_platform and not trial_env_vars.REUSE_MODE:
_init_logger_trial()
return
_init_logger_standalone()
logging.getLogger('filelock').setLevel(logging.WARNING) | [
"def",
"init_logger",
"(",
")",
"->",
"None",
":",
"colorama",
".",
"init",
"(",
")",
"if",
"dispatcher_env_vars",
".",
"SDK_PROCESS",
"==",
"'dispatcher'",
":",
"_init_logger_dispatcher",
"(",
")",
"return",
"trial_platform",
"=",
"trial_env_vars",
".",
"NNI_PLATFORM",
"if",
"trial_platform",
"==",
"'unittest'",
":",
"return",
"if",
"trial_platform",
"and",
"not",
"trial_env_vars",
".",
"REUSE_MODE",
":",
"_init_logger_trial",
"(",
")",
"return",
"_init_logger_standalone",
"(",
")",
"logging",
".",
"getLogger",
"(",
"'filelock'",
")",
".",
"setLevel",
"(",
"logging",
".",
"WARNING",
")"
] | [
21,
0
] | [
46,
59
] | python | en | ['en', 'error', 'th'] | False |
init_logger_experiment | () |
Initialize logger for `nni.experiment.Experiment`.
This function will get invoked after `init_logger()`.
|
Initialize logger for `nni.experiment.Experiment`. | def init_logger_experiment() -> None:
"""
Initialize logger for `nni.experiment.Experiment`.
This function will get invoked after `init_logger()`.
"""
global _exp_log_initialized
if not _exp_log_initialized:
_exp_log_initialized = True
colorful_formatter = Formatter(log_format, time_format)
colorful_formatter.format = _colorful_format
handlers['_default_'].setFormatter(colorful_formatter) | [
"def",
"init_logger_experiment",
"(",
")",
"->",
"None",
":",
"global",
"_exp_log_initialized",
"if",
"not",
"_exp_log_initialized",
":",
"_exp_log_initialized",
"=",
"True",
"colorful_formatter",
"=",
"Formatter",
"(",
"log_format",
",",
"time_format",
")",
"colorful_formatter",
".",
"format",
"=",
"_colorful_format",
"handlers",
"[",
"'_default_'",
"]",
".",
"setFormatter",
"(",
"colorful_formatter",
")"
] | [
50,
0
] | [
61,
62
] | python | en | ['en', 'error', 'th'] | False |
setup_platform | (hass, config, add_entities, discovery_info=None) | Set up the Reddit sensor platform. | Set up the Reddit sensor platform. | def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Reddit sensor platform."""
subreddits = config[CONF_SUBREDDITS]
user_agent = "{}_home_assistant_sensor".format(config[CONF_USERNAME])
limit = config[CONF_MAXIMUM]
sort_by = config[CONF_SORT_BY]
try:
reddit = praw.Reddit(
client_id=config[CONF_CLIENT_ID],
client_secret=config[CONF_CLIENT_SECRET],
username=config[CONF_USERNAME],
password=config[CONF_PASSWORD],
user_agent=user_agent,
)
_LOGGER.debug("Connected to praw")
except praw.exceptions.PRAWException as err:
_LOGGER.error("Reddit error %s", err)
return
sensors = [
RedditSensor(reddit, subreddit, limit, sort_by) for subreddit in subreddits
]
add_entities(sensors, True) | [
"def",
"setup_platform",
"(",
"hass",
",",
"config",
",",
"add_entities",
",",
"discovery_info",
"=",
"None",
")",
":",
"subreddits",
"=",
"config",
"[",
"CONF_SUBREDDITS",
"]",
"user_agent",
"=",
"\"{}_home_assistant_sensor\"",
".",
"format",
"(",
"config",
"[",
"CONF_USERNAME",
"]",
")",
"limit",
"=",
"config",
"[",
"CONF_MAXIMUM",
"]",
"sort_by",
"=",
"config",
"[",
"CONF_SORT_BY",
"]",
"try",
":",
"reddit",
"=",
"praw",
".",
"Reddit",
"(",
"client_id",
"=",
"config",
"[",
"CONF_CLIENT_ID",
"]",
",",
"client_secret",
"=",
"config",
"[",
"CONF_CLIENT_SECRET",
"]",
",",
"username",
"=",
"config",
"[",
"CONF_USERNAME",
"]",
",",
"password",
"=",
"config",
"[",
"CONF_PASSWORD",
"]",
",",
"user_agent",
"=",
"user_agent",
",",
")",
"_LOGGER",
".",
"debug",
"(",
"\"Connected to praw\"",
")",
"except",
"praw",
".",
"exceptions",
".",
"PRAWException",
"as",
"err",
":",
"_LOGGER",
".",
"error",
"(",
"\"Reddit error %s\"",
",",
"err",
")",
"return",
"sensors",
"=",
"[",
"RedditSensor",
"(",
"reddit",
",",
"subreddit",
",",
"limit",
",",
"sort_by",
")",
"for",
"subreddit",
"in",
"subreddits",
"]",
"add_entities",
"(",
"sensors",
",",
"True",
")"
] | [
56,
0
] | [
81,
31
] | python | en | ['en', 'da', 'en'] | True |
RedditSensor.__init__ | (self, reddit, subreddit: str, limit: int, sort_by: str) | Initialize the Reddit sensor. | Initialize the Reddit sensor. | def __init__(self, reddit, subreddit: str, limit: int, sort_by: str):
"""Initialize the Reddit sensor."""
self._reddit = reddit
self._subreddit = subreddit
self._limit = limit
self._sort_by = sort_by
self._subreddit_data = [] | [
"def",
"__init__",
"(",
"self",
",",
"reddit",
",",
"subreddit",
":",
"str",
",",
"limit",
":",
"int",
",",
"sort_by",
":",
"str",
")",
":",
"self",
".",
"_reddit",
"=",
"reddit",
"self",
".",
"_subreddit",
"=",
"subreddit",
"self",
".",
"_limit",
"=",
"limit",
"self",
".",
"_sort_by",
"=",
"sort_by",
"self",
".",
"_subreddit_data",
"=",
"[",
"]"
] | [
87,
4
] | [
94,
33
] | python | en | ['en', 'da', 'en'] | True |
RedditSensor.name | (self) | Return the name of the sensor. | Return the name of the sensor. | def name(self):
"""Return the name of the sensor."""
return f"reddit_{self._subreddit}" | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"f\"reddit_{self._subreddit}\""
] | [
97,
4
] | [
99,
42
] | python | en | ['en', 'mi', 'en'] | True |
RedditSensor.state | (self) | Return the state of the sensor. | Return the state of the sensor. | def state(self):
"""Return the state of the sensor."""
return len(self._subreddit_data) | [
"def",
"state",
"(",
"self",
")",
":",
"return",
"len",
"(",
"self",
".",
"_subreddit_data",
")"
] | [
102,
4
] | [
104,
40
] | python | en | ['en', 'en', 'en'] | True |
RedditSensor.device_state_attributes | (self) | Return the state attributes. | Return the state attributes. | def device_state_attributes(self):
"""Return the state attributes."""
return {
ATTR_SUBREDDIT: self._subreddit,
ATTR_POSTS: self._subreddit_data,
CONF_SORT_BY: self._sort_by,
} | [
"def",
"device_state_attributes",
"(",
"self",
")",
":",
"return",
"{",
"ATTR_SUBREDDIT",
":",
"self",
".",
"_subreddit",
",",
"ATTR_POSTS",
":",
"self",
".",
"_subreddit_data",
",",
"CONF_SORT_BY",
":",
"self",
".",
"_sort_by",
",",
"}"
] | [
107,
4
] | [
113,
9
] | python | en | ['en', 'en', 'en'] | True |
RedditSensor.icon | (self) | Return the icon to use in the frontend. | Return the icon to use in the frontend. | def icon(self):
"""Return the icon to use in the frontend."""
return "mdi:reddit" | [
"def",
"icon",
"(",
"self",
")",
":",
"return",
"\"mdi:reddit\""
] | [
116,
4
] | [
118,
27
] | python | en | ['en', 'en', 'en'] | True |
RedditSensor.update | (self) | Update data from Reddit API. | Update data from Reddit API. | def update(self):
"""Update data from Reddit API."""
self._subreddit_data = []
try:
subreddit = self._reddit.subreddit(self._subreddit)
if hasattr(subreddit, self._sort_by):
method_to_call = getattr(subreddit, self._sort_by)
for submission in method_to_call(limit=self._limit):
self._subreddit_data.append(
{
ATTR_ID: submission.id,
ATTR_URL: submission.url,
ATTR_TITLE: submission.title,
ATTR_SCORE: submission.score,
ATTR_COMMENTS_NUMBER: submission.num_comments,
ATTR_CREATED: submission.created,
ATTR_BODY: submission.selftext,
}
)
except praw.exceptions.PRAWException as err:
_LOGGER.error("Reddit error %s", err) | [
"def",
"update",
"(",
"self",
")",
":",
"self",
".",
"_subreddit_data",
"=",
"[",
"]",
"try",
":",
"subreddit",
"=",
"self",
".",
"_reddit",
".",
"subreddit",
"(",
"self",
".",
"_subreddit",
")",
"if",
"hasattr",
"(",
"subreddit",
",",
"self",
".",
"_sort_by",
")",
":",
"method_to_call",
"=",
"getattr",
"(",
"subreddit",
",",
"self",
".",
"_sort_by",
")",
"for",
"submission",
"in",
"method_to_call",
"(",
"limit",
"=",
"self",
".",
"_limit",
")",
":",
"self",
".",
"_subreddit_data",
".",
"append",
"(",
"{",
"ATTR_ID",
":",
"submission",
".",
"id",
",",
"ATTR_URL",
":",
"submission",
".",
"url",
",",
"ATTR_TITLE",
":",
"submission",
".",
"title",
",",
"ATTR_SCORE",
":",
"submission",
".",
"score",
",",
"ATTR_COMMENTS_NUMBER",
":",
"submission",
".",
"num_comments",
",",
"ATTR_CREATED",
":",
"submission",
".",
"created",
",",
"ATTR_BODY",
":",
"submission",
".",
"selftext",
",",
"}",
")",
"except",
"praw",
".",
"exceptions",
".",
"PRAWException",
"as",
"err",
":",
"_LOGGER",
".",
"error",
"(",
"\"Reddit error %s\"",
",",
"err",
")"
] | [
120,
4
] | [
143,
49
] | python | en | ['en', 'no', 'en'] | True |
location_info_fixture | () | Mock location info. | Mock location info. | def location_info_fixture():
"""Mock location info."""
with patch(
"homeassistant.components.ps4.config_flow.location.async_detect_location_info",
return_value=MOCK_LOCATION,
):
yield | [
"def",
"location_info_fixture",
"(",
")",
":",
"with",
"patch",
"(",
"\"homeassistant.components.ps4.config_flow.location.async_detect_location_info\"",
",",
"return_value",
"=",
"MOCK_LOCATION",
",",
")",
":",
"yield"
] | [
77,
0
] | [
83,
13
] | python | en | ['en', 'fy', 'en'] | True |
ps4_setup_fixture | () | Patch ps4 setup entry. | Patch ps4 setup entry. | def ps4_setup_fixture():
"""Patch ps4 setup entry."""
with patch(
"homeassistant.components.ps4.async_setup_entry",
return_value=True,
):
yield | [
"def",
"ps4_setup_fixture",
"(",
")",
":",
"with",
"patch",
"(",
"\"homeassistant.components.ps4.async_setup_entry\"",
",",
"return_value",
"=",
"True",
",",
")",
":",
"yield"
] | [
87,
0
] | [
93,
13
] | python | en | ['en', 'cs', 'en'] | True |
test_full_flow_implementation | (hass) | Test registering an implementation and flow works. | Test registering an implementation and flow works. | async def test_full_flow_implementation(hass):
"""Test registering an implementation and flow works."""
# User Step Started, results in Step Creds
with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": "user"}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["step_id"] == "creds"
# Step Creds results with form in Step Mode.
with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["step_id"] == "mode"
# Step Mode with User Input which is not manual, results in Step Link.
with patch(
"pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}]
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input=MOCK_AUTO
)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["step_id"] == "link"
# User Input results in created entry.
with patch("pyps4_2ndscreen.Helper.link", return_value=(True, True)), patch(
"pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}]
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input=MOCK_CONFIG
)
assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
assert result["data"][CONF_TOKEN] == MOCK_CREDS
assert result["data"]["devices"] == [MOCK_DEVICE]
assert result["title"] == MOCK_TITLE | [
"async",
"def",
"test_full_flow_implementation",
"(",
"hass",
")",
":",
"# User Step Started, results in Step Creds",
"with",
"patch",
"(",
"\"pyps4_2ndscreen.Helper.port_bind\"",
",",
"return_value",
"=",
"None",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"\"user\"",
"}",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_FORM",
"assert",
"result",
"[",
"\"step_id\"",
"]",
"==",
"\"creds\"",
"# Step Creds results with form in Step Mode.",
"with",
"patch",
"(",
"\"pyps4_2ndscreen.Helper.get_creds\"",
",",
"return_value",
"=",
"MOCK_CREDS",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_configure",
"(",
"result",
"[",
"\"flow_id\"",
"]",
",",
"user_input",
"=",
"{",
"}",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_FORM",
"assert",
"result",
"[",
"\"step_id\"",
"]",
"==",
"\"mode\"",
"# Step Mode with User Input which is not manual, results in Step Link.",
"with",
"patch",
"(",
"\"pyps4_2ndscreen.Helper.has_devices\"",
",",
"return_value",
"=",
"[",
"{",
"\"host-ip\"",
":",
"MOCK_HOST",
"}",
"]",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_configure",
"(",
"result",
"[",
"\"flow_id\"",
"]",
",",
"user_input",
"=",
"MOCK_AUTO",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_FORM",
"assert",
"result",
"[",
"\"step_id\"",
"]",
"==",
"\"link\"",
"# User Input results in created entry.",
"with",
"patch",
"(",
"\"pyps4_2ndscreen.Helper.link\"",
",",
"return_value",
"=",
"(",
"True",
",",
"True",
")",
")",
",",
"patch",
"(",
"\"pyps4_2ndscreen.Helper.has_devices\"",
",",
"return_value",
"=",
"[",
"{",
"\"host-ip\"",
":",
"MOCK_HOST",
"}",
"]",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_configure",
"(",
"result",
"[",
"\"flow_id\"",
"]",
",",
"user_input",
"=",
"MOCK_CONFIG",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_CREATE_ENTRY",
"assert",
"result",
"[",
"\"data\"",
"]",
"[",
"CONF_TOKEN",
"]",
"==",
"MOCK_CREDS",
"assert",
"result",
"[",
"\"data\"",
"]",
"[",
"\"devices\"",
"]",
"==",
"[",
"MOCK_DEVICE",
"]",
"assert",
"result",
"[",
"\"title\"",
"]",
"==",
"MOCK_TITLE"
] | [
96,
0
] | [
134,
40
] | python | en | ['en', 'en', 'en'] | True |
test_multiple_flow_implementation | (hass) | Test multiple device flows. | Test multiple device flows. | async def test_multiple_flow_implementation(hass):
"""Test multiple device flows."""
# User Step Started, results in Step Creds
with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": "user"}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["step_id"] == "creds"
# Step Creds results with form in Step Mode.
with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["step_id"] == "mode"
# Step Mode with User Input which is not manual, results in Step Link.
with patch(
"pyps4_2ndscreen.Helper.has_devices",
return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}],
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input=MOCK_AUTO
)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["step_id"] == "link"
# User Input results in created entry.
with patch("pyps4_2ndscreen.Helper.link", return_value=(True, True)), patch(
"pyps4_2ndscreen.Helper.has_devices",
return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}],
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input=MOCK_CONFIG
)
assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
assert result["data"][CONF_TOKEN] == MOCK_CREDS
assert result["data"]["devices"] == [MOCK_DEVICE]
assert result["title"] == MOCK_TITLE
# Check if entry exists.
entries = hass.config_entries.async_entries()
assert len(entries) == 1
# Check if there is a device config in entry.
entry_1 = entries[0]
assert len(entry_1.data["devices"]) == 1
# Test additional flow.
# User Step Started, results in Step Mode:
with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None), patch(
"pyps4_2ndscreen.Helper.has_devices",
return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}],
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": "user"}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["step_id"] == "creds"
# Step Creds results with form in Step Mode.
with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["step_id"] == "mode"
# Step Mode with User Input which is not manual, results in Step Link.
with patch(
"pyps4_2ndscreen.Helper.has_devices",
return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}],
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input=MOCK_AUTO
)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["step_id"] == "link"
# Step Link
with patch(
"pyps4_2ndscreen.Helper.has_devices",
return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}],
), patch("pyps4_2ndscreen.Helper.link", return_value=(True, True)):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input=MOCK_CONFIG_ADDITIONAL
)
assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
assert result["data"][CONF_TOKEN] == MOCK_CREDS
assert len(result["data"]["devices"]) == 1
assert result["title"] == MOCK_TITLE
# Check if there are 2 entries.
entries = hass.config_entries.async_entries()
assert len(entries) == 2
# Check if there is device config in the last entry.
entry_2 = entries[-1]
assert len(entry_2.data["devices"]) == 1
# Check that entry 1 is different from entry 2.
assert entry_1 is not entry_2 | [
"async",
"def",
"test_multiple_flow_implementation",
"(",
"hass",
")",
":",
"# User Step Started, results in Step Creds",
"with",
"patch",
"(",
"\"pyps4_2ndscreen.Helper.port_bind\"",
",",
"return_value",
"=",
"None",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"\"user\"",
"}",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_FORM",
"assert",
"result",
"[",
"\"step_id\"",
"]",
"==",
"\"creds\"",
"# Step Creds results with form in Step Mode.",
"with",
"patch",
"(",
"\"pyps4_2ndscreen.Helper.get_creds\"",
",",
"return_value",
"=",
"MOCK_CREDS",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_configure",
"(",
"result",
"[",
"\"flow_id\"",
"]",
",",
"user_input",
"=",
"{",
"}",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_FORM",
"assert",
"result",
"[",
"\"step_id\"",
"]",
"==",
"\"mode\"",
"# Step Mode with User Input which is not manual, results in Step Link.",
"with",
"patch",
"(",
"\"pyps4_2ndscreen.Helper.has_devices\"",
",",
"return_value",
"=",
"[",
"{",
"\"host-ip\"",
":",
"MOCK_HOST",
"}",
",",
"{",
"\"host-ip\"",
":",
"MOCK_HOST_ADDITIONAL",
"}",
"]",
",",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_configure",
"(",
"result",
"[",
"\"flow_id\"",
"]",
",",
"user_input",
"=",
"MOCK_AUTO",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_FORM",
"assert",
"result",
"[",
"\"step_id\"",
"]",
"==",
"\"link\"",
"# User Input results in created entry.",
"with",
"patch",
"(",
"\"pyps4_2ndscreen.Helper.link\"",
",",
"return_value",
"=",
"(",
"True",
",",
"True",
")",
")",
",",
"patch",
"(",
"\"pyps4_2ndscreen.Helper.has_devices\"",
",",
"return_value",
"=",
"[",
"{",
"\"host-ip\"",
":",
"MOCK_HOST",
"}",
",",
"{",
"\"host-ip\"",
":",
"MOCK_HOST_ADDITIONAL",
"}",
"]",
",",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_configure",
"(",
"result",
"[",
"\"flow_id\"",
"]",
",",
"user_input",
"=",
"MOCK_CONFIG",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_CREATE_ENTRY",
"assert",
"result",
"[",
"\"data\"",
"]",
"[",
"CONF_TOKEN",
"]",
"==",
"MOCK_CREDS",
"assert",
"result",
"[",
"\"data\"",
"]",
"[",
"\"devices\"",
"]",
"==",
"[",
"MOCK_DEVICE",
"]",
"assert",
"result",
"[",
"\"title\"",
"]",
"==",
"MOCK_TITLE",
"# Check if entry exists.",
"entries",
"=",
"hass",
".",
"config_entries",
".",
"async_entries",
"(",
")",
"assert",
"len",
"(",
"entries",
")",
"==",
"1",
"# Check if there is a device config in entry.",
"entry_1",
"=",
"entries",
"[",
"0",
"]",
"assert",
"len",
"(",
"entry_1",
".",
"data",
"[",
"\"devices\"",
"]",
")",
"==",
"1",
"# Test additional flow.",
"# User Step Started, results in Step Mode:",
"with",
"patch",
"(",
"\"pyps4_2ndscreen.Helper.port_bind\"",
",",
"return_value",
"=",
"None",
")",
",",
"patch",
"(",
"\"pyps4_2ndscreen.Helper.has_devices\"",
",",
"return_value",
"=",
"[",
"{",
"\"host-ip\"",
":",
"MOCK_HOST",
"}",
",",
"{",
"\"host-ip\"",
":",
"MOCK_HOST_ADDITIONAL",
"}",
"]",
",",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"\"user\"",
"}",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_FORM",
"assert",
"result",
"[",
"\"step_id\"",
"]",
"==",
"\"creds\"",
"# Step Creds results with form in Step Mode.",
"with",
"patch",
"(",
"\"pyps4_2ndscreen.Helper.get_creds\"",
",",
"return_value",
"=",
"MOCK_CREDS",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_configure",
"(",
"result",
"[",
"\"flow_id\"",
"]",
",",
"user_input",
"=",
"{",
"}",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_FORM",
"assert",
"result",
"[",
"\"step_id\"",
"]",
"==",
"\"mode\"",
"# Step Mode with User Input which is not manual, results in Step Link.",
"with",
"patch",
"(",
"\"pyps4_2ndscreen.Helper.has_devices\"",
",",
"return_value",
"=",
"[",
"{",
"\"host-ip\"",
":",
"MOCK_HOST",
"}",
",",
"{",
"\"host-ip\"",
":",
"MOCK_HOST_ADDITIONAL",
"}",
"]",
",",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_configure",
"(",
"result",
"[",
"\"flow_id\"",
"]",
",",
"user_input",
"=",
"MOCK_AUTO",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_FORM",
"assert",
"result",
"[",
"\"step_id\"",
"]",
"==",
"\"link\"",
"# Step Link",
"with",
"patch",
"(",
"\"pyps4_2ndscreen.Helper.has_devices\"",
",",
"return_value",
"=",
"[",
"{",
"\"host-ip\"",
":",
"MOCK_HOST",
"}",
",",
"{",
"\"host-ip\"",
":",
"MOCK_HOST_ADDITIONAL",
"}",
"]",
",",
")",
",",
"patch",
"(",
"\"pyps4_2ndscreen.Helper.link\"",
",",
"return_value",
"=",
"(",
"True",
",",
"True",
")",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_configure",
"(",
"result",
"[",
"\"flow_id\"",
"]",
",",
"user_input",
"=",
"MOCK_CONFIG_ADDITIONAL",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_CREATE_ENTRY",
"assert",
"result",
"[",
"\"data\"",
"]",
"[",
"CONF_TOKEN",
"]",
"==",
"MOCK_CREDS",
"assert",
"len",
"(",
"result",
"[",
"\"data\"",
"]",
"[",
"\"devices\"",
"]",
")",
"==",
"1",
"assert",
"result",
"[",
"\"title\"",
"]",
"==",
"MOCK_TITLE",
"# Check if there are 2 entries.",
"entries",
"=",
"hass",
".",
"config_entries",
".",
"async_entries",
"(",
")",
"assert",
"len",
"(",
"entries",
")",
"==",
"2",
"# Check if there is device config in the last entry.",
"entry_2",
"=",
"entries",
"[",
"-",
"1",
"]",
"assert",
"len",
"(",
"entry_2",
".",
"data",
"[",
"\"devices\"",
"]",
")",
"==",
"1",
"# Check that entry 1 is different from entry 2.",
"assert",
"entry_1",
"is",
"not",
"entry_2"
] | [
137,
0
] | [
239,
33
] | python | en | ['fr', 'en', 'en'] | True |
test_port_bind_abort | (hass) | Test that flow aborted when cannot bind to ports 987, 997. | Test that flow aborted when cannot bind to ports 987, 997. | async def test_port_bind_abort(hass):
"""Test that flow aborted when cannot bind to ports 987, 997."""
with patch("pyps4_2ndscreen.Helper.port_bind", return_value=MOCK_UDP_PORT):
reason = "port_987_bind_error"
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": "user"}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT
assert result["reason"] == reason
with patch("pyps4_2ndscreen.Helper.port_bind", return_value=MOCK_TCP_PORT):
reason = "port_997_bind_error"
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": "user"}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT
assert result["reason"] == reason | [
"async",
"def",
"test_port_bind_abort",
"(",
"hass",
")",
":",
"with",
"patch",
"(",
"\"pyps4_2ndscreen.Helper.port_bind\"",
",",
"return_value",
"=",
"MOCK_UDP_PORT",
")",
":",
"reason",
"=",
"\"port_987_bind_error\"",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"\"user\"",
"}",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_ABORT",
"assert",
"result",
"[",
"\"reason\"",
"]",
"==",
"reason",
"with",
"patch",
"(",
"\"pyps4_2ndscreen.Helper.port_bind\"",
",",
"return_value",
"=",
"MOCK_TCP_PORT",
")",
":",
"reason",
"=",
"\"port_997_bind_error\"",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"\"user\"",
"}",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_ABORT",
"assert",
"result",
"[",
"\"reason\"",
"]",
"==",
"reason"
] | [
242,
0
] | [
258,
37
] | python | en | ['en', 'en', 'en'] | True |
test_duplicate_abort | (hass) | Test that Flow aborts when found devices already configured. | Test that Flow aborts when found devices already configured. | async def test_duplicate_abort(hass):
"""Test that Flow aborts when found devices already configured."""
MockConfigEntry(domain=ps4.DOMAIN, data=MOCK_DATA).add_to_hass(hass)
with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": "user"}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["step_id"] == "creds"
with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["step_id"] == "mode"
with patch(
"pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}]
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input=MOCK_AUTO
)
assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT
assert result["reason"] == "already_configured" | [
"async",
"def",
"test_duplicate_abort",
"(",
"hass",
")",
":",
"MockConfigEntry",
"(",
"domain",
"=",
"ps4",
".",
"DOMAIN",
",",
"data",
"=",
"MOCK_DATA",
")",
".",
"add_to_hass",
"(",
"hass",
")",
"with",
"patch",
"(",
"\"pyps4_2ndscreen.Helper.port_bind\"",
",",
"return_value",
"=",
"None",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"\"user\"",
"}",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_FORM",
"assert",
"result",
"[",
"\"step_id\"",
"]",
"==",
"\"creds\"",
"with",
"patch",
"(",
"\"pyps4_2ndscreen.Helper.get_creds\"",
",",
"return_value",
"=",
"MOCK_CREDS",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_configure",
"(",
"result",
"[",
"\"flow_id\"",
"]",
",",
"user_input",
"=",
"{",
"}",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_FORM",
"assert",
"result",
"[",
"\"step_id\"",
"]",
"==",
"\"mode\"",
"with",
"patch",
"(",
"\"pyps4_2ndscreen.Helper.has_devices\"",
",",
"return_value",
"=",
"[",
"{",
"\"host-ip\"",
":",
"MOCK_HOST",
"}",
"]",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_configure",
"(",
"result",
"[",
"\"flow_id\"",
"]",
",",
"user_input",
"=",
"MOCK_AUTO",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_ABORT",
"assert",
"result",
"[",
"\"reason\"",
"]",
"==",
"\"already_configured\""
] | [
261,
0
] | [
286,
51
] | python | en | ['en', 'de', 'en'] | True |
test_additional_device | (hass) | Test that Flow can configure another device. | Test that Flow can configure another device. | async def test_additional_device(hass):
"""Test that Flow can configure another device."""
# Mock existing entry.
entry = MockConfigEntry(domain=ps4.DOMAIN, data=MOCK_DATA)
entry.add_to_hass(hass)
with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": "user"}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["step_id"] == "creds"
with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["step_id"] == "mode"
with patch(
"pyps4_2ndscreen.Helper.has_devices",
return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}],
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input=MOCK_AUTO
)
with patch("pyps4_2ndscreen.Helper.link", return_value=(True, True)):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input=MOCK_CONFIG_ADDITIONAL
)
assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
assert result["data"][CONF_TOKEN] == MOCK_CREDS
assert len(result["data"]["devices"]) == 1
assert result["title"] == MOCK_TITLE | [
"async",
"def",
"test_additional_device",
"(",
"hass",
")",
":",
"# Mock existing entry.",
"entry",
"=",
"MockConfigEntry",
"(",
"domain",
"=",
"ps4",
".",
"DOMAIN",
",",
"data",
"=",
"MOCK_DATA",
")",
"entry",
".",
"add_to_hass",
"(",
"hass",
")",
"with",
"patch",
"(",
"\"pyps4_2ndscreen.Helper.port_bind\"",
",",
"return_value",
"=",
"None",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"\"user\"",
"}",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_FORM",
"assert",
"result",
"[",
"\"step_id\"",
"]",
"==",
"\"creds\"",
"with",
"patch",
"(",
"\"pyps4_2ndscreen.Helper.get_creds\"",
",",
"return_value",
"=",
"MOCK_CREDS",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_configure",
"(",
"result",
"[",
"\"flow_id\"",
"]",
",",
"user_input",
"=",
"{",
"}",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_FORM",
"assert",
"result",
"[",
"\"step_id\"",
"]",
"==",
"\"mode\"",
"with",
"patch",
"(",
"\"pyps4_2ndscreen.Helper.has_devices\"",
",",
"return_value",
"=",
"[",
"{",
"\"host-ip\"",
":",
"MOCK_HOST",
"}",
",",
"{",
"\"host-ip\"",
":",
"MOCK_HOST_ADDITIONAL",
"}",
"]",
",",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_configure",
"(",
"result",
"[",
"\"flow_id\"",
"]",
",",
"user_input",
"=",
"MOCK_AUTO",
")",
"with",
"patch",
"(",
"\"pyps4_2ndscreen.Helper.link\"",
",",
"return_value",
"=",
"(",
"True",
",",
"True",
")",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_configure",
"(",
"result",
"[",
"\"flow_id\"",
"]",
",",
"user_input",
"=",
"MOCK_CONFIG_ADDITIONAL",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_CREATE_ENTRY",
"assert",
"result",
"[",
"\"data\"",
"]",
"[",
"CONF_TOKEN",
"]",
"==",
"MOCK_CREDS",
"assert",
"len",
"(",
"result",
"[",
"\"data\"",
"]",
"[",
"\"devices\"",
"]",
")",
"==",
"1",
"assert",
"result",
"[",
"\"title\"",
"]",
"==",
"MOCK_TITLE"
] | [
289,
0
] | [
325,
40
] | python | en | ['en', 'en', 'en'] | True |
test_0_pin | (hass) | Test Pin with leading '0' is passed correctly. | Test Pin with leading '0' is passed correctly. | async def test_0_pin(hass):
"""Test Pin with leading '0' is passed correctly."""
with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS):
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": "creds"},
data={},
)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["step_id"] == "mode"
with patch(
"pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}]
), patch(
"homeassistant.components.ps4.config_flow.location.async_detect_location_info",
return_value=MOCK_LOCATION,
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], MOCK_AUTO
)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["step_id"] == "link"
mock_config = MOCK_CONFIG
mock_config[CONF_CODE] = MOCK_CODE_LEAD_0
with patch(
"pyps4_2ndscreen.Helper.link", return_value=(True, True)
) as mock_call, patch(
"pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}]
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], mock_config
)
mock_call.assert_called_once_with(
MOCK_HOST, MOCK_CREDS, MOCK_CODE_LEAD_0_STR, DEFAULT_ALIAS
) | [
"async",
"def",
"test_0_pin",
"(",
"hass",
")",
":",
"with",
"patch",
"(",
"\"pyps4_2ndscreen.Helper.get_creds\"",
",",
"return_value",
"=",
"MOCK_CREDS",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"\"creds\"",
"}",
",",
"data",
"=",
"{",
"}",
",",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_FORM",
"assert",
"result",
"[",
"\"step_id\"",
"]",
"==",
"\"mode\"",
"with",
"patch",
"(",
"\"pyps4_2ndscreen.Helper.has_devices\"",
",",
"return_value",
"=",
"[",
"{",
"\"host-ip\"",
":",
"MOCK_HOST",
"}",
"]",
")",
",",
"patch",
"(",
"\"homeassistant.components.ps4.config_flow.location.async_detect_location_info\"",
",",
"return_value",
"=",
"MOCK_LOCATION",
",",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_configure",
"(",
"result",
"[",
"\"flow_id\"",
"]",
",",
"MOCK_AUTO",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_FORM",
"assert",
"result",
"[",
"\"step_id\"",
"]",
"==",
"\"link\"",
"mock_config",
"=",
"MOCK_CONFIG",
"mock_config",
"[",
"CONF_CODE",
"]",
"=",
"MOCK_CODE_LEAD_0",
"with",
"patch",
"(",
"\"pyps4_2ndscreen.Helper.link\"",
",",
"return_value",
"=",
"(",
"True",
",",
"True",
")",
")",
"as",
"mock_call",
",",
"patch",
"(",
"\"pyps4_2ndscreen.Helper.has_devices\"",
",",
"return_value",
"=",
"[",
"{",
"\"host-ip\"",
":",
"MOCK_HOST",
"}",
"]",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_configure",
"(",
"result",
"[",
"\"flow_id\"",
"]",
",",
"mock_config",
")",
"mock_call",
".",
"assert_called_once_with",
"(",
"MOCK_HOST",
",",
"MOCK_CREDS",
",",
"MOCK_CODE_LEAD_0_STR",
",",
"DEFAULT_ALIAS",
")"
] | [
328,
0
] | [
363,
5
] | python | en | ['en', 'en', 'en'] | True |
test_no_devices_found_abort | (hass) | Test that failure to find devices aborts flow. | Test that failure to find devices aborts flow. | async def test_no_devices_found_abort(hass):
"""Test that failure to find devices aborts flow."""
with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": "user"}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["step_id"] == "creds"
with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["step_id"] == "mode"
with patch("pyps4_2ndscreen.Helper.has_devices", return_value=[]):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input=MOCK_AUTO
)
assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT
assert result["reason"] == "no_devices_found" | [
"async",
"def",
"test_no_devices_found_abort",
"(",
"hass",
")",
":",
"with",
"patch",
"(",
"\"pyps4_2ndscreen.Helper.port_bind\"",
",",
"return_value",
"=",
"None",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"\"user\"",
"}",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_FORM",
"assert",
"result",
"[",
"\"step_id\"",
"]",
"==",
"\"creds\"",
"with",
"patch",
"(",
"\"pyps4_2ndscreen.Helper.get_creds\"",
",",
"return_value",
"=",
"MOCK_CREDS",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_configure",
"(",
"result",
"[",
"\"flow_id\"",
"]",
",",
"user_input",
"=",
"{",
"}",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_FORM",
"assert",
"result",
"[",
"\"step_id\"",
"]",
"==",
"\"mode\"",
"with",
"patch",
"(",
"\"pyps4_2ndscreen.Helper.has_devices\"",
",",
"return_value",
"=",
"[",
"]",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_configure",
"(",
"result",
"[",
"\"flow_id\"",
"]",
",",
"user_input",
"=",
"MOCK_AUTO",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_ABORT",
"assert",
"result",
"[",
"\"reason\"",
"]",
"==",
"\"no_devices_found\""
] | [
366,
0
] | [
388,
49
] | python | en | ['en', 'en', 'en'] | True |
test_manual_mode | (hass) | Test host specified in manual mode is passed to Step Link. | Test host specified in manual mode is passed to Step Link. | async def test_manual_mode(hass):
"""Test host specified in manual mode is passed to Step Link."""
with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": "user"}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["step_id"] == "creds"
with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["step_id"] == "mode"
# Step Mode with User Input: manual, results in Step Link.
with patch(
"pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}]
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input=MOCK_MANUAL
)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["step_id"] == "link" | [
"async",
"def",
"test_manual_mode",
"(",
"hass",
")",
":",
"with",
"patch",
"(",
"\"pyps4_2ndscreen.Helper.port_bind\"",
",",
"return_value",
"=",
"None",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"\"user\"",
"}",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_FORM",
"assert",
"result",
"[",
"\"step_id\"",
"]",
"==",
"\"creds\"",
"with",
"patch",
"(",
"\"pyps4_2ndscreen.Helper.get_creds\"",
",",
"return_value",
"=",
"MOCK_CREDS",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_configure",
"(",
"result",
"[",
"\"flow_id\"",
"]",
",",
"user_input",
"=",
"{",
"}",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_FORM",
"assert",
"result",
"[",
"\"step_id\"",
"]",
"==",
"\"mode\"",
"# Step Mode with User Input: manual, results in Step Link.",
"with",
"patch",
"(",
"\"pyps4_2ndscreen.Helper.has_devices\"",
",",
"return_value",
"=",
"[",
"{",
"\"host-ip\"",
":",
"MOCK_HOST",
"}",
"]",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_configure",
"(",
"result",
"[",
"\"flow_id\"",
"]",
",",
"user_input",
"=",
"MOCK_MANUAL",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_FORM",
"assert",
"result",
"[",
"\"step_id\"",
"]",
"==",
"\"link\""
] | [
391,
0
] | [
416,
38
] | python | en | ['en', 'en', 'en'] | True |
test_credential_abort | (hass) | Test that failure to get credentials aborts flow. | Test that failure to get credentials aborts flow. | async def test_credential_abort(hass):
"""Test that failure to get credentials aborts flow."""
with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": "user"}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["step_id"] == "creds"
with patch("pyps4_2ndscreen.Helper.get_creds", return_value=None):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT
assert result["reason"] == "credential_error" | [
"async",
"def",
"test_credential_abort",
"(",
"hass",
")",
":",
"with",
"patch",
"(",
"\"pyps4_2ndscreen.Helper.port_bind\"",
",",
"return_value",
"=",
"None",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"\"user\"",
"}",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_FORM",
"assert",
"result",
"[",
"\"step_id\"",
"]",
"==",
"\"creds\"",
"with",
"patch",
"(",
"\"pyps4_2ndscreen.Helper.get_creds\"",
",",
"return_value",
"=",
"None",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_configure",
"(",
"result",
"[",
"\"flow_id\"",
"]",
",",
"user_input",
"=",
"{",
"}",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_ABORT",
"assert",
"result",
"[",
"\"reason\"",
"]",
"==",
"\"credential_error\""
] | [
419,
0
] | [
434,
49
] | python | en | ['en', 'de', 'en'] | True |
test_credential_timeout | (hass) | Test that Credential Timeout shows error. | Test that Credential Timeout shows error. | async def test_credential_timeout(hass):
"""Test that Credential Timeout shows error."""
with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": "user"}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["step_id"] == "creds"
with patch("pyps4_2ndscreen.Helper.get_creds", side_effect=CredentialTimeout):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["step_id"] == "creds"
assert result["errors"] == {"base": "credential_timeout"} | [
"async",
"def",
"test_credential_timeout",
"(",
"hass",
")",
":",
"with",
"patch",
"(",
"\"pyps4_2ndscreen.Helper.port_bind\"",
",",
"return_value",
"=",
"None",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"\"user\"",
"}",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_FORM",
"assert",
"result",
"[",
"\"step_id\"",
"]",
"==",
"\"creds\"",
"with",
"patch",
"(",
"\"pyps4_2ndscreen.Helper.get_creds\"",
",",
"side_effect",
"=",
"CredentialTimeout",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_configure",
"(",
"result",
"[",
"\"flow_id\"",
"]",
",",
"user_input",
"=",
"{",
"}",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_FORM",
"assert",
"result",
"[",
"\"step_id\"",
"]",
"==",
"\"creds\"",
"assert",
"result",
"[",
"\"errors\"",
"]",
"==",
"{",
"\"base\"",
":",
"\"credential_timeout\"",
"}"
] | [
437,
0
] | [
453,
61
] | python | en | ['en', 'en', 'en'] | True |
test_wrong_pin_error | (hass) | Test that incorrect pin throws an error. | Test that incorrect pin throws an error. | async def test_wrong_pin_error(hass):
"""Test that incorrect pin throws an error."""
with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": "user"}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["step_id"] == "creds"
with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["step_id"] == "mode"
with patch(
"pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}]
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input=MOCK_AUTO
)
with patch("pyps4_2ndscreen.Helper.link", return_value=(True, False)):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input=MOCK_CONFIG
)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["step_id"] == "link"
assert result["errors"] == {"base": "login_failed"} | [
"async",
"def",
"test_wrong_pin_error",
"(",
"hass",
")",
":",
"with",
"patch",
"(",
"\"pyps4_2ndscreen.Helper.port_bind\"",
",",
"return_value",
"=",
"None",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"\"user\"",
"}",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_FORM",
"assert",
"result",
"[",
"\"step_id\"",
"]",
"==",
"\"creds\"",
"with",
"patch",
"(",
"\"pyps4_2ndscreen.Helper.get_creds\"",
",",
"return_value",
"=",
"MOCK_CREDS",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_configure",
"(",
"result",
"[",
"\"flow_id\"",
"]",
",",
"user_input",
"=",
"{",
"}",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_FORM",
"assert",
"result",
"[",
"\"step_id\"",
"]",
"==",
"\"mode\"",
"with",
"patch",
"(",
"\"pyps4_2ndscreen.Helper.has_devices\"",
",",
"return_value",
"=",
"[",
"{",
"\"host-ip\"",
":",
"MOCK_HOST",
"}",
"]",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_configure",
"(",
"result",
"[",
"\"flow_id\"",
"]",
",",
"user_input",
"=",
"MOCK_AUTO",
")",
"with",
"patch",
"(",
"\"pyps4_2ndscreen.Helper.link\"",
",",
"return_value",
"=",
"(",
"True",
",",
"False",
")",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_configure",
"(",
"result",
"[",
"\"flow_id\"",
"]",
",",
"user_input",
"=",
"MOCK_CONFIG",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_FORM",
"assert",
"result",
"[",
"\"step_id\"",
"]",
"==",
"\"link\"",
"assert",
"result",
"[",
"\"errors\"",
"]",
"==",
"{",
"\"base\"",
":",
"\"login_failed\"",
"}"
] | [
456,
0
] | [
485,
55
] | python | en | ['en', 'en', 'en'] | True |
test_device_connection_error | (hass) | Test that device not connected or on throws an error. | Test that device not connected or on throws an error. | async def test_device_connection_error(hass):
"""Test that device not connected or on throws an error."""
with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": "user"}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["step_id"] == "creds"
with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["step_id"] == "mode"
with patch(
"pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}]
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input=MOCK_AUTO
)
with patch("pyps4_2ndscreen.Helper.link", return_value=(False, True)):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input=MOCK_CONFIG
)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["step_id"] == "link"
assert result["errors"] == {"base": "cannot_connect"} | [
"async",
"def",
"test_device_connection_error",
"(",
"hass",
")",
":",
"with",
"patch",
"(",
"\"pyps4_2ndscreen.Helper.port_bind\"",
",",
"return_value",
"=",
"None",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"\"user\"",
"}",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_FORM",
"assert",
"result",
"[",
"\"step_id\"",
"]",
"==",
"\"creds\"",
"with",
"patch",
"(",
"\"pyps4_2ndscreen.Helper.get_creds\"",
",",
"return_value",
"=",
"MOCK_CREDS",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_configure",
"(",
"result",
"[",
"\"flow_id\"",
"]",
",",
"user_input",
"=",
"{",
"}",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_FORM",
"assert",
"result",
"[",
"\"step_id\"",
"]",
"==",
"\"mode\"",
"with",
"patch",
"(",
"\"pyps4_2ndscreen.Helper.has_devices\"",
",",
"return_value",
"=",
"[",
"{",
"\"host-ip\"",
":",
"MOCK_HOST",
"}",
"]",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_configure",
"(",
"result",
"[",
"\"flow_id\"",
"]",
",",
"user_input",
"=",
"MOCK_AUTO",
")",
"with",
"patch",
"(",
"\"pyps4_2ndscreen.Helper.link\"",
",",
"return_value",
"=",
"(",
"False",
",",
"True",
")",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_configure",
"(",
"result",
"[",
"\"flow_id\"",
"]",
",",
"user_input",
"=",
"MOCK_CONFIG",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_FORM",
"assert",
"result",
"[",
"\"step_id\"",
"]",
"==",
"\"link\"",
"assert",
"result",
"[",
"\"errors\"",
"]",
"==",
"{",
"\"base\"",
":",
"\"cannot_connect\"",
"}"
] | [
488,
0
] | [
517,
57
] | python | en | ['en', 'en', 'en'] | True |
test_manual_mode_no_ip_error | (hass) | Test no IP specified in manual mode throws an error. | Test no IP specified in manual mode throws an error. | async def test_manual_mode_no_ip_error(hass):
"""Test no IP specified in manual mode throws an error."""
with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": "user"}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["step_id"] == "creds"
with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["step_id"] == "mode"
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={"Config Mode": "Manual Entry"}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["step_id"] == "mode"
assert result["errors"] == {CONF_IP_ADDRESS: "no_ipaddress"} | [
"async",
"def",
"test_manual_mode_no_ip_error",
"(",
"hass",
")",
":",
"with",
"patch",
"(",
"\"pyps4_2ndscreen.Helper.port_bind\"",
",",
"return_value",
"=",
"None",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"\"user\"",
"}",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_FORM",
"assert",
"result",
"[",
"\"step_id\"",
"]",
"==",
"\"creds\"",
"with",
"patch",
"(",
"\"pyps4_2ndscreen.Helper.get_creds\"",
",",
"return_value",
"=",
"MOCK_CREDS",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_configure",
"(",
"result",
"[",
"\"flow_id\"",
"]",
",",
"user_input",
"=",
"{",
"}",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_FORM",
"assert",
"result",
"[",
"\"step_id\"",
"]",
"==",
"\"mode\"",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_configure",
"(",
"result",
"[",
"\"flow_id\"",
"]",
",",
"user_input",
"=",
"{",
"\"Config Mode\"",
":",
"\"Manual Entry\"",
"}",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_FORM",
"assert",
"result",
"[",
"\"step_id\"",
"]",
"==",
"\"mode\"",
"assert",
"result",
"[",
"\"errors\"",
"]",
"==",
"{",
"CONF_IP_ADDRESS",
":",
"\"no_ipaddress\"",
"}"
] | [
520,
0
] | [
542,
64
] | python | en | ['en', 'en', 'en'] | True |
_get_non_vacuum_device | () | Return a non vacuum device. | Return a non vacuum device. | def _get_non_vacuum_device():
"""Return a non vacuum device."""
device = mock.Mock()
device.name = "Device_Fan"
device.state = None
return device | [
"def",
"_get_non_vacuum_device",
"(",
")",
":",
"device",
"=",
"mock",
".",
"Mock",
"(",
")",
"device",
".",
"name",
"=",
"\"Device_Fan\"",
"device",
".",
"state",
"=",
"None",
"return",
"device"
] | [
13,
0
] | [
18,
17
] | python | en | ['la', 'it', 'en'] | False |
_get_vacuum_device_cleaning | () | Return a vacuum device running. | Return a vacuum device running. | def _get_vacuum_device_cleaning():
"""Return a vacuum device running."""
device = mock.Mock(spec=Dyson360Eye)
device.name = "Device_Vacuum"
device.state = mock.MagicMock()
device.state.state = Dyson360EyeMode.FULL_CLEAN_RUNNING
device.state.battery_level = 85
device.state.power_mode = PowerMode.QUIET
device.state.position = (0, 0)
return device | [
"def",
"_get_vacuum_device_cleaning",
"(",
")",
":",
"device",
"=",
"mock",
".",
"Mock",
"(",
"spec",
"=",
"Dyson360Eye",
")",
"device",
".",
"name",
"=",
"\"Device_Vacuum\"",
"device",
".",
"state",
"=",
"mock",
".",
"MagicMock",
"(",
")",
"device",
".",
"state",
".",
"state",
"=",
"Dyson360EyeMode",
".",
"FULL_CLEAN_RUNNING",
"device",
".",
"state",
".",
"battery_level",
"=",
"85",
"device",
".",
"state",
".",
"power_mode",
"=",
"PowerMode",
".",
"QUIET",
"device",
".",
"state",
".",
"position",
"=",
"(",
"0",
",",
"0",
")",
"return",
"device"
] | [
21,
0
] | [
30,
17
] | python | de | ['de', 'la', 'en'] | False |
_get_vacuum_device_charging | () | Return a vacuum device charging. | Return a vacuum device charging. | def _get_vacuum_device_charging():
"""Return a vacuum device charging."""
device = mock.Mock(spec=Dyson360Eye)
device.name = "Device_Vacuum"
device.state = mock.MagicMock()
device.state.state = Dyson360EyeMode.INACTIVE_CHARGING
device.state.battery_level = 40
device.state.power_mode = PowerMode.QUIET
device.state.position = (0, 0)
return device | [
"def",
"_get_vacuum_device_charging",
"(",
")",
":",
"device",
"=",
"mock",
".",
"Mock",
"(",
"spec",
"=",
"Dyson360Eye",
")",
"device",
".",
"name",
"=",
"\"Device_Vacuum\"",
"device",
".",
"state",
"=",
"mock",
".",
"MagicMock",
"(",
")",
"device",
".",
"state",
".",
"state",
"=",
"Dyson360EyeMode",
".",
"INACTIVE_CHARGING",
"device",
".",
"state",
".",
"battery_level",
"=",
"40",
"device",
".",
"state",
".",
"power_mode",
"=",
"PowerMode",
".",
"QUIET",
"device",
".",
"state",
".",
"position",
"=",
"(",
"0",
",",
"0",
")",
"return",
"device"
] | [
33,
0
] | [
42,
17
] | python | bg | ['pt', 'bg', 'en'] | False |
_get_vacuum_device_pause | () | Return a vacuum device in pause. | Return a vacuum device in pause. | def _get_vacuum_device_pause():
"""Return a vacuum device in pause."""
device = mock.MagicMock(spec=Dyson360Eye)
device.name = "Device_Vacuum"
device.state = mock.MagicMock()
device.state.state = Dyson360EyeMode.FULL_CLEAN_PAUSED
device.state.battery_level = 40
device.state.power_mode = PowerMode.QUIET
device.state.position = (0, 0)
return device | [
"def",
"_get_vacuum_device_pause",
"(",
")",
":",
"device",
"=",
"mock",
".",
"MagicMock",
"(",
"spec",
"=",
"Dyson360Eye",
")",
"device",
".",
"name",
"=",
"\"Device_Vacuum\"",
"device",
".",
"state",
"=",
"mock",
".",
"MagicMock",
"(",
")",
"device",
".",
"state",
".",
"state",
"=",
"Dyson360EyeMode",
".",
"FULL_CLEAN_PAUSED",
"device",
".",
"state",
".",
"battery_level",
"=",
"40",
"device",
".",
"state",
".",
"power_mode",
"=",
"PowerMode",
".",
"QUIET",
"device",
".",
"state",
".",
"position",
"=",
"(",
"0",
",",
"0",
")",
"return",
"device"
] | [
45,
0
] | [
54,
17
] | python | en | ['de', 'en', 'en'] | True |
_get_vacuum_device_unknown_state | () | Return a vacuum device with unknown state. | Return a vacuum device with unknown state. | def _get_vacuum_device_unknown_state():
"""Return a vacuum device with unknown state."""
device = mock.Mock(spec=Dyson360Eye)
device.name = "Device_Vacuum"
device.state = mock.MagicMock()
device.state.state = "Unknown"
return device | [
"def",
"_get_vacuum_device_unknown_state",
"(",
")",
":",
"device",
"=",
"mock",
".",
"Mock",
"(",
"spec",
"=",
"Dyson360Eye",
")",
"device",
".",
"name",
"=",
"\"Device_Vacuum\"",
"device",
".",
"state",
"=",
"mock",
".",
"MagicMock",
"(",
")",
"device",
".",
"state",
".",
"state",
"=",
"\"Unknown\"",
"return",
"device"
] | [
57,
0
] | [
63,
17
] | python | en | ['en', 'en', 'en'] | True |
DysonTest.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",
")"
] | [
69,
4
] | [
72,
47
] | python | en | ['en', 'en', 'en'] | True |
DysonTest.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",
"(",
")"
] | [
74,
4
] | [
76,
24
] | python | en | ['en', 'en', 'en'] | True |
DysonTest.test_setup_component_with_no_devices | (self) | Test setup component with no devices. | Test setup component with no devices. | def test_setup_component_with_no_devices(self):
"""Test setup component with no devices."""
self.hass.data[dyson.DYSON_DEVICES] = []
add_entities = mock.MagicMock()
dyson.setup_platform(self.hass, {}, add_entities)
add_entities.assert_called_with([]) | [
"def",
"test_setup_component_with_no_devices",
"(",
"self",
")",
":",
"self",
".",
"hass",
".",
"data",
"[",
"dyson",
".",
"DYSON_DEVICES",
"]",
"=",
"[",
"]",
"add_entities",
"=",
"mock",
".",
"MagicMock",
"(",
")",
"dyson",
".",
"setup_platform",
"(",
"self",
".",
"hass",
",",
"{",
"}",
",",
"add_entities",
")",
"add_entities",
".",
"assert_called_with",
"(",
"[",
"]",
")"
] | [
78,
4
] | [
83,
43
] | python | en | ['en', 'en', 'en'] | True |
DysonTest.test_setup_component | (self) | Test setup component with devices. | Test setup component with devices. | def test_setup_component(self):
"""Test setup component with devices."""
def _add_device(devices):
assert len(devices) == 1
assert devices[0].name == "Device_Vacuum"
device_vacuum = _get_vacuum_device_cleaning()
device_non_vacuum = _get_non_vacuum_device()
self.hass.data[dyson.DYSON_DEVICES] = [device_vacuum, device_non_vacuum]
dyson.setup_platform(self.hass, {}, _add_device) | [
"def",
"test_setup_component",
"(",
"self",
")",
":",
"def",
"_add_device",
"(",
"devices",
")",
":",
"assert",
"len",
"(",
"devices",
")",
"==",
"1",
"assert",
"devices",
"[",
"0",
"]",
".",
"name",
"==",
"\"Device_Vacuum\"",
"device_vacuum",
"=",
"_get_vacuum_device_cleaning",
"(",
")",
"device_non_vacuum",
"=",
"_get_non_vacuum_device",
"(",
")",
"self",
".",
"hass",
".",
"data",
"[",
"dyson",
".",
"DYSON_DEVICES",
"]",
"=",
"[",
"device_vacuum",
",",
"device_non_vacuum",
"]",
"dyson",
".",
"setup_platform",
"(",
"self",
".",
"hass",
",",
"{",
"}",
",",
"_add_device",
")"
] | [
85,
4
] | [
95,
56
] | python | en | ['en', 'en', 'en'] | True |
DysonTest.test_on_message | (self) | Test when message is received. | Test when message is received. | def test_on_message(self):
"""Test when message is received."""
device = _get_vacuum_device_cleaning()
component = Dyson360EyeDevice(device)
component.entity_id = "entity_id"
component.schedule_update_ha_state = mock.Mock()
component.on_message(mock.Mock())
assert component.schedule_update_ha_state.called | [
"def",
"test_on_message",
"(",
"self",
")",
":",
"device",
"=",
"_get_vacuum_device_cleaning",
"(",
")",
"component",
"=",
"Dyson360EyeDevice",
"(",
"device",
")",
"component",
".",
"entity_id",
"=",
"\"entity_id\"",
"component",
".",
"schedule_update_ha_state",
"=",
"mock",
".",
"Mock",
"(",
")",
"component",
".",
"on_message",
"(",
"mock",
".",
"Mock",
"(",
")",
")",
"assert",
"component",
".",
"schedule_update_ha_state",
".",
"called"
] | [
97,
4
] | [
104,
56
] | python | en | ['en', 'en', 'en'] | True |
DysonTest.test_should_poll | (self) | Test polling is disable. | Test polling is disable. | def test_should_poll(self):
"""Test polling is disable."""
device = _get_vacuum_device_cleaning()
component = Dyson360EyeDevice(device)
assert not component.should_poll | [
"def",
"test_should_poll",
"(",
"self",
")",
":",
"device",
"=",
"_get_vacuum_device_cleaning",
"(",
")",
"component",
"=",
"Dyson360EyeDevice",
"(",
"device",
")",
"assert",
"not",
"component",
".",
"should_poll"
] | [
106,
4
] | [
110,
40
] | python | en | ['en', 'en', 'en'] | True |
DysonTest.test_properties | (self) | Test component properties. | Test component properties. | def test_properties(self):
"""Test component properties."""
device1 = _get_vacuum_device_cleaning()
device2 = _get_vacuum_device_unknown_state()
device3 = _get_vacuum_device_charging()
component = Dyson360EyeDevice(device1)
component2 = Dyson360EyeDevice(device2)
component3 = Dyson360EyeDevice(device3)
assert component.name == "Device_Vacuum"
assert component.is_on
assert component.status == "Cleaning"
assert component2.status == "Unknown"
assert component.battery_level == 85
assert component.fan_speed == "Quiet"
assert component.fan_speed_list == ["Quiet", "Max"]
assert component.device_state_attributes["position"] == "(0, 0)"
assert component.available
assert component.supported_features == 255
assert component.battery_icon == "mdi:battery-80"
assert component3.battery_icon == "mdi:battery-charging-40" | [
"def",
"test_properties",
"(",
"self",
")",
":",
"device1",
"=",
"_get_vacuum_device_cleaning",
"(",
")",
"device2",
"=",
"_get_vacuum_device_unknown_state",
"(",
")",
"device3",
"=",
"_get_vacuum_device_charging",
"(",
")",
"component",
"=",
"Dyson360EyeDevice",
"(",
"device1",
")",
"component2",
"=",
"Dyson360EyeDevice",
"(",
"device2",
")",
"component3",
"=",
"Dyson360EyeDevice",
"(",
"device3",
")",
"assert",
"component",
".",
"name",
"==",
"\"Device_Vacuum\"",
"assert",
"component",
".",
"is_on",
"assert",
"component",
".",
"status",
"==",
"\"Cleaning\"",
"assert",
"component2",
".",
"status",
"==",
"\"Unknown\"",
"assert",
"component",
".",
"battery_level",
"==",
"85",
"assert",
"component",
".",
"fan_speed",
"==",
"\"Quiet\"",
"assert",
"component",
".",
"fan_speed_list",
"==",
"[",
"\"Quiet\"",
",",
"\"Max\"",
"]",
"assert",
"component",
".",
"device_state_attributes",
"[",
"\"position\"",
"]",
"==",
"\"(0, 0)\"",
"assert",
"component",
".",
"available",
"assert",
"component",
".",
"supported_features",
"==",
"255",
"assert",
"component",
".",
"battery_icon",
"==",
"\"mdi:battery-80\"",
"assert",
"component3",
".",
"battery_icon",
"==",
"\"mdi:battery-charging-40\""
] | [
112,
4
] | [
131,
67
] | python | en | ['en', 'nl', 'en'] | True |
DysonTest.test_turn_on | (self) | Test turn on vacuum. | Test turn on vacuum. | def test_turn_on(self):
"""Test turn on vacuum."""
device1 = _get_vacuum_device_charging()
component1 = Dyson360EyeDevice(device1)
component1.turn_on()
assert device1.start.called
device2 = _get_vacuum_device_pause()
component2 = Dyson360EyeDevice(device2)
component2.turn_on()
assert device2.resume.called | [
"def",
"test_turn_on",
"(",
"self",
")",
":",
"device1",
"=",
"_get_vacuum_device_charging",
"(",
")",
"component1",
"=",
"Dyson360EyeDevice",
"(",
"device1",
")",
"component1",
".",
"turn_on",
"(",
")",
"assert",
"device1",
".",
"start",
".",
"called",
"device2",
"=",
"_get_vacuum_device_pause",
"(",
")",
"component2",
"=",
"Dyson360EyeDevice",
"(",
"device2",
")",
"component2",
".",
"turn_on",
"(",
")",
"assert",
"device2",
".",
"resume",
".",
"called"
] | [
133,
4
] | [
143,
36
] | python | et | ['et', 'et', 'en'] | True |
DysonTest.test_turn_off | (self) | Test turn off vacuum. | Test turn off vacuum. | def test_turn_off(self):
"""Test turn off vacuum."""
device1 = _get_vacuum_device_cleaning()
component1 = Dyson360EyeDevice(device1)
component1.turn_off()
assert device1.pause.called | [
"def",
"test_turn_off",
"(",
"self",
")",
":",
"device1",
"=",
"_get_vacuum_device_cleaning",
"(",
")",
"component1",
"=",
"Dyson360EyeDevice",
"(",
"device1",
")",
"component1",
".",
"turn_off",
"(",
")",
"assert",
"device1",
".",
"pause",
".",
"called"
] | [
145,
4
] | [
150,
35
] | python | en | ['en', 'la', 'en'] | True |
DysonTest.test_stop | (self) | Test stop vacuum. | Test stop vacuum. | def test_stop(self):
"""Test stop vacuum."""
device1 = _get_vacuum_device_cleaning()
component1 = Dyson360EyeDevice(device1)
component1.stop()
assert device1.pause.called | [
"def",
"test_stop",
"(",
"self",
")",
":",
"device1",
"=",
"_get_vacuum_device_cleaning",
"(",
")",
"component1",
"=",
"Dyson360EyeDevice",
"(",
"device1",
")",
"component1",
".",
"stop",
"(",
")",
"assert",
"device1",
".",
"pause",
".",
"called"
] | [
152,
4
] | [
157,
35
] | python | en | ['nl', 'la', 'en'] | False |
DysonTest.test_set_fan_speed | (self) | Test set fan speed vacuum. | Test set fan speed vacuum. | def test_set_fan_speed(self):
"""Test set fan speed vacuum."""
device1 = _get_vacuum_device_cleaning()
component1 = Dyson360EyeDevice(device1)
component1.set_fan_speed("Max")
device1.set_power_mode.assert_called_with(PowerMode.MAX) | [
"def",
"test_set_fan_speed",
"(",
"self",
")",
":",
"device1",
"=",
"_get_vacuum_device_cleaning",
"(",
")",
"component1",
"=",
"Dyson360EyeDevice",
"(",
"device1",
")",
"component1",
".",
"set_fan_speed",
"(",
"\"Max\"",
")",
"device1",
".",
"set_power_mode",
".",
"assert_called_with",
"(",
"PowerMode",
".",
"MAX",
")"
] | [
159,
4
] | [
164,
64
] | python | en | ['en', 'fy', 'nl'] | False |
DysonTest.test_start_pause | (self) | Test start/pause. | Test start/pause. | def test_start_pause(self):
"""Test start/pause."""
device1 = _get_vacuum_device_charging()
component1 = Dyson360EyeDevice(device1)
component1.start_pause()
assert device1.start.called
device2 = _get_vacuum_device_pause()
component2 = Dyson360EyeDevice(device2)
component2.start_pause()
assert device2.resume.called
device3 = _get_vacuum_device_cleaning()
component3 = Dyson360EyeDevice(device3)
component3.start_pause()
assert device3.pause.called | [
"def",
"test_start_pause",
"(",
"self",
")",
":",
"device1",
"=",
"_get_vacuum_device_charging",
"(",
")",
"component1",
"=",
"Dyson360EyeDevice",
"(",
"device1",
")",
"component1",
".",
"start_pause",
"(",
")",
"assert",
"device1",
".",
"start",
".",
"called",
"device2",
"=",
"_get_vacuum_device_pause",
"(",
")",
"component2",
"=",
"Dyson360EyeDevice",
"(",
"device2",
")",
"component2",
".",
"start_pause",
"(",
")",
"assert",
"device2",
".",
"resume",
".",
"called",
"device3",
"=",
"_get_vacuum_device_cleaning",
"(",
")",
"component3",
"=",
"Dyson360EyeDevice",
"(",
"device3",
")",
"component3",
".",
"start_pause",
"(",
")",
"assert",
"device3",
".",
"pause",
".",
"called"
] | [
166,
4
] | [
181,
35
] | python | de | ['de', 'fi', 'en'] | False |
DysonTest.test_return_to_base | (self) | Test return to base. | Test return to base. | def test_return_to_base(self):
"""Test return to base."""
device = _get_vacuum_device_pause()
component = Dyson360EyeDevice(device)
component.return_to_base()
assert device.abort.called | [
"def",
"test_return_to_base",
"(",
"self",
")",
":",
"device",
"=",
"_get_vacuum_device_pause",
"(",
")",
"component",
"=",
"Dyson360EyeDevice",
"(",
"device",
")",
"component",
".",
"return_to_base",
"(",
")",
"assert",
"device",
".",
"abort",
".",
"called"
] | [
183,
4
] | [
188,
34
] | python | en | ['en', 'ig', 'en'] | True |
EfficientAttentionMixin._look_adjacent | (self, vectors, num_chunks_before, num_chunks_after) |
Used to implement attention between consecutive chunks.
Args:
vectors: array of shape [batch_size, num_attention_heads, n_chunks, chunk_len, ...]
num_chunks_before: chunks before current chunk to include in attention
num_chunks_after: chunks after current chunk to include in attention
Returns:
tensor of shape [num_chunks, N * chunk_length, ...], where N = (1 + num_chunks_before + num_chunks_after).
|
Used to implement attention between consecutive chunks. | def _look_adjacent(self, vectors, num_chunks_before, num_chunks_after):
"""
Used to implement attention between consecutive chunks.
Args:
vectors: array of shape [batch_size, num_attention_heads, n_chunks, chunk_len, ...]
num_chunks_before: chunks before current chunk to include in attention
num_chunks_after: chunks after current chunk to include in attention
Returns:
tensor of shape [num_chunks, N * chunk_length, ...], where N = (1 + num_chunks_before + num_chunks_after).
"""
if num_chunks_before == 0 and num_chunks_after == 0:
return vectors
slices = []
for i in range(-num_chunks_before, num_chunks_after + 1):
if i == 0:
slices.append(vectors)
else:
slices.append(torch.cat([vectors[:, :, i:, ...], vectors[:, :, :i, ...]], dim=2))
return torch.cat(slices, dim=3) | [
"def",
"_look_adjacent",
"(",
"self",
",",
"vectors",
",",
"num_chunks_before",
",",
"num_chunks_after",
")",
":",
"if",
"num_chunks_before",
"==",
"0",
"and",
"num_chunks_after",
"==",
"0",
":",
"return",
"vectors",
"slices",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"-",
"num_chunks_before",
",",
"num_chunks_after",
"+",
"1",
")",
":",
"if",
"i",
"==",
"0",
":",
"slices",
".",
"append",
"(",
"vectors",
")",
"else",
":",
"slices",
".",
"append",
"(",
"torch",
".",
"cat",
"(",
"[",
"vectors",
"[",
":",
",",
":",
",",
"i",
":",
",",
"...",
"]",
",",
"vectors",
"[",
":",
",",
":",
",",
":",
"i",
",",
"...",
"]",
"]",
",",
"dim",
"=",
"2",
")",
")",
"return",
"torch",
".",
"cat",
"(",
"slices",
",",
"dim",
"=",
"3",
")"
] | [
274,
4
] | [
295,
39
] | python | en | ['en', 'error', 'th'] | False |
EfficientAttentionMixin._split_hidden_size_dim | (self, x, num_attn_heads, attn_head_size) |
splits hidden_size dim into attn_head_size and num_attn_heads
|
splits hidden_size dim into attn_head_size and num_attn_heads
| def _split_hidden_size_dim(self, x, num_attn_heads, attn_head_size):
"""
splits hidden_size dim into attn_head_size and num_attn_heads
"""
new_x_shape = x.size()[:-1] + (num_attn_heads, attn_head_size)
x = x.view(*new_x_shape)
return x.transpose(2, 1) | [
"def",
"_split_hidden_size_dim",
"(",
"self",
",",
"x",
",",
"num_attn_heads",
",",
"attn_head_size",
")",
":",
"new_x_shape",
"=",
"x",
".",
"size",
"(",
")",
"[",
":",
"-",
"1",
"]",
"+",
"(",
"num_attn_heads",
",",
"attn_head_size",
")",
"x",
"=",
"x",
".",
"view",
"(",
"*",
"new_x_shape",
")",
"return",
"x",
".",
"transpose",
"(",
"2",
",",
"1",
")"
] | [
297,
4
] | [
303,
32
] | python | en | ['en', 'error', 'th'] | False |
EfficientAttentionMixin._merge_hidden_size_dims | (self, x, num_attn_heads, attn_head_size) |
merges attn_head_size dim and num_attn_heads dim into hidden_size
|
merges attn_head_size dim and num_attn_heads dim into hidden_size
| def _merge_hidden_size_dims(self, x, num_attn_heads, attn_head_size):
"""
merges attn_head_size dim and num_attn_heads dim into hidden_size
"""
x = x.permute(0, 2, 1, 3)
return torch.reshape(x, (x.size()[0], -1, num_attn_heads * attn_head_size)) | [
"def",
"_merge_hidden_size_dims",
"(",
"self",
",",
"x",
",",
"num_attn_heads",
",",
"attn_head_size",
")",
":",
"x",
"=",
"x",
".",
"permute",
"(",
"0",
",",
"2",
",",
"1",
",",
"3",
")",
"return",
"torch",
".",
"reshape",
"(",
"x",
",",
"(",
"x",
".",
"size",
"(",
")",
"[",
"0",
"]",
",",
"-",
"1",
",",
"num_attn_heads",
"*",
"attn_head_size",
")",
")"
] | [
305,
4
] | [
310,
83
] | python | en | ['en', 'error', 'th'] | False |
EfficientAttentionMixin._split_seq_length_dim_to | (self, vectors, dim_factor_1, dim_factor_2, num_attn_heads, attn_head_size=None) |
splits sequence length dim of vectors into `dim_factor_1` and `dim_factor_2` dims
|
splits sequence length dim of vectors into `dim_factor_1` and `dim_factor_2` dims
| def _split_seq_length_dim_to(self, vectors, dim_factor_1, dim_factor_2, num_attn_heads, attn_head_size=None):
"""
splits sequence length dim of vectors into `dim_factor_1` and `dim_factor_2` dims
"""
batch_size = vectors.shape[0]
split_dim_shape = (batch_size, num_attn_heads, dim_factor_1, dim_factor_2)
if len(vectors.shape) == 4:
return torch.reshape(vectors, split_dim_shape + (attn_head_size,))
elif len(vectors.shape) == 3:
return torch.reshape(vectors, split_dim_shape)
else:
raise ValueError("Input vector rank should be one of [3, 4], but is: {}".format(len(vectors.shape))) | [
"def",
"_split_seq_length_dim_to",
"(",
"self",
",",
"vectors",
",",
"dim_factor_1",
",",
"dim_factor_2",
",",
"num_attn_heads",
",",
"attn_head_size",
"=",
"None",
")",
":",
"batch_size",
"=",
"vectors",
".",
"shape",
"[",
"0",
"]",
"split_dim_shape",
"=",
"(",
"batch_size",
",",
"num_attn_heads",
",",
"dim_factor_1",
",",
"dim_factor_2",
")",
"if",
"len",
"(",
"vectors",
".",
"shape",
")",
"==",
"4",
":",
"return",
"torch",
".",
"reshape",
"(",
"vectors",
",",
"split_dim_shape",
"+",
"(",
"attn_head_size",
",",
")",
")",
"elif",
"len",
"(",
"vectors",
".",
"shape",
")",
"==",
"3",
":",
"return",
"torch",
".",
"reshape",
"(",
"vectors",
",",
"split_dim_shape",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"Input vector rank should be one of [3, 4], but is: {}\"",
".",
"format",
"(",
"len",
"(",
"vectors",
".",
"shape",
")",
")",
")"
] | [
312,
4
] | [
324,
112
] | python | en | ['en', 'error', 'th'] | False |
LSHSelfAttention._len_and_dim_norm | (self, vectors) |
length and attention head size dim normalization
|
length and attention head size dim normalization
| def _len_and_dim_norm(self, vectors):
"""
length and attention head size dim normalization
"""
vectors = self._len_norm(vectors)
vectors = vectors * torch.rsqrt(
torch.tensor(self.attention_head_size, device=vectors.device, dtype=vectors.dtype)
)
return vectors | [
"def",
"_len_and_dim_norm",
"(",
"self",
",",
"vectors",
")",
":",
"vectors",
"=",
"self",
".",
"_len_norm",
"(",
"vectors",
")",
"vectors",
"=",
"vectors",
"*",
"torch",
".",
"rsqrt",
"(",
"torch",
".",
"tensor",
"(",
"self",
".",
"attention_head_size",
",",
"device",
"=",
"vectors",
".",
"device",
",",
"dtype",
"=",
"vectors",
".",
"dtype",
")",
")",
"return",
"vectors"
] | [
958,
4
] | [
966,
22
] | python | en | ['en', 'error', 'th'] | False |
LSHSelfAttention._len_norm | (self, x, epsilon=1e-6) |
length normalization
|
length normalization
| def _len_norm(self, x, epsilon=1e-6):
"""
length normalization
"""
variance = torch.mean(x ** 2, -1, keepdim=True)
norm_x = x * torch.rsqrt(variance + epsilon)
return norm_x | [
"def",
"_len_norm",
"(",
"self",
",",
"x",
",",
"epsilon",
"=",
"1e-6",
")",
":",
"variance",
"=",
"torch",
".",
"mean",
"(",
"x",
"**",
"2",
",",
"-",
"1",
",",
"keepdim",
"=",
"True",
")",
"norm_x",
"=",
"x",
"*",
"torch",
".",
"rsqrt",
"(",
"variance",
"+",
"epsilon",
")",
"return",
"norm_x"
] | [
968,
4
] | [
974,
21
] | python | en | ['en', 'error', 'th'] | False |
LSHSelfAttention._gather_by_expansion | (self, vectors, idxs, num_hashes) |
expand dims of idxs and vectors for all hashes and gather
|
expand dims of idxs and vectors for all hashes and gather
| def _gather_by_expansion(self, vectors, idxs, num_hashes):
"""
expand dims of idxs and vectors for all hashes and gather
"""
expanded_idxs = idxs.unsqueeze(-1).expand(-1, -1, -1, self.attention_head_size)
vectors = vectors.repeat(1, 1, num_hashes, 1)
return torch.gather(vectors, 2, expanded_idxs) | [
"def",
"_gather_by_expansion",
"(",
"self",
",",
"vectors",
",",
"idxs",
",",
"num_hashes",
")",
":",
"expanded_idxs",
"=",
"idxs",
".",
"unsqueeze",
"(",
"-",
"1",
")",
".",
"expand",
"(",
"-",
"1",
",",
"-",
"1",
",",
"-",
"1",
",",
"self",
".",
"attention_head_size",
")",
"vectors",
"=",
"vectors",
".",
"repeat",
"(",
"1",
",",
"1",
",",
"num_hashes",
",",
"1",
")",
"return",
"torch",
".",
"gather",
"(",
"vectors",
",",
"2",
",",
"expanded_idxs",
")"
] | [
976,
4
] | [
982,
54
] | python | en | ['en', 'error', 'th'] | False |
ReformerLayer._init_attention_seed | (self) |
This function sets a new seed for the attention layer to make dropout deterministic for both forward calls: 1
normal forward call and 1 forward call in backward to recalculate activations.
|
This function sets a new seed for the attention layer to make dropout deterministic for both forward calls: 1
normal forward call and 1 forward call in backward to recalculate activations.
| def _init_attention_seed(self):
"""
This function sets a new seed for the attention layer to make dropout deterministic for both forward calls: 1
normal forward call and 1 forward call in backward to recalculate activations.
"""
# randomize seeds
# use cuda generator if available
if hasattr(torch.cuda, "default_generators") and len(torch.cuda.default_generators) > 0:
# GPU
device_idx = torch.cuda.current_device()
self.attention_seed = torch.cuda.default_generators[device_idx].seed()
else:
# CPU
self.attention_seed = int(torch.seed() % sys.maxsize)
torch.manual_seed(self.attention_seed) | [
"def",
"_init_attention_seed",
"(",
"self",
")",
":",
"# randomize seeds",
"# use cuda generator if available",
"if",
"hasattr",
"(",
"torch",
".",
"cuda",
",",
"\"default_generators\"",
")",
"and",
"len",
"(",
"torch",
".",
"cuda",
".",
"default_generators",
")",
">",
"0",
":",
"# GPU",
"device_idx",
"=",
"torch",
".",
"cuda",
".",
"current_device",
"(",
")",
"self",
".",
"attention_seed",
"=",
"torch",
".",
"cuda",
".",
"default_generators",
"[",
"device_idx",
"]",
".",
"seed",
"(",
")",
"else",
":",
"# CPU",
"self",
".",
"attention_seed",
"=",
"int",
"(",
"torch",
".",
"seed",
"(",
")",
"%",
"sys",
".",
"maxsize",
")",
"torch",
".",
"manual_seed",
"(",
"self",
".",
"attention_seed",
")"
] | [
1422,
4
] | [
1438,
46
] | python | en | ['en', 'error', 'th'] | False |
ReformerLayer._init_feed_forward_seed | (self) |
This function sets a new seed for the feed forward layer to make dropout deterministic for both forward calls:
1 normal forward call and 1 forward call in backward to recalculate activations.
|
This function sets a new seed for the feed forward layer to make dropout deterministic for both forward calls:
1 normal forward call and 1 forward call in backward to recalculate activations.
| def _init_feed_forward_seed(self):
"""
This function sets a new seed for the feed forward layer to make dropout deterministic for both forward calls:
1 normal forward call and 1 forward call in backward to recalculate activations.
"""
# randomize seeds
# use cuda generator if available
if hasattr(torch.cuda, "default_generators") and len(torch.cuda.default_generators) > 0:
# GPU
device_idx = torch.cuda.current_device()
self.feed_forward_seed = torch.cuda.default_generators[device_idx].seed()
else:
# CPU
self.feed_forward_seed = int(torch.seed() % sys.maxsize)
torch.manual_seed(self.feed_forward_seed) | [
"def",
"_init_feed_forward_seed",
"(",
"self",
")",
":",
"# randomize seeds",
"# use cuda generator if available",
"if",
"hasattr",
"(",
"torch",
".",
"cuda",
",",
"\"default_generators\"",
")",
"and",
"len",
"(",
"torch",
".",
"cuda",
".",
"default_generators",
")",
">",
"0",
":",
"# GPU",
"device_idx",
"=",
"torch",
".",
"cuda",
".",
"current_device",
"(",
")",
"self",
".",
"feed_forward_seed",
"=",
"torch",
".",
"cuda",
".",
"default_generators",
"[",
"device_idx",
"]",
".",
"seed",
"(",
")",
"else",
":",
"# CPU",
"self",
".",
"feed_forward_seed",
"=",
"int",
"(",
"torch",
".",
"seed",
"(",
")",
"%",
"sys",
".",
"maxsize",
")",
"torch",
".",
"manual_seed",
"(",
"self",
".",
"feed_forward_seed",
")"
] | [
1440,
4
] | [
1455,
49
] | python | en | ['en', 'error', 'th'] | False |
ReformerPreTrainedModel._init_weights | (self, module) | Initialize the weights | Initialize the weights | def _init_weights(self, module):
""" Initialize the weights """
if isinstance(module, AxialPositionEmbeddings):
for weight in module.weights:
torch.nn.init.normal_(weight, std=self.config.axial_norm_std)
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.Linear):
# Slightly different from the TF version which uses truncated_normal for initialization
# cf https://github.com/pytorch/pytorch/pull/5617
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.LayerNorm):
module.bias.data.zero_()
module.weight.data.fill_(1.0) | [
"def",
"_init_weights",
"(",
"self",
",",
"module",
")",
":",
"if",
"isinstance",
"(",
"module",
",",
"AxialPositionEmbeddings",
")",
":",
"for",
"weight",
"in",
"module",
".",
"weights",
":",
"torch",
".",
"nn",
".",
"init",
".",
"normal_",
"(",
"weight",
",",
"std",
"=",
"self",
".",
"config",
".",
"axial_norm_std",
")",
"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",
".",
"Linear",
")",
":",
"# Slightly different from the TF version which uses truncated_normal for initialization",
"# cf https://github.com/pytorch/pytorch/pull/5617",
"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",
".",
"LayerNorm",
")",
":",
"module",
".",
"bias",
".",
"data",
".",
"zero_",
"(",
")",
"module",
".",
"weight",
".",
"data",
".",
"fill_",
"(",
"1.0",
")"
] | [
1787,
4
] | [
1804,
41
] | python | en | ['en', 'en', 'en'] | True |
async_setup_entry | (hass, config_entry, async_add_entities) | Set up the JuiceNet Sensors. | Set up the JuiceNet Sensors. | async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up the JuiceNet Sensors."""
entities = []
juicenet_data = hass.data[DOMAIN][config_entry.entry_id]
api = juicenet_data[JUICENET_API]
coordinator = juicenet_data[JUICENET_COORDINATOR]
for device in api.devices:
for sensor in SENSOR_TYPES:
entities.append(JuiceNetSensorDevice(device, sensor, coordinator))
async_add_entities(entities) | [
"async",
"def",
"async_setup_entry",
"(",
"hass",
",",
"config_entry",
",",
"async_add_entities",
")",
":",
"entities",
"=",
"[",
"]",
"juicenet_data",
"=",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"config_entry",
".",
"entry_id",
"]",
"api",
"=",
"juicenet_data",
"[",
"JUICENET_API",
"]",
"coordinator",
"=",
"juicenet_data",
"[",
"JUICENET_COORDINATOR",
"]",
"for",
"device",
"in",
"api",
".",
"devices",
":",
"for",
"sensor",
"in",
"SENSOR_TYPES",
":",
"entities",
".",
"append",
"(",
"JuiceNetSensorDevice",
"(",
"device",
",",
"sensor",
",",
"coordinator",
")",
")",
"async_add_entities",
"(",
"entities",
")"
] | [
25,
0
] | [
35,
32
] | python | en | ['en', 'sq', 'en'] | True |
JuiceNetSensorDevice.__init__ | (self, device, sensor_type, coordinator) | Initialise the sensor. | Initialise the sensor. | def __init__(self, device, sensor_type, coordinator):
"""Initialise the sensor."""
super().__init__(device, sensor_type, coordinator)
self._name = SENSOR_TYPES[sensor_type][0]
self._unit_of_measurement = SENSOR_TYPES[sensor_type][1] | [
"def",
"__init__",
"(",
"self",
",",
"device",
",",
"sensor_type",
",",
"coordinator",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"device",
",",
"sensor_type",
",",
"coordinator",
")",
"self",
".",
"_name",
"=",
"SENSOR_TYPES",
"[",
"sensor_type",
"]",
"[",
"0",
"]",
"self",
".",
"_unit_of_measurement",
"=",
"SENSOR_TYPES",
"[",
"sensor_type",
"]",
"[",
"1",
"]"
] | [
41,
4
] | [
45,
64
] | python | en | ['en', 'sm', 'en'] | True |
JuiceNetSensorDevice.name | (self) | Return the name of the device. | Return the name of the device. | def name(self):
"""Return the name of the device."""
return f"{self.device.name} {self._name}" | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"f\"{self.device.name} {self._name}\""
] | [
48,
4
] | [
50,
49
] | python | en | ['en', 'en', 'en'] | True |
JuiceNetSensorDevice.icon | (self) | Return the icon of the sensor. | Return the icon of the sensor. | def icon(self):
"""Return the icon of the sensor."""
icon = None
if self.type == "status":
status = self.device.status
if status == "standby":
icon = "mdi:power-plug-off"
elif status == "plugged":
icon = "mdi:power-plug"
elif status == "charging":
icon = "mdi:battery-positive"
elif self.type == "temperature":
icon = "mdi:thermometer"
elif self.type == "voltage":
icon = "mdi:flash"
elif self.type == "amps":
icon = "mdi:flash"
elif self.type == "watts":
icon = "mdi:flash"
elif self.type == "charge_time":
icon = "mdi:timer-outline"
elif self.type == "energy_added":
icon = "mdi:flash"
return icon | [
"def",
"icon",
"(",
"self",
")",
":",
"icon",
"=",
"None",
"if",
"self",
".",
"type",
"==",
"\"status\"",
":",
"status",
"=",
"self",
".",
"device",
".",
"status",
"if",
"status",
"==",
"\"standby\"",
":",
"icon",
"=",
"\"mdi:power-plug-off\"",
"elif",
"status",
"==",
"\"plugged\"",
":",
"icon",
"=",
"\"mdi:power-plug\"",
"elif",
"status",
"==",
"\"charging\"",
":",
"icon",
"=",
"\"mdi:battery-positive\"",
"elif",
"self",
".",
"type",
"==",
"\"temperature\"",
":",
"icon",
"=",
"\"mdi:thermometer\"",
"elif",
"self",
".",
"type",
"==",
"\"voltage\"",
":",
"icon",
"=",
"\"mdi:flash\"",
"elif",
"self",
".",
"type",
"==",
"\"amps\"",
":",
"icon",
"=",
"\"mdi:flash\"",
"elif",
"self",
".",
"type",
"==",
"\"watts\"",
":",
"icon",
"=",
"\"mdi:flash\"",
"elif",
"self",
".",
"type",
"==",
"\"charge_time\"",
":",
"icon",
"=",
"\"mdi:timer-outline\"",
"elif",
"self",
".",
"type",
"==",
"\"energy_added\"",
":",
"icon",
"=",
"\"mdi:flash\"",
"return",
"icon"
] | [
53,
4
] | [
76,
19
] | python | en | ['en', 'en', 'en'] | True |
JuiceNetSensorDevice.unit_of_measurement | (self) | Return the unit the value is expressed in. | Return the unit the value is expressed in. | def unit_of_measurement(self):
"""Return the unit the value is expressed in."""
return self._unit_of_measurement | [
"def",
"unit_of_measurement",
"(",
"self",
")",
":",
"return",
"self",
".",
"_unit_of_measurement"
] | [
79,
4
] | [
81,
40
] | python | en | ['en', 'en', 'en'] | True |
JuiceNetSensorDevice.state | (self) | Return the state. | Return the state. | def state(self):
"""Return the state."""
state = None
if self.type == "status":
state = self.device.status
elif self.type == "temperature":
state = self.device.temperature
elif self.type == "voltage":
state = self.device.voltage
elif self.type == "amps":
state = self.device.amps
elif self.type == "watts":
state = self.device.watts
elif self.type == "charge_time":
state = self.device.charge_time
elif self.type == "energy_added":
state = self.device.energy_added
else:
state = "Unknown"
return state | [
"def",
"state",
"(",
"self",
")",
":",
"state",
"=",
"None",
"if",
"self",
".",
"type",
"==",
"\"status\"",
":",
"state",
"=",
"self",
".",
"device",
".",
"status",
"elif",
"self",
".",
"type",
"==",
"\"temperature\"",
":",
"state",
"=",
"self",
".",
"device",
".",
"temperature",
"elif",
"self",
".",
"type",
"==",
"\"voltage\"",
":",
"state",
"=",
"self",
".",
"device",
".",
"voltage",
"elif",
"self",
".",
"type",
"==",
"\"amps\"",
":",
"state",
"=",
"self",
".",
"device",
".",
"amps",
"elif",
"self",
".",
"type",
"==",
"\"watts\"",
":",
"state",
"=",
"self",
".",
"device",
".",
"watts",
"elif",
"self",
".",
"type",
"==",
"\"charge_time\"",
":",
"state",
"=",
"self",
".",
"device",
".",
"charge_time",
"elif",
"self",
".",
"type",
"==",
"\"energy_added\"",
":",
"state",
"=",
"self",
".",
"device",
".",
"energy_added",
"else",
":",
"state",
"=",
"\"Unknown\"",
"return",
"state"
] | [
84,
4
] | [
103,
20
] | python | en | ['en', 'en', 'en'] | True |
apply_stop_hass | (stop_hass) | Make sure all hass are stopped. | Make sure all hass are stopped. | async def apply_stop_hass(stop_hass):
"""Make sure all hass are stopped.""" | [
"async",
"def",
"apply_stop_hass",
"(",
"stop_hass",
")",
":"
] | [
28,
0
] | [
29,
41
] | python | en | ['en', 'en', 'en'] | True |
normalize_yaml_files | (check_dict) | Remove configuration path from ['yaml_files']. | Remove configuration path from ['yaml_files']. | def normalize_yaml_files(check_dict):
"""Remove configuration path from ['yaml_files']."""
root = get_test_config_dir()
return [key.replace(root, "...") for key in sorted(check_dict["yaml_files"].keys())] | [
"def",
"normalize_yaml_files",
"(",
"check_dict",
")",
":",
"root",
"=",
"get_test_config_dir",
"(",
")",
"return",
"[",
"key",
".",
"replace",
"(",
"root",
",",
"\"...\"",
")",
"for",
"key",
"in",
"sorted",
"(",
"check_dict",
"[",
"\"yaml_files\"",
"]",
".",
"keys",
"(",
")",
")",
"]"
] | [
32,
0
] | [
35,
88
] | python | en | ['en', 'en', 'en'] | True |
test_bad_core_config | (isfile_patch, loop) | Test a bad core config setup. | Test a bad core config setup. | def test_bad_core_config(isfile_patch, loop):
"""Test a bad core config setup."""
files = {YAML_CONFIG_FILE: BAD_CORE_CONFIG}
with patch_yaml_files(files):
res = check_config.check(get_test_config_dir())
assert res["except"].keys() == {"homeassistant"}
assert res["except"]["homeassistant"][1] == {"unit_system": "bad"} | [
"def",
"test_bad_core_config",
"(",
"isfile_patch",
",",
"loop",
")",
":",
"files",
"=",
"{",
"YAML_CONFIG_FILE",
":",
"BAD_CORE_CONFIG",
"}",
"with",
"patch_yaml_files",
"(",
"files",
")",
":",
"res",
"=",
"check_config",
".",
"check",
"(",
"get_test_config_dir",
"(",
")",
")",
"assert",
"res",
"[",
"\"except\"",
"]",
".",
"keys",
"(",
")",
"==",
"{",
"\"homeassistant\"",
"}",
"assert",
"res",
"[",
"\"except\"",
"]",
"[",
"\"homeassistant\"",
"]",
"[",
"1",
"]",
"==",
"{",
"\"unit_system\"",
":",
"\"bad\"",
"}"
] | [
39,
0
] | [
45,
74
] | python | en | ['en', 'st', '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.