init home-assistant

This commit is contained in:
2026-11-19 15:15:32 -05:00
parent 2e81d9d300
commit feec6ef9fb
19230 changed files with 3335526 additions and 0 deletions

View File

@@ -0,0 +1 @@
"""Tests for the Google Mail integration."""

View File

@@ -0,0 +1,121 @@
"""Configure tests for the Google Mail integration."""
from collections.abc import Awaitable, Callable, Coroutine
import time
from typing import Any
from unittest.mock import patch
from httplib2 import Response
import pytest
from homeassistant.components.application_credentials import (
ClientCredential,
async_import_client_credential,
)
from homeassistant.components.google_mail.const import DOMAIN
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component
from tests.common import MockConfigEntry, load_fixture
from tests.test_util.aiohttp import AiohttpClientMocker
type ComponentSetup = Callable[[], Awaitable[None]]
BUILD = "homeassistant.components.google_mail.api.build"
CLIENT_ID = "1234"
CLIENT_SECRET = "5678"
GOOGLE_AUTH_URI = "https://accounts.google.com/o/oauth2/v2/auth"
GOOGLE_TOKEN_URI = "https://oauth2.googleapis.com/token"
SCOPES = [
"https://www.googleapis.com/auth/gmail.compose",
"https://www.googleapis.com/auth/gmail.settings.basic",
]
SENSOR = "sensor.example_gmail_com_vacation_end_date"
TITLE = "example@gmail.com"
TOKEN = "homeassistant.components.google_mail.api.config_entry_oauth2_flow.OAuth2Session.async_ensure_token_valid"
@pytest.fixture(name="scopes")
def mock_scopes() -> list[str]:
"""Fixture to set the scopes present in the OAuth token."""
return SCOPES
@pytest.fixture(autouse=True)
async def setup_credentials(hass: HomeAssistant) -> None:
"""Fixture to setup credentials."""
assert await async_setup_component(hass, "application_credentials", {})
await async_import_client_credential(
hass,
DOMAIN,
ClientCredential(CLIENT_ID, CLIENT_SECRET),
DOMAIN,
)
@pytest.fixture(name="expires_at")
def mock_expires_at() -> int:
"""Fixture to set the oauth token expiration time."""
return time.time() + 3600
@pytest.fixture(name="config_entry")
def mock_config_entry(expires_at: int, scopes: list[str]) -> MockConfigEntry:
"""Create Google Mail entry in Home Assistant."""
return MockConfigEntry(
domain=DOMAIN,
title=TITLE,
unique_id=TITLE,
data={
"auth_implementation": DOMAIN,
"token": {
"access_token": "mock-access-token",
"refresh_token": "mock-refresh-token",
"expires_at": expires_at,
"scope": " ".join(scopes),
},
},
)
@pytest.fixture(autouse=True)
def mock_connection(aioclient_mock: AiohttpClientMocker) -> None:
"""Mock Google Mail connection."""
aioclient_mock.post(
GOOGLE_TOKEN_URI,
json={
"refresh_token": "mock-refresh-token",
"access_token": "mock-access-token",
"type": "Bearer",
"expires_in": 60,
},
)
@pytest.fixture(name="setup_integration")
async def mock_setup_integration(
hass: HomeAssistant, config_entry: MockConfigEntry
) -> Callable[[], Coroutine[Any, Any, None]]:
"""Fixture for setting up the component."""
config_entry.add_to_hass(hass)
assert await async_setup_component(hass, "application_credentials", {})
await async_import_client_credential(
hass,
DOMAIN,
ClientCredential(CLIENT_ID, CLIENT_SECRET),
DOMAIN,
)
async def func() -> None:
with patch(
"httplib2.Http.request",
return_value=(
Response({}),
bytes(load_fixture("google_mail/get_vacation.json"), encoding="UTF-8"),
),
):
assert await async_setup_component(hass, DOMAIN, {})
await hass.async_block_till_done()
return func

View File

@@ -0,0 +1,6 @@
{
"emailAddress": "example@gmail.com",
"messagesTotal": 35308,
"threadsTotal": 33901,
"historyId": "4178212"
}

View File

@@ -0,0 +1,6 @@
{
"emailAddress": "example2@gmail.com",
"messagesTotal": 35308,
"threadsTotal": 33901,
"historyId": "4178212"
}

View File

@@ -0,0 +1,8 @@
{
"enableAutoReply": true,
"responseSubject": "Vacation",
"responseBodyPlainText": "I am on vacation.",
"restrictToContacts": false,
"startTime": "1668402000000",
"endTime": "1668747600000"
}

View File

@@ -0,0 +1,6 @@
{
"enableAutoReply": true,
"responseSubject": "Vacation",
"responseBodyPlainText": "I am on vacation.",
"restrictToContacts": false
}

View File

@@ -0,0 +1,8 @@
{
"enableAutoReply": false,
"responseSubject": "Vacation",
"responseBodyPlainText": "I am on vacation.",
"restrictToContacts": false,
"startTime": "1668402000000",
"endTime": "1668747600000"
}

View File

@@ -0,0 +1,216 @@
"""Test the Google Mail config flow."""
from unittest.mock import patch
from httplib2 import Response
import pytest
from homeassistant import config_entries
from homeassistant.components.google_mail.const import DOMAIN
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from homeassistant.helpers import config_entry_oauth2_flow
from .conftest import CLIENT_ID, GOOGLE_AUTH_URI, GOOGLE_TOKEN_URI, SCOPES, TITLE
from tests.common import MockConfigEntry, load_fixture
from tests.test_util.aiohttp import AiohttpClientMocker
from tests.typing import ClientSessionGenerator
@pytest.mark.usefixtures("current_request_with_host")
async def test_full_flow(
hass: HomeAssistant, hass_client_no_auth: ClientSessionGenerator
) -> None:
"""Check full flow."""
result = await hass.config_entries.flow.async_init(
"google_mail", context={"source": config_entries.SOURCE_USER}
)
state = config_entry_oauth2_flow._encode_jwt(
hass,
{
"flow_id": result["flow_id"],
"redirect_uri": "https://example.com/auth/external/callback",
},
)
assert result["url"] == (
f"{GOOGLE_AUTH_URI}?response_type=code&client_id={CLIENT_ID}"
"&redirect_uri=https://example.com/auth/external/callback"
f"&state={state}&scope={'+'.join(SCOPES)}"
"&access_type=offline&prompt=consent"
)
client = await hass_client_no_auth()
resp = await client.get(f"/auth/external/callback?code=abcd&state={state}")
assert resp.status == 200
assert resp.headers["content-type"] == "text/html; charset=utf-8"
with (
patch(
"homeassistant.components.google_mail.async_setup_entry", return_value=True
) as mock_setup,
patch(
"httplib2.Http.request",
return_value=(
Response({}),
bytes(load_fixture("google_mail/get_profile.json"), encoding="UTF-8"),
),
),
):
result = await hass.config_entries.flow.async_configure(result["flow_id"])
assert len(hass.config_entries.async_entries(DOMAIN)) == 1
assert len(mock_setup.mock_calls) == 1
assert result.get("type") is FlowResultType.CREATE_ENTRY
assert result.get("title") == TITLE
assert "result" in result
assert result.get("result").unique_id == TITLE
assert "token" in result.get("result").data
assert result.get("result").data["token"].get("access_token") == "mock-access-token"
assert (
result.get("result").data["token"].get("refresh_token") == "mock-refresh-token"
)
@pytest.mark.parametrize(
("fixture", "abort_reason", "placeholders", "call_count", "access_token"),
[
("get_profile", "reauth_successful", None, 1, "updated-access-token"),
(
"get_profile_2",
"wrong_account",
{"email": "example@gmail.com"},
0,
"mock-access-token",
),
],
)
@pytest.mark.usefixtures("current_request_with_host")
async def test_reauth(
hass: HomeAssistant,
hass_client_no_auth: ClientSessionGenerator,
aioclient_mock: AiohttpClientMocker,
config_entry: MockConfigEntry,
fixture: str,
abort_reason: str,
placeholders: dict[str, str],
call_count: int,
access_token: str,
) -> None:
"""Test the re-authentication case updates the correct config entry.
Make sure we abort if the user selects the
wrong account on the consent screen.
"""
config_entry.add_to_hass(hass)
config_entry.async_start_reauth(hass)
await hass.async_block_till_done()
flows = hass.config_entries.flow.async_progress()
assert len(flows) == 1
result = flows[0]
assert result["step_id"] == "reauth_confirm"
result = await hass.config_entries.flow.async_configure(result["flow_id"], {})
state = config_entry_oauth2_flow._encode_jwt(
hass,
{
"flow_id": result["flow_id"],
"redirect_uri": "https://example.com/auth/external/callback",
},
)
assert result["url"] == (
f"{GOOGLE_AUTH_URI}?response_type=code&client_id={CLIENT_ID}"
"&redirect_uri=https://example.com/auth/external/callback"
f"&state={state}&scope={'+'.join(SCOPES)}"
"&access_type=offline&prompt=consent"
)
client = await hass_client_no_auth()
resp = await client.get(f"/auth/external/callback?code=abcd&state={state}")
assert resp.status == 200
assert resp.headers["content-type"] == "text/html; charset=utf-8"
aioclient_mock.clear_requests()
aioclient_mock.post(
GOOGLE_TOKEN_URI,
json={
"refresh_token": "mock-refresh-token",
"access_token": "updated-access-token",
"type": "Bearer",
"expires_in": 60,
},
)
with (
patch(
"homeassistant.components.google_mail.async_setup_entry", return_value=True
) as mock_setup,
patch(
"httplib2.Http.request",
return_value=(
Response({}),
bytes(load_fixture(f"google_mail/{fixture}.json"), encoding="UTF-8"),
),
),
):
result = await hass.config_entries.flow.async_configure(result["flow_id"])
assert len(hass.config_entries.async_entries(DOMAIN)) == 1
assert result.get("type") is FlowResultType.ABORT
assert result["reason"] == abort_reason
assert result["description_placeholders"] == placeholders
assert len(mock_setup.mock_calls) == call_count
assert config_entry.unique_id == TITLE
assert "token" in config_entry.data
# Verify access token is refreshed
assert config_entry.data["token"].get("access_token") == access_token
assert config_entry.data["token"].get("refresh_token") == "mock-refresh-token"
@pytest.mark.usefixtures("current_request_with_host")
async def test_already_configured(
hass: HomeAssistant,
hass_client_no_auth: ClientSessionGenerator,
config_entry: MockConfigEntry,
) -> None:
"""Test case where config flow discovers unique id was already configured."""
config_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
"google_mail", context={"source": config_entries.SOURCE_USER}
)
state = config_entry_oauth2_flow._encode_jwt(
hass,
{
"flow_id": result["flow_id"],
"redirect_uri": "https://example.com/auth/external/callback",
},
)
assert result["url"] == (
f"{GOOGLE_AUTH_URI}?response_type=code&client_id={CLIENT_ID}"
"&redirect_uri=https://example.com/auth/external/callback"
f"&state={state}&scope={'+'.join(SCOPES)}"
"&access_type=offline&prompt=consent"
)
client = await hass_client_no_auth()
resp = await client.get(f"/auth/external/callback?code=abcd&state={state}")
assert resp.status == 200
assert resp.headers["content-type"] == "text/html; charset=utf-8"
with patch(
"httplib2.Http.request",
return_value=(
Response({}),
bytes(load_fixture("google_mail/get_profile.json"), encoding="UTF-8"),
),
):
result = await hass.config_entries.flow.async_configure(result["flow_id"])
assert result.get("type") is FlowResultType.ABORT
assert result.get("reason") == "already_configured"

View File

@@ -0,0 +1,138 @@
"""Tests for Google Mail."""
import http
import time
from unittest.mock import patch
from aiohttp.client_exceptions import ClientError
import pytest
from homeassistant.components.google_mail import DOMAIN
from homeassistant.config_entries import ConfigEntryState
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr
from .conftest import GOOGLE_TOKEN_URI, ComponentSetup
from tests.test_util.aiohttp import AiohttpClientMocker
async def test_setup_success(
hass: HomeAssistant, setup_integration: ComponentSetup
) -> None:
"""Test successful setup and unload."""
await setup_integration()
entries = hass.config_entries.async_entries(DOMAIN)
assert len(entries) == 1
assert entries[0].state is ConfigEntryState.LOADED
await hass.config_entries.async_unload(entries[0].entry_id)
await hass.async_block_till_done()
assert not hass.services.async_services().get(DOMAIN)
@pytest.mark.parametrize("expires_at", [time.time() - 3600], ids=["expired"])
async def test_expired_token_refresh_success(
hass: HomeAssistant,
setup_integration: ComponentSetup,
aioclient_mock: AiohttpClientMocker,
) -> None:
"""Test expired token is refreshed."""
aioclient_mock.clear_requests()
aioclient_mock.post(
GOOGLE_TOKEN_URI,
json={
"access_token": "updated-access-token",
"refresh_token": "updated-refresh-token",
"expires_at": time.time() + 3600,
"expires_in": 3600,
},
)
await setup_integration()
entries = hass.config_entries.async_entries(DOMAIN)
assert len(entries) == 1
assert entries[0].state is ConfigEntryState.LOADED
assert entries[0].data["token"]["access_token"] == "updated-access-token"
assert entries[0].data["token"]["expires_in"] == 3600
@pytest.mark.parametrize(
("expires_at", "status", "expected_state"),
[
(
time.time() - 3600,
http.HTTPStatus.UNAUTHORIZED,
ConfigEntryState.SETUP_ERROR,
),
(
time.time() - 3600,
http.HTTPStatus.INTERNAL_SERVER_ERROR,
ConfigEntryState.SETUP_RETRY,
),
(
time.time() - 3600,
http.HTTPStatus.BAD_REQUEST,
ConfigEntryState.SETUP_ERROR,
),
],
ids=["failure_requires_reauth", "transient_failure", "revoked_auth"],
)
async def test_expired_token_refresh_failure(
hass: HomeAssistant,
setup_integration: ComponentSetup,
aioclient_mock: AiohttpClientMocker,
status: http.HTTPStatus,
expected_state: ConfigEntryState,
) -> None:
"""Test failure while refreshing token with a transient error."""
aioclient_mock.clear_requests()
aioclient_mock.post(
GOOGLE_TOKEN_URI,
status=status,
)
await setup_integration()
# Verify a transient failure has occurred
entries = hass.config_entries.async_entries(DOMAIN)
assert entries[0].state is expected_state
async def test_expired_token_refresh_client_error(
hass: HomeAssistant,
setup_integration: ComponentSetup,
) -> None:
"""Test failure while refreshing token with a client error."""
with patch(
"homeassistant.components.google_mail.OAuth2Session.async_ensure_token_valid",
side_effect=ClientError,
):
await setup_integration()
# Verify a transient failure has occurred
entries = hass.config_entries.async_entries(DOMAIN)
assert entries[0].state is ConfigEntryState.SETUP_RETRY
async def test_device_info(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
setup_integration: ComponentSetup,
) -> None:
"""Test device info."""
await setup_integration()
entry = hass.config_entries.async_entries(DOMAIN)[0]
device = device_registry.async_get_device(identifiers={(DOMAIN, entry.entry_id)})
assert device.entry_type is dr.DeviceEntryType.SERVICE
assert device.identifiers == {(DOMAIN, entry.entry_id)}
assert device.manufacturer == "Google, Inc."
assert device.name == "example@gmail.com"

View File

@@ -0,0 +1,77 @@
"""Notify tests for the Google Mail integration."""
from unittest.mock import patch
import pytest
from voluptuous.error import Invalid
from homeassistant.components.notify import DOMAIN as NOTIFY_DOMAIN
from homeassistant.core import HomeAssistant
from .conftest import BUILD, ComponentSetup
async def test_notify(
hass: HomeAssistant,
setup_integration: ComponentSetup,
) -> None:
"""Test service call draft email."""
await setup_integration()
with patch(BUILD) as mock_client:
await hass.services.async_call(
NOTIFY_DOMAIN,
"example_gmail_com",
{
"title": "Test",
"message": "test email",
"target": "text@example.com",
},
blocking=True,
)
assert len(mock_client.mock_calls) == 5
with patch(BUILD) as mock_client:
await hass.services.async_call(
NOTIFY_DOMAIN,
"example_gmail_com",
{
"title": "Test",
"message": "test email",
"target": "text@example.com",
"data": {"send": False},
},
blocking=True,
)
assert len(mock_client.mock_calls) == 5
async def test_notify_voluptuous_error(
hass: HomeAssistant,
setup_integration: ComponentSetup,
) -> None:
"""Test voluptuous error thrown when drafting email."""
await setup_integration()
with pytest.raises(ValueError) as ex:
await hass.services.async_call(
NOTIFY_DOMAIN,
"example_gmail_com",
{
"title": "Test",
"message": "test email",
},
blocking=True,
)
assert ex.match("recipient address required")
with pytest.raises(Invalid) as ex:
await hass.services.async_call(
NOTIFY_DOMAIN,
"example_gmail_com",
{
"title": "Test",
},
blocking=True,
)
assert ex.getrepr("required key not provided")

View File

@@ -0,0 +1,72 @@
"""Sensor tests for the Google Mail integration."""
from datetime import timedelta
from unittest.mock import patch
from google.auth.exceptions import RefreshError
from httplib2 import Response
import pytest
from homeassistant import config_entries
from homeassistant.components.google_mail.const import DOMAIN
from homeassistant.components.sensor import SensorDeviceClass
from homeassistant.const import ATTR_DEVICE_CLASS, STATE_UNKNOWN
from homeassistant.core import HomeAssistant
import homeassistant.util.dt as dt_util
from .conftest import SENSOR, TOKEN, ComponentSetup
from tests.common import async_fire_time_changed, load_fixture
@pytest.mark.parametrize(
("fixture", "result"),
[
("get_vacation", "2022-11-18T05:00:00+00:00"),
("get_vacation_no_dates", STATE_UNKNOWN),
("get_vacation_off", STATE_UNKNOWN),
],
)
async def test_sensors(
hass: HomeAssistant, setup_integration: ComponentSetup, fixture: str, result: str
) -> None:
"""Test we get sensor data."""
await setup_integration()
state = hass.states.get(SENSOR)
assert state.state == "2022-11-18T05:00:00+00:00"
assert state.attributes.get(ATTR_DEVICE_CLASS) == SensorDeviceClass.TIMESTAMP
with patch(
"httplib2.Http.request",
return_value=(
Response({}),
bytes(load_fixture(f"google_mail/{fixture}.json"), encoding="UTF-8"),
),
):
next_update = dt_util.utcnow() + timedelta(minutes=15)
async_fire_time_changed(hass, next_update)
await hass.async_block_till_done(wait_background_tasks=True)
state = hass.states.get(SENSOR)
assert state.state == result
async def test_sensor_reauth_trigger(
hass: HomeAssistant, setup_integration: ComponentSetup
) -> None:
"""Test reauth is triggered after a refresh error."""
await setup_integration()
with patch(TOKEN, side_effect=RefreshError):
next_update = dt_util.utcnow() + timedelta(minutes=15)
async_fire_time_changed(hass, next_update)
await hass.async_block_till_done(wait_background_tasks=True)
flows = hass.config_entries.flow.async_progress()
assert len(flows) == 1
flow = flows[0]
assert flow["step_id"] == "reauth_confirm"
assert flow["handler"] == DOMAIN
assert flow["context"]["source"] == config_entries.SOURCE_REAUTH

View File

@@ -0,0 +1,105 @@
"""Services tests for the Google Mail integration."""
from unittest.mock import patch
from aiohttp.client_exceptions import ClientResponseError
from google.auth.exceptions import RefreshError
import pytest
from homeassistant import config_entries
from homeassistant.components.google_mail import DOMAIN
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from .conftest import BUILD, SENSOR, TOKEN, ComponentSetup
async def test_set_vacation(
hass: HomeAssistant,
setup_integration: ComponentSetup,
) -> None:
"""Test service call set vacation."""
await setup_integration()
with patch(BUILD) as mock_client:
await hass.services.async_call(
DOMAIN,
"set_vacation",
{
"entity_id": SENSOR,
"enabled": True,
"title": "Vacation",
"message": "Vacation message",
"plain_text": False,
"restrict_contacts": True,
"restrict_domain": True,
"start": "2022-11-20",
"end": "2022-11-26",
},
blocking=True,
)
assert len(mock_client.mock_calls) == 5
with patch(BUILD) as mock_client:
await hass.services.async_call(
DOMAIN,
"set_vacation",
{
"entity_id": SENSOR,
"enabled": True,
"title": "Vacation",
"message": "Vacation message",
"plain_text": True,
"restrict_contacts": True,
"restrict_domain": True,
"start": "2022-11-20",
"end": "2022-11-26",
},
blocking=True,
)
assert len(mock_client.mock_calls) == 5
@pytest.mark.parametrize(
("side_effect"),
[
(RefreshError,),
(ClientResponseError("", (), status=400),),
],
)
async def test_reauth_trigger(
hass: HomeAssistant,
setup_integration: ComponentSetup,
side_effect,
) -> None:
"""Test reauth is triggered after a refresh error during service call."""
await setup_integration()
with patch(TOKEN, side_effect=side_effect), pytest.raises(HomeAssistantError):
await hass.services.async_call(
DOMAIN,
"set_vacation",
{
"entity_id": SENSOR,
"enabled": True,
"title": "Vacation",
"message": "Vacation message",
"plain_text": True,
"restrict_contacts": True,
"restrict_domain": True,
"start": "2022-11-20",
"end": "2022-11-26",
},
blocking=True,
)
await hass.async_block_till_done()
await hass.async_block_till_done()
flows = hass.config_entries.flow.async_progress()
assert len(flows) == 1
flow = flows[0]
assert flow["step_id"] == "reauth_confirm"
assert flow["handler"] == DOMAIN
assert flow["context"]["source"] == config_entries.SOURCE_REAUTH