Add application credentials platform for nest and deprecate yaml for SDM API (#73050)

* Update the nest integration to be useable fully from the config flow

* Support discovery in nest config flow

* Remove configuration entries

* Remove unused import

* Remove dead code

* Update homeassistant/components/nest/strings.json

Co-authored-by: Martin Hjelmare <marhje52@gmail.com>

* Remove commented out code

* Use config flow for app auth reauthentication path

* Improves for re-auth for upgrading existing project and creds

* More dead code removal

* Apply suggestions from code review

Co-authored-by: Martin Hjelmare <marhje52@gmail.com>

* Remove outdated code

* Update homeassistant/components/nest/config_flow.py

Co-authored-by: Martin Hjelmare <marhje52@gmail.com>

Co-authored-by: Martin Hjelmare <marhje52@gmail.com>
This commit is contained in:
Allen Porter
2022-06-15 07:15:53 -07:00
committed by GitHub
co-authored by Martin Hjelmare
parent f8f1bfde21
commit b014d558ff
19 changed files with 856 additions and 517 deletions
+28 -6
View File
@@ -1,8 +1,10 @@
"""Common libraries for test setup."""
from __future__ import annotations
from collections.abc import Awaitable, Callable
import copy
from dataclasses import dataclass
from dataclasses import dataclass, field
import time
from typing import Any, Generator, TypeVar
@@ -13,6 +15,7 @@ from google_nest_sdm.event import EventMessage
from google_nest_sdm.event_media import CachePolicy
from google_nest_sdm.google_nest_subscriber import GoogleNestSubscriber
from homeassistant.components.application_credentials import ClientCredential
from homeassistant.components.nest import DOMAIN
from homeassistant.components.nest.const import SDM_SCOPES
@@ -73,8 +76,10 @@ def create_config_entry(token_expiration_time=None) -> MockConfigEntry:
class NestTestConfig:
"""Holder for integration configuration."""
config: dict[str, Any]
config_entry_data: dict[str, Any]
config: dict[str, Any] = field(default_factory=dict)
config_entry_data: dict[str, Any] | None = None
auth_implementation: str = WEB_AUTH_DOMAIN
credential: ClientCredential | None = None
# Exercises mode where all configuration is in configuration.yaml
@@ -86,7 +91,7 @@ TEST_CONFIG_YAML_ONLY = NestTestConfig(
},
)
TEST_CONFIGFLOW_YAML_ONLY = NestTestConfig(
config=TEST_CONFIG_YAML_ONLY.config, config_entry_data=None
config=TEST_CONFIG_YAML_ONLY.config,
)
# Exercises mode where subscriber id is created in the config flow, but
@@ -106,8 +111,24 @@ TEST_CONFIG_HYBRID = NestTestConfig(
"subscriber_id": SUBSCRIBER_ID,
},
)
TEST_CONFIGFLOW_HYBRID = NestTestConfig(
TEST_CONFIG_HYBRID.config, config_entry_data=None
TEST_CONFIGFLOW_HYBRID = NestTestConfig(TEST_CONFIG_HYBRID.config)
# Exercises mode where all configuration is from the config flow
TEST_CONFIG_APP_CREDS = NestTestConfig(
config_entry_data={
"sdm": {},
"token": create_token_entry(),
"project_id": PROJECT_ID,
"cloud_project_id": CLOUD_PROJECT_ID,
"subscriber_id": SUBSCRIBER_ID,
},
auth_implementation="imported-cred",
credential=ClientCredential(CLIENT_ID, CLIENT_SECRET),
)
TEST_CONFIGFLOW_APP_CREDS = NestTestConfig(
config=TEST_CONFIG_APP_CREDS.config,
auth_implementation="imported-cred",
credential=ClientCredential(CLIENT_ID, CLIENT_SECRET),
)
TEST_CONFIG_LEGACY = NestTestConfig(
@@ -126,6 +147,7 @@ TEST_CONFIG_LEGACY = NestTestConfig(
},
},
},
credential=None,
)
+23 -9
View File
@@ -14,6 +14,9 @@ from google_nest_sdm.auth import AbstractAuth
from google_nest_sdm.device_manager import DeviceManager
import pytest
from homeassistant.components.application_credentials import (
async_import_client_credential,
)
from homeassistant.components.nest import DOMAIN
from homeassistant.components.nest.const import CONF_SUBSCRIBER_ID
from homeassistant.core import HomeAssistant
@@ -22,9 +25,8 @@ from homeassistant.setup import async_setup_component
from .common import (
DEVICE_ID,
SUBSCRIBER_ID,
TEST_CONFIG_HYBRID,
TEST_CONFIG_APP_CREDS,
TEST_CONFIG_YAML_ONLY,
WEB_AUTH_DOMAIN,
CreateDevice,
FakeSubscriber,
NestTestConfig,
@@ -183,14 +185,14 @@ def subscriber_id() -> str:
@pytest.fixture
def auth_implementation() -> str | None:
def auth_implementation(nest_test_config: NestTestConfig) -> str | None:
"""Fixture to let tests override the auth implementation in the config entry."""
return WEB_AUTH_DOMAIN
return nest_test_config.auth_implementation
@pytest.fixture(
params=[TEST_CONFIG_YAML_ONLY, TEST_CONFIG_HYBRID],
ids=["yaml-config-only", "hybrid-config"],
params=[TEST_CONFIG_YAML_ONLY, TEST_CONFIG_APP_CREDS],
ids=["yaml-config-only", "app-creds"],
)
def nest_test_config(request) -> NestTestConfig:
"""Fixture that sets up the configuration used for the test."""
@@ -230,6 +232,20 @@ def config_entry(
return MockConfigEntry(domain=DOMAIN, data=data)
@pytest.fixture(autouse=True)
async def credential(hass: HomeAssistant, nest_test_config: NestTestConfig) -> None:
"""Fixture that provides the ClientCredential for the test if any."""
if not nest_test_config.credential:
return
assert await async_setup_component(hass, "application_credentials", {})
await async_import_client_credential(
hass,
DOMAIN,
nest_test_config.credential,
nest_test_config.auth_implementation,
)
@pytest.fixture
async def setup_base_platform(
hass: HomeAssistant,
@@ -240,9 +256,7 @@ async def setup_base_platform(
"""Fixture to setup the integration platform."""
if config_entry:
config_entry.add_to_hass(hass)
with patch(
"homeassistant.helpers.config_entry_oauth2_flow.async_get_config_entry_implementation"
), patch("homeassistant.components.nest.PLATFORMS", platforms):
with patch("homeassistant.components.nest.PLATFORMS", platforms):
async def _setup_func() -> bool:
assert await async_setup_component(hass, DOMAIN, config)
+5
View File
@@ -11,6 +11,8 @@ The tests below exercise both cases during integration setup.
import time
from unittest.mock import patch
import pytest
from homeassistant.components.nest import DOMAIN
from homeassistant.components.nest.const import API_URL, OAUTH2_TOKEN, SDM_SCOPES
from homeassistant.setup import async_setup_component
@@ -23,6 +25,7 @@ from .common import (
FAKE_REFRESH_TOKEN,
FAKE_TOKEN,
PROJECT_ID,
TEST_CONFIGFLOW_YAML_ONLY,
create_config_entry,
)
@@ -35,6 +38,7 @@ async def async_setup_sdm(hass):
await hass.async_block_till_done()
@pytest.mark.parametrize("nest_test_config", [TEST_CONFIGFLOW_YAML_ONLY])
async def test_auth(hass, aioclient_mock):
"""Exercise authentication library creates valid credentials."""
@@ -84,6 +88,7 @@ async def test_auth(hass, aioclient_mock):
assert creds.scopes == SDM_SCOPES
@pytest.mark.parametrize("nest_test_config", [TEST_CONFIGFLOW_YAML_ONLY])
async def test_auth_expired_token(hass, aioclient_mock):
"""Verify behavior of an expired token."""
@@ -13,15 +13,6 @@ from tests.common import MockConfigEntry
CONFIG = TEST_CONFIG_LEGACY.config
async def test_abort_if_no_implementation_registered(hass):
"""Test we abort if no implementation is registered."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT
assert result["reason"] == "missing_configuration"
async def test_abort_if_single_instance_allowed(hass):
"""Test we abort if Nest is already setup."""
existing_entry = MockConfigEntry(domain=DOMAIN, data={})
+392 -266
View File
@@ -1,5 +1,8 @@
"""Test the Google Nest Device Access config flow."""
from __future__ import annotations
from typing import Any
from unittest.mock import patch
from google_nest_sdm.exceptions import (
@@ -12,23 +15,31 @@ import pytest
from homeassistant import config_entries
from homeassistant.components import dhcp
from homeassistant.components.application_credentials import (
ClientCredential,
async_import_client_credential,
)
from homeassistant.components.nest.const import DOMAIN, OAUTH2_AUTHORIZE, OAUTH2_TOKEN
from homeassistant.config_entries import ConfigEntry
from homeassistant.data_entry_flow import FlowResult
from homeassistant.helpers import config_entry_oauth2_flow
from .common import (
APP_AUTH_DOMAIN,
CLIENT_ID,
CLIENT_SECRET,
CLOUD_PROJECT_ID,
FAKE_TOKEN,
PROJECT_ID,
SUBSCRIBER_ID,
TEST_CONFIG_APP_CREDS,
TEST_CONFIG_HYBRID,
TEST_CONFIG_YAML_ONLY,
TEST_CONFIGFLOW_HYBRID,
TEST_CONFIGFLOW_APP_CREDS,
TEST_CONFIGFLOW_YAML_ONLY,
WEB_AUTH_DOMAIN,
MockConfigEntry,
NestTestConfig,
)
WEB_REDIRECT_URL = "https://example.com/auth/external/callback"
@@ -49,17 +60,35 @@ class OAuthFixture:
self.hass_client = hass_client_no_auth
self.aioclient_mock = aioclient_mock
async def async_pick_flow(self, result: dict, auth_domain: str) -> dict:
"""Invoke flow to puth the auth type to use for this flow."""
assert result["type"] == "form"
assert result["step_id"] == "pick_implementation"
async def async_app_creds_flow(
self,
result: dict,
cloud_project_id: str = CLOUD_PROJECT_ID,
project_id: str = PROJECT_ID,
) -> None:
"""Invoke multiple steps in the app credentials based flow."""
assert result.get("type") == "form"
assert result.get("step_id") == "cloud_project"
return await self.async_configure(result, {"implementation": auth_domain})
result = await self.async_configure(
result, {"cloud_project_id": CLOUD_PROJECT_ID}
)
assert result.get("type") == "form"
assert result.get("step_id") == "device_project"
async def async_oauth_web_flow(self, result: dict) -> None:
result = await self.async_configure(result, {"project_id": PROJECT_ID})
await self.async_oauth_web_flow(result)
async def async_oauth_web_flow(self, result: dict, project_id=PROJECT_ID) -> None:
"""Invoke the oauth flow for Web Auth with fake responses."""
state = self.create_state(result, WEB_REDIRECT_URL)
assert result["url"] == self.authorize_url(state, WEB_REDIRECT_URL)
assert result["type"] == "external"
assert result["url"] == self.authorize_url(
state,
WEB_REDIRECT_URL,
CLIENT_ID,
project_id,
)
# Simulate user redirect back with auth code
client = await self.hass_client()
@@ -69,38 +98,26 @@ class OAuthFixture:
await self.async_mock_refresh(result)
async def async_oauth_app_flow(self, result: dict) -> None:
"""Invoke the oauth flow for Installed Auth with fake responses."""
# Render form with a link to get an auth token
assert result["type"] == "form"
assert result["step_id"] == "auth"
assert "description_placeholders" in result
assert "url" in result["description_placeholders"]
state = self.create_state(result, APP_REDIRECT_URL)
assert result["description_placeholders"]["url"] == self.authorize_url(
state, APP_REDIRECT_URL
)
# Simulate user entering auth token in form
await self.async_mock_refresh(result, {"code": "abcd"})
async def async_reauth(self, old_data: dict) -> dict:
async def async_reauth(self, config_entry: ConfigEntry) -> dict:
"""Initiate a reuath flow."""
result = await self.hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_REAUTH}, data=old_data
)
assert result["type"] == "form"
assert result["step_id"] == "reauth_confirm"
config_entry.async_start_reauth(self.hass)
await self.hass.async_block_till_done()
# Advance through the reauth flow
flows = self.hass.config_entries.flow.async_progress()
assert len(flows) == 1
assert flows[0]["step_id"] == "reauth_confirm"
result = self.async_progress()
assert result["step_id"] == "reauth_confirm"
# Advance to the oauth flow
return await self.hass.config_entries.flow.async_configure(
flows[0]["flow_id"], {}
result["flow_id"], {}
)
def async_progress(self) -> FlowResult:
"""Return the current step of the config flow."""
flows = self.hass.config_entries.flow.async_progress()
assert len(flows) == 1
return flows[0]
def create_state(self, result: dict, redirect_url: str) -> str:
"""Create state object based on redirect url."""
return config_entry_oauth2_flow._encode_jwt(
@@ -111,11 +128,13 @@ class OAuthFixture:
},
)
def authorize_url(self, state: str, redirect_url: str) -> str:
def authorize_url(
self, state: str, redirect_url: str, client_id: str, project_id: str
) -> str:
"""Generate the expected authorization url."""
oauth_authorize = OAUTH2_AUTHORIZE.format(project_id=PROJECT_ID)
oauth_authorize = OAUTH2_AUTHORIZE.format(project_id=project_id)
return (
f"{oauth_authorize}?response_type=code&client_id={CLIENT_ID}"
f"{oauth_authorize}?response_type=code&client_id={client_id}"
f"&redirect_uri={redirect_url}"
f"&state={state}&scope=https://www.googleapis.com/auth/sdm.service"
"+https://www.googleapis.com/auth/pubsub"
@@ -146,13 +165,16 @@ class OAuthFixture:
await self.hass.async_block_till_done()
return self.get_config_entry()
async def async_configure(self, result: dict, user_input: dict) -> dict:
async def async_configure(
self, result: dict[str, Any], user_input: dict[str, Any]
) -> dict:
"""Advance to the next step in the config flow."""
return await self.hass.config_entries.flow.async_configure(
result["flow_id"], user_input
result["flow_id"],
user_input,
)
async def async_pubsub_flow(self, result: dict, cloud_project_id="") -> ConfigEntry:
async def async_pubsub_flow(self, result: dict, cloud_project_id="") -> None:
"""Verify the pubsub creation step."""
# Render form with a link to get an auth token
assert result["type"] == "form"
@@ -164,7 +186,7 @@ class OAuthFixture:
def get_config_entry(self) -> ConfigEntry:
"""Get the config entry."""
entries = self.hass.config_entries.async_entries(DOMAIN)
assert len(entries) == 1
assert len(entries) >= 1
return entries[0]
@@ -174,42 +196,209 @@ async def oauth(hass, hass_client_no_auth, aioclient_mock, current_request_with_
return OAuthFixture(hass, hass_client_no_auth, aioclient_mock)
@pytest.mark.parametrize("nest_test_config", [TEST_CONFIGFLOW_YAML_ONLY])
async def test_web_full_flow(hass, oauth, setup_platform):
@pytest.mark.parametrize("nest_test_config", [TEST_CONFIGFLOW_APP_CREDS])
async def test_app_credentials(hass, oauth, subscriber, setup_platform):
"""Check full flow."""
await setup_platform()
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
await oauth.async_app_creds_flow(result)
result = await oauth.async_pick_flow(result, WEB_AUTH_DOMAIN)
await oauth.async_oauth_web_flow(result)
entry = await oauth.async_finish_setup(result)
assert entry.title == "OAuth for Web"
assert "token" in entry.data
entry.data["token"].pop("expires_at")
assert entry.unique_id == DOMAIN
assert entry.data["token"] == {
"refresh_token": "mock-refresh-token",
"access_token": "mock-access-token",
"type": "Bearer",
"expires_in": 60,
data = dict(entry.data)
assert "token" in data
data["token"].pop("expires_in")
data["token"].pop("expires_at")
assert "subscriber_id" in data
assert f"projects/{CLOUD_PROJECT_ID}/subscriptions" in data["subscriber_id"]
data.pop("subscriber_id")
assert data == {
"sdm": {},
"auth_implementation": "imported-cred",
"cloud_project_id": CLOUD_PROJECT_ID,
"project_id": PROJECT_ID,
"token": {
"refresh_token": "mock-refresh-token",
"access_token": "mock-access-token",
"type": "Bearer",
},
}
# Subscriber from configuration.yaml
assert "subscriber_id" not in entry.data
@pytest.mark.parametrize("nest_test_config", [TEST_CONFIGFLOW_APP_CREDS])
async def test_config_flow_restart(hass, oauth, subscriber, setup_platform):
"""Check with auth implementation is re-initialized when aborting the flow."""
await setup_platform()
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
await oauth.async_app_creds_flow(result)
# At this point, we should have a valid auth implementation configured.
# Simulate aborting the flow and starting over to ensure we get prompted
# again to configure everything.
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result.get("type") == "form"
assert result.get("step_id") == "cloud_project"
# Change the values to show they are reflected below
result = await oauth.async_configure(
result, {"cloud_project_id": "new-cloud-project-id"}
)
assert result.get("type") == "form"
assert result.get("step_id") == "device_project"
result = await oauth.async_configure(result, {"project_id": "new-project-id"})
await oauth.async_oauth_web_flow(result, "new-project-id")
entry = await oauth.async_finish_setup(result, {"code": "1234"})
data = dict(entry.data)
assert "token" in data
data["token"].pop("expires_in")
data["token"].pop("expires_at")
assert "subscriber_id" in data
assert "projects/new-cloud-project-id/subscriptions" in data["subscriber_id"]
data.pop("subscriber_id")
assert data == {
"sdm": {},
"auth_implementation": "imported-cred",
"cloud_project_id": "new-cloud-project-id",
"project_id": "new-project-id",
"token": {
"refresh_token": "mock-refresh-token",
"access_token": "mock-access-token",
"type": "Bearer",
},
}
@pytest.mark.parametrize("nest_test_config", [TEST_CONFIGFLOW_APP_CREDS])
async def test_config_flow_wrong_project_id(hass, oauth, subscriber, setup_platform):
"""Check the case where the wrong project ids are entered."""
await setup_platform()
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result.get("type") == "form"
assert result.get("step_id") == "cloud_project"
result = await oauth.async_configure(result, {"cloud_project_id": CLOUD_PROJECT_ID})
assert result.get("type") == "form"
assert result.get("step_id") == "device_project"
# Enter the cloud project id instead of device access project id (really we just check
# they are the same value which is never correct)
result = await oauth.async_configure(result, {"project_id": CLOUD_PROJECT_ID})
assert result["type"] == "form"
assert "errors" in result
assert "project_id" in result["errors"]
assert result["errors"]["project_id"] == "wrong_project_id"
# Fix with a correct value and complete the rest of the flow
result = await oauth.async_configure(result, {"project_id": PROJECT_ID})
await oauth.async_oauth_web_flow(result)
await hass.async_block_till_done()
entry = await oauth.async_finish_setup(result, {"code": "1234"})
data = dict(entry.data)
assert "token" in data
data["token"].pop("expires_in")
data["token"].pop("expires_at")
assert "subscriber_id" in data
assert f"projects/{CLOUD_PROJECT_ID}/subscriptions" in data["subscriber_id"]
data.pop("subscriber_id")
assert data == {
"sdm": {},
"auth_implementation": "imported-cred",
"cloud_project_id": CLOUD_PROJECT_ID,
"project_id": PROJECT_ID,
"token": {
"refresh_token": "mock-refresh-token",
"access_token": "mock-access-token",
"type": "Bearer",
},
}
@pytest.mark.parametrize("nest_test_config", [TEST_CONFIGFLOW_APP_CREDS])
async def test_config_flow_pubsub_configuration_error(
hass,
oauth,
setup_platform,
mock_subscriber,
):
"""Check full flow fails with configuration error."""
await setup_platform()
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
await oauth.async_app_creds_flow(result)
mock_subscriber.create_subscription.side_effect = ConfigurationException
result = await oauth.async_configure(result, {"code": "1234"})
assert result["type"] == "form"
assert "errors" in result
assert "cloud_project_id" in result["errors"]
assert result["errors"]["cloud_project_id"] == "bad_project_id"
@pytest.mark.parametrize("nest_test_config", [TEST_CONFIGFLOW_APP_CREDS])
async def test_config_flow_pubsub_subscriber_error(
hass, oauth, setup_platform, mock_subscriber
):
"""Check full flow with a subscriber error."""
await setup_platform()
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
await oauth.async_app_creds_flow(result)
mock_subscriber.create_subscription.side_effect = SubscriberException()
result = await oauth.async_configure(result, {"code": "1234"})
assert result["type"] == "form"
assert "errors" in result
assert "cloud_project_id" in result["errors"]
assert result["errors"]["cloud_project_id"] == "subscriber_error"
@pytest.mark.parametrize("nest_test_config", [TEST_CONFIGFLOW_YAML_ONLY])
async def test_config_yaml_ignored(hass, oauth, setup_platform):
"""Check full flow."""
await setup_platform()
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
await hass.async_block_till_done()
assert result["type"] == "form"
assert result["step_id"] == "create_cloud_project"
result = await oauth.async_configure(result, {})
assert result.get("type") == "abort"
assert result.get("reason") == "missing_credentials"
@pytest.mark.parametrize("nest_test_config", [TEST_CONFIG_YAML_ONLY])
async def test_web_reauth(hass, oauth, setup_platform, config_entry):
"""Test Nest reauthentication."""
await setup_platform()
assert config_entry.data["token"].get("access_token") == FAKE_TOKEN
result = await oauth.async_reauth(config_entry.data)
orig_subscriber_id = config_entry.data.get("subscriber_id")
result = await oauth.async_reauth(config_entry)
await oauth.async_oauth_web_flow(result)
entry = await oauth.async_finish_setup(result)
@@ -223,7 +412,7 @@ async def test_web_reauth(hass, oauth, setup_platform, config_entry):
"expires_in": 60,
}
assert entry.data["auth_implementation"] == WEB_AUTH_DOMAIN
assert "subscriber_id" not in entry.data # not updated
assert entry.data.get("subscriber_id") == orig_subscriber_id # Not updated
async def test_single_config_entry(hass, setup_platform):
@@ -237,7 +426,9 @@ async def test_single_config_entry(hass, setup_platform):
assert result["reason"] == "single_instance_allowed"
async def test_unexpected_existing_config_entries(hass, oauth, setup_platform):
async def test_unexpected_existing_config_entries(
hass, oauth, setup_platform, config_entry
):
"""Test Nest reauthentication with multiple existing config entries."""
# Note that this case will not happen in the future since only a single
# instance is now allowed, but this may have been allowed in the past.
@@ -246,23 +437,29 @@ async def test_unexpected_existing_config_entries(hass, oauth, setup_platform):
await setup_platform()
old_entry = MockConfigEntry(
domain=DOMAIN, data={"auth_implementation": WEB_AUTH_DOMAIN, "sdm": {}}
domain=DOMAIN,
data={
**config_entry.data,
"extra_data": True,
},
)
old_entry.add_to_hass(hass)
entries = hass.config_entries.async_entries(DOMAIN)
assert len(entries) == 2
orig_subscriber_id = config_entry.data.get("subscriber_id")
# Invoke the reauth flow
result = await oauth.async_reauth(old_entry.data)
result = await oauth.async_reauth(config_entry)
await oauth.async_oauth_web_flow(result)
await oauth.async_finish_setup(result)
# Only a single entry now exists, and the other was cleaned up
# Only reauth entry was updated, the other entry is preserved
entries = hass.config_entries.async_entries(DOMAIN)
assert len(entries) == 1
assert len(entries) == 2
entry = entries[0]
assert entry.unique_id == DOMAIN
entry.data["token"].pop("expires_at")
@@ -272,7 +469,14 @@ async def test_unexpected_existing_config_entries(hass, oauth, setup_platform):
"type": "Bearer",
"expires_in": 60,
}
assert "subscriber_id" not in entry.data # not updated
assert entry.data.get("subscriber_id") == orig_subscriber_id # Not updated
assert not entry.data.get("extra_data")
# Other entry was not refreshed
entry = entries[1]
entry.data["token"].pop("expires_at")
assert entry.data.get("token", {}).get("access_token") == "some-token"
assert entry.data.get("extra_data")
async def test_reauth_missing_config_entry(hass, setup_platform):
@@ -287,42 +491,51 @@ async def test_reauth_missing_config_entry(hass, setup_platform):
assert result["reason"] == "missing_configuration"
@pytest.mark.parametrize("nest_test_config", [TEST_CONFIGFLOW_YAML_ONLY])
async def test_app_full_flow(hass, oauth, setup_platform):
"""Check full flow."""
await setup_platform()
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
result = await oauth.async_pick_flow(result, APP_AUTH_DOMAIN)
await oauth.async_oauth_app_flow(result)
entry = await oauth.async_finish_setup(result, {"code": "1234"})
assert entry.title == "OAuth for Apps"
assert "token" in entry.data
entry.data["token"].pop("expires_at")
assert entry.unique_id == DOMAIN
assert entry.data["token"] == {
"refresh_token": "mock-refresh-token",
"access_token": "mock-access-token",
"type": "Bearer",
"expires_in": 60,
}
# Subscriber from configuration.yaml
assert "subscriber_id" not in entry.data
@pytest.mark.parametrize(
"nest_test_config,auth_implementation", [(TEST_CONFIG_YAML_ONLY, APP_AUTH_DOMAIN)]
"nest_test_config,auth_implementation", [(TEST_CONFIG_HYBRID, APP_AUTH_DOMAIN)]
)
async def test_app_reauth(hass, oauth, setup_platform, config_entry):
"""Test Nest reauthentication for Installed App Auth."""
async def test_app_auth_yaml_reauth(hass, oauth, setup_platform, config_entry):
"""Test reauth for deprecated app auth credentails upgrade instructions."""
await setup_platform()
result = await oauth.async_reauth(config_entry.data)
await oauth.async_oauth_app_flow(result)
orig_subscriber_id = config_entry.data.get("subscriber_id")
assert config_entry.data["auth_implementation"] == APP_AUTH_DOMAIN
result = oauth.async_progress()
assert result.get("step_id") == "reauth_confirm"
result = await oauth.async_configure(result, {})
assert result.get("type") == "form"
assert result.get("step_id") == "auth_upgrade"
result = await oauth.async_configure(result, {})
assert result.get("type") == "abort"
assert result.get("reason") == "missing_credentials"
await hass.async_block_till_done()
# Config flow is aborted, but new one created back in re-auth state waiting for user
# to create application credentials
flows = hass.config_entries.flow.async_progress()
assert len(flows) == 1
# Emulate user entering credentials (different from configuration.yaml creds)
await async_import_client_credential(
hass,
DOMAIN,
ClientCredential(CLIENT_ID, CLIENT_SECRET),
)
# Config flow is placed back into a reuath state
result = oauth.async_progress()
assert result.get("step_id") == "reauth_confirm"
result = await oauth.async_configure(result, {})
assert result.get("type") == "form"
assert result.get("step_id") == "device_project_upgrade"
# Frontend sends user back through the config flow again
result = await oauth.async_configure(result, {})
await oauth.async_oauth_web_flow(result)
# Verify existing tokens are replaced
entry = await oauth.async_finish_setup(result, {"code": "1234"})
@@ -334,29 +547,28 @@ async def test_app_reauth(hass, oauth, setup_platform, config_entry):
"type": "Bearer",
"expires_in": 60,
}
assert entry.data["auth_implementation"] == APP_AUTH_DOMAIN
assert "subscriber_id" not in entry.data # not updated
assert entry.data["auth_implementation"] == DOMAIN
assert entry.data.get("subscriber_id") == orig_subscriber_id # Not updated
# Existing entry is updated
assert config_entry.data["auth_implementation"] == DOMAIN
@pytest.mark.parametrize("nest_test_config", [TEST_CONFIGFLOW_HYBRID])
async def test_pubsub_subscription(hass, oauth, subscriber, setup_platform):
"""Check flow that creates a pub/sub subscription."""
@pytest.mark.parametrize(
"nest_test_config,auth_implementation", [(TEST_CONFIG_YAML_ONLY, WEB_AUTH_DOMAIN)]
)
async def test_web_auth_yaml_reauth(hass, oauth, setup_platform, config_entry):
"""Test Nest reauthentication for Installed App Auth."""
await setup_platform()
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
result = await oauth.async_pick_flow(result, APP_AUTH_DOMAIN)
await oauth.async_oauth_app_flow(result)
orig_subscriber_id = config_entry.data.get("subscriber_id")
result = await oauth.async_configure(result, {"code": "1234"})
await oauth.async_pubsub_flow(result)
entry = await oauth.async_finish_setup(
result, {"cloud_project_id": CLOUD_PROJECT_ID}
)
result = await oauth.async_reauth(config_entry)
await oauth.async_oauth_web_flow(result)
assert entry.title == "OAuth for Apps"
assert "token" in entry.data
# Verify existing tokens are replaced
entry = await oauth.async_finish_setup(result, {"code": "1234"})
entry.data["token"].pop("expires_at")
assert entry.unique_id == DOMAIN
assert entry.data["token"] == {
@@ -365,11 +577,11 @@ async def test_pubsub_subscription(hass, oauth, subscriber, setup_platform):
"type": "Bearer",
"expires_in": 60,
}
assert "subscriber_id" in entry.data
assert entry.data["cloud_project_id"] == CLOUD_PROJECT_ID
assert entry.data["auth_implementation"] == WEB_AUTH_DOMAIN
assert entry.data.get("subscriber_id") == orig_subscriber_id # Not updated
@pytest.mark.parametrize("nest_test_config", [TEST_CONFIGFLOW_HYBRID])
@pytest.mark.parametrize("nest_test_config", [TEST_CONFIGFLOW_APP_CREDS])
async def test_pubsub_subscription_strip_whitespace(
hass, oauth, subscriber, setup_platform
):
@@ -379,16 +591,12 @@ async def test_pubsub_subscription_strip_whitespace(
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
result = await oauth.async_pick_flow(result, APP_AUTH_DOMAIN)
await oauth.async_oauth_app_flow(result)
result = await oauth.async_configure(result, {"code": "1234"})
await oauth.async_pubsub_flow(result)
entry = await oauth.async_finish_setup(
result, {"cloud_project_id": " " + CLOUD_PROJECT_ID + " "}
await oauth.async_app_creds_flow(
result, cloud_project_id=" " + CLOUD_PROJECT_ID + " "
)
entry = await oauth.async_finish_setup(result, {"code": "1234"})
assert entry.title == "OAuth for Apps"
assert entry.title == "Import from configuration.yaml"
assert "token" in entry.data
entry.data["token"].pop("expires_at")
assert entry.unique_id == DOMAIN
@@ -402,7 +610,7 @@ async def test_pubsub_subscription_strip_whitespace(
assert entry.data["cloud_project_id"] == CLOUD_PROJECT_ID
@pytest.mark.parametrize("nest_test_config", [TEST_CONFIGFLOW_HYBRID])
@pytest.mark.parametrize("nest_test_config", [TEST_CONFIGFLOW_APP_CREDS])
async def test_pubsub_subscription_auth_failure(
hass, oauth, setup_platform, mock_subscriber
):
@@ -412,102 +620,25 @@ async def test_pubsub_subscription_auth_failure(
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
result = await oauth.async_pick_flow(result, APP_AUTH_DOMAIN)
await oauth.async_oauth_app_flow(result)
result = await oauth.async_configure(result, {"code": "1234"})
mock_subscriber.create_subscription.side_effect = AuthException()
await oauth.async_pubsub_flow(result)
result = await oauth.async_configure(result, {"cloud_project_id": CLOUD_PROJECT_ID})
await oauth.async_app_creds_flow(result)
result = await oauth.async_configure(result, {"code": "1234"})
assert result["type"] == "abort"
assert result["reason"] == "invalid_access_token"
@pytest.mark.parametrize("nest_test_config", [TEST_CONFIGFLOW_HYBRID])
async def test_pubsub_subscription_failure(
hass, oauth, setup_platform, mock_subscriber
):
"""Check flow that creates a pub/sub subscription."""
await setup_platform()
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
result = await oauth.async_pick_flow(result, APP_AUTH_DOMAIN)
await oauth.async_oauth_app_flow(result)
result = await oauth.async_configure(result, {"code": "1234"})
await oauth.async_pubsub_flow(result)
mock_subscriber.create_subscription.side_effect = SubscriberException()
result = await oauth.async_configure(result, {"cloud_project_id": CLOUD_PROJECT_ID})
assert result["type"] == "form"
assert "errors" in result
assert "cloud_project_id" in result["errors"]
assert result["errors"]["cloud_project_id"] == "subscriber_error"
@pytest.mark.parametrize("nest_test_config", [TEST_CONFIGFLOW_HYBRID])
async def test_pubsub_subscription_configuration_failure(
hass, oauth, setup_platform, mock_subscriber
):
"""Check flow that creates a pub/sub subscription."""
await setup_platform()
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
result = await oauth.async_pick_flow(result, APP_AUTH_DOMAIN)
await oauth.async_oauth_app_flow(result)
result = await oauth.async_configure(result, {"code": "1234"})
await oauth.async_pubsub_flow(result)
mock_subscriber.create_subscription.side_effect = ConfigurationException()
result = await oauth.async_configure(result, {"cloud_project_id": CLOUD_PROJECT_ID})
assert result["type"] == "form"
assert "errors" in result
assert "cloud_project_id" in result["errors"]
assert result["errors"]["cloud_project_id"] == "bad_project_id"
@pytest.mark.parametrize("nest_test_config", [TEST_CONFIGFLOW_HYBRID])
async def test_pubsub_with_wrong_project_id(hass, oauth, setup_platform):
"""Test a possible common misconfiguration mixing up project ids."""
await setup_platform()
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
result = await oauth.async_pick_flow(result, APP_AUTH_DOMAIN)
await oauth.async_oauth_app_flow(result)
result = await oauth.async_configure(result, {"code": "1234"})
await oauth.async_pubsub_flow(result)
result = await oauth.async_configure(
result, {"cloud_project_id": PROJECT_ID} # SDM project id
)
await hass.async_block_till_done()
assert result["type"] == "form"
assert "errors" in result
assert "cloud_project_id" in result["errors"]
assert result["errors"]["cloud_project_id"] == "wrong_project_id"
@pytest.mark.parametrize(
"nest_test_config,auth_implementation", [(TEST_CONFIG_HYBRID, APP_AUTH_DOMAIN)]
)
@pytest.mark.parametrize("nest_test_config", [TEST_CONFIG_APP_CREDS])
async def test_pubsub_subscriber_config_entry_reauth(
hass, oauth, setup_platform, subscriber, config_entry
hass, oauth, setup_platform, subscriber, config_entry, auth_implementation
):
"""Test the pubsub subscriber id is preserved during reauth."""
await setup_platform()
result = await oauth.async_reauth(config_entry.data)
await oauth.async_oauth_app_flow(result)
result = await oauth.async_reauth(config_entry)
await oauth.async_oauth_web_flow(result)
# Entering an updated access token refreshs the config entry.
entry = await oauth.async_finish_setup(result, {"code": "1234"})
@@ -519,12 +650,12 @@ async def test_pubsub_subscriber_config_entry_reauth(
"type": "Bearer",
"expires_in": 60,
}
assert entry.data["auth_implementation"] == APP_AUTH_DOMAIN
assert entry.data["auth_implementation"] == auth_implementation
assert entry.data["subscriber_id"] == SUBSCRIBER_ID
assert entry.data["cloud_project_id"] == CLOUD_PROJECT_ID
@pytest.mark.parametrize("nest_test_config", [TEST_CONFIGFLOW_HYBRID])
@pytest.mark.parametrize("nest_test_config", [TEST_CONFIGFLOW_APP_CREDS])
async def test_config_entry_title_from_home(hass, oauth, setup_platform, subscriber):
"""Test that the Google Home name is used for the config entry title."""
@@ -547,22 +678,16 @@ async def test_config_entry_title_from_home(hass, oauth, setup_platform, subscri
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
result = await oauth.async_pick_flow(result, APP_AUTH_DOMAIN)
await oauth.async_oauth_app_flow(result)
result = await oauth.async_configure(result, {"code": "1234"})
await oauth.async_pubsub_flow(result)
entry = await oauth.async_finish_setup(
result, {"cloud_project_id": CLOUD_PROJECT_ID}
)
await oauth.async_app_creds_flow(result)
entry = await oauth.async_finish_setup(result, {"code": "1234"})
assert entry.title == "Example Home"
assert "token" in entry.data
assert "subscriber_id" in entry.data
assert entry.data["cloud_project_id"] == CLOUD_PROJECT_ID
@pytest.mark.parametrize("nest_test_config", [TEST_CONFIGFLOW_HYBRID])
@pytest.mark.parametrize("nest_test_config", [TEST_CONFIGFLOW_APP_CREDS])
async def test_config_entry_title_multiple_homes(
hass, oauth, setup_platform, subscriber
):
@@ -599,18 +724,13 @@ async def test_config_entry_title_multiple_homes(
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
result = await oauth.async_pick_flow(result, APP_AUTH_DOMAIN)
await oauth.async_oauth_app_flow(result)
await oauth.async_app_creds_flow(result)
result = await oauth.async_configure(result, {"code": "1234"})
await oauth.async_pubsub_flow(result)
entry = await oauth.async_finish_setup(
result, {"cloud_project_id": CLOUD_PROJECT_ID}
)
entry = await oauth.async_finish_setup(result, {"code": "1234"})
assert entry.title == "Example Home #1, Example Home #2"
@pytest.mark.parametrize("nest_test_config", [TEST_CONFIGFLOW_HYBRID])
@pytest.mark.parametrize("nest_test_config", [TEST_CONFIGFLOW_APP_CREDS])
async def test_title_failure_fallback(hass, oauth, setup_platform, mock_subscriber):
"""Test exception handling when determining the structure names."""
await setup_platform()
@@ -618,24 +738,17 @@ async def test_title_failure_fallback(hass, oauth, setup_platform, mock_subscrib
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
result = await oauth.async_pick_flow(result, APP_AUTH_DOMAIN)
await oauth.async_oauth_app_flow(result)
await oauth.async_app_creds_flow(result)
mock_subscriber.async_get_device_manager.side_effect = AuthException()
result = await oauth.async_configure(result, {"code": "1234"})
await oauth.async_pubsub_flow(result)
entry = await oauth.async_finish_setup(
result, {"cloud_project_id": CLOUD_PROJECT_ID}
)
assert entry.title == "OAuth for Apps"
entry = await oauth.async_finish_setup(result, {"code": "1234"})
assert entry.title == "Import from configuration.yaml"
assert "token" in entry.data
assert "subscriber_id" in entry.data
assert entry.data["cloud_project_id"] == CLOUD_PROJECT_ID
@pytest.mark.parametrize("nest_test_config", [TEST_CONFIGFLOW_HYBRID])
@pytest.mark.parametrize("nest_test_config", [TEST_CONFIGFLOW_APP_CREDS])
async def test_structure_missing_trait(hass, oauth, setup_platform, subscriber):
"""Test handling the case where a structure has no name set."""
@@ -655,34 +768,33 @@ async def test_structure_missing_trait(hass, oauth, setup_platform, subscriber):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
result = await oauth.async_pick_flow(result, APP_AUTH_DOMAIN)
await oauth.async_oauth_app_flow(result)
result = await oauth.async_configure(result, {"code": "1234"})
await oauth.async_pubsub_flow(result)
entry = await oauth.async_finish_setup(
result, {"cloud_project_id": CLOUD_PROJECT_ID}
)
await oauth.async_app_creds_flow(result)
entry = await oauth.async_finish_setup(result, {"code": "1234"})
# Fallback to default name
assert entry.title == "OAuth for Apps"
assert entry.title == "Import from configuration.yaml"
async def test_dhcp_discovery_without_config(hass, oauth):
"""Exercise discovery dhcp with no config present (can't run)."""
@pytest.mark.parametrize("nest_test_config", [NestTestConfig()])
async def test_dhcp_discovery(hass, oauth, subscriber):
"""Exercise discovery dhcp starts the config flow and kicks user to frontend creds flow."""
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_DHCP},
data=FAKE_DHCP_DATA,
)
await hass.async_block_till_done()
assert result["type"] == "abort"
assert result["reason"] == "missing_configuration"
assert result["type"] == "form"
assert result["step_id"] == "create_cloud_project"
result = await oauth.async_configure(result, {})
assert result.get("type") == "abort"
assert result.get("reason") == "missing_credentials"
@pytest.mark.parametrize("nest_test_config", [TEST_CONFIGFLOW_YAML_ONLY])
async def test_dhcp_discovery(hass, oauth, setup_platform):
"""Discover via dhcp when config is present."""
@pytest.mark.parametrize("nest_test_config", [TEST_CONFIGFLOW_APP_CREDS])
async def test_dhcp_discovery_with_creds(hass, oauth, subscriber, setup_platform):
"""Exercise discovery dhcp with no config present (can't run)."""
await setup_platform()
result = await hass.config_entries.flow.async_init(
@@ -691,19 +803,33 @@ async def test_dhcp_discovery(hass, oauth, setup_platform):
data=FAKE_DHCP_DATA,
)
await hass.async_block_till_done()
assert result.get("type") == "form"
assert result.get("step_id") == "cloud_project"
# DHCP discovery invokes the config flow
result = await oauth.async_pick_flow(result, WEB_AUTH_DOMAIN)
result = await oauth.async_configure(result, {"cloud_project_id": CLOUD_PROJECT_ID})
assert result.get("type") == "form"
assert result.get("step_id") == "device_project"
result = await oauth.async_configure(result, {"project_id": PROJECT_ID})
await oauth.async_oauth_web_flow(result)
entry = await oauth.async_finish_setup(result)
assert entry.title == "OAuth for Web"
# Discovery does not run once configured
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_DHCP},
data=FAKE_DHCP_DATA,
)
entry = await oauth.async_finish_setup(result, {"code": "1234"})
await hass.async_block_till_done()
assert result["type"] == "abort"
assert result["reason"] == "already_configured"
data = dict(entry.data)
assert "token" in data
data["token"].pop("expires_in")
data["token"].pop("expires_at")
assert "subscriber_id" in data
assert f"projects/{CLOUD_PROJECT_ID}/subscriptions" in data["subscriber_id"]
data.pop("subscriber_id")
assert data == {
"sdm": {},
"auth_implementation": "imported-cred",
"cloud_project_id": CLOUD_PROJECT_ID,
"project_id": PROJECT_ID,
"token": {
"refresh_token": "mock-refresh-token",
"access_token": "mock-access-token",
"type": "Bearer",
},
}
@@ -127,8 +127,6 @@ async def test_setup_susbcriber_failure(
):
"""Test configuration error."""
with patch(
"homeassistant.helpers.config_entry_oauth2_flow.async_get_config_entry_implementation"
), patch(
"homeassistant.components.nest.api.GoogleNestSubscriber.start_async",
side_effect=SubscriberException(),
):
+1 -3
View File
@@ -443,9 +443,7 @@ async def test_structure_update_event(hass, subscriber, setup_platform):
},
auth=None,
)
with patch(
"homeassistant.helpers.config_entry_oauth2_flow.async_get_config_entry_implementation"
), patch("homeassistant.components.nest.PLATFORMS", [PLATFORM]), patch(
with patch("homeassistant.components.nest.PLATFORMS", [PLATFORM]), patch(
"homeassistant.components.nest.api.GoogleNestSubscriber",
return_value=subscriber,
):
+17 -4
View File
@@ -25,10 +25,13 @@ from homeassistant.components.nest import DOMAIN
from homeassistant.config_entries import ConfigEntryState
from .common import (
PROJECT_ID,
SUBSCRIBER_ID,
TEST_CONFIG_APP_CREDS,
TEST_CONFIG_HYBRID,
TEST_CONFIG_YAML_ONLY,
TEST_CONFIGFLOW_APP_CREDS,
FakeSubscriber,
NestTestConfig,
YieldFixture,
)
@@ -170,7 +173,8 @@ async def test_subscriber_configuration_failure(
@pytest.mark.parametrize(
"nest_test_config", [NestTestConfig(config={}, config_entry_data=None)]
"nest_test_config",
[TEST_CONFIGFLOW_APP_CREDS],
)
async def test_empty_config(hass, error_caplog, config, setup_platform):
"""Test setup is a no-op with not config."""
@@ -205,8 +209,12 @@ async def test_unload_entry(hass, setup_platform):
TEST_CONFIG_HYBRID,
True,
), # Integration created subscriber, garbage collect on remove
(
TEST_CONFIG_APP_CREDS,
True,
), # Integration created subscriber, garbage collect on remove
],
ids=["yaml-config-only", "hybrid-config"],
ids=["yaml-config-only", "hybrid-config", "config-entry"],
)
async def test_remove_entry(hass, nest_test_config, setup_base_platform, delete_called):
"""Test successful unload of a ConfigEntry."""
@@ -220,6 +228,9 @@ async def test_remove_entry(hass, nest_test_config, setup_base_platform, delete_
assert len(entries) == 1
entry = entries[0]
assert entry.state is ConfigEntryState.LOADED
# Assert entry was imported if from configuration.yaml
assert entry.data.get("subscriber_id") == SUBSCRIBER_ID
assert entry.data.get("project_id") == PROJECT_ID
with patch(
"homeassistant.components.nest.api.GoogleNestSubscriber.subscriber_id"
@@ -234,7 +245,9 @@ async def test_remove_entry(hass, nest_test_config, setup_base_platform, delete_
@pytest.mark.parametrize(
"nest_test_config", [TEST_CONFIG_HYBRID], ids=["hyrbid-config"]
"nest_test_config",
[TEST_CONFIG_HYBRID, TEST_CONFIG_APP_CREDS],
ids=["hyrbid-config", "app-creds"],
)
async def test_remove_entry_delete_subscriber_failure(
hass, nest_test_config, setup_base_platform