1
0
mirror of https://github.com/home-assistant/core.git synced 2025-12-24 12:59:34 +00:00

Simplify google calendar authentication setup (#67314)

Simplify google calendar authentication to combine some of the cases together, and reduce unecessarily checks. Make the
tests share common authentication setup and reduce use of mocks by introducing a fake for holding on to credentials.
This makes future refactoring simpler, so we don't have to care as much about the interactions with the credentials
storage.
This commit is contained in:
Allen Porter
2022-02-26 15:17:02 -08:00
committed by GitHub
parent a151d3f9a0
commit 0e74184e4f
4 changed files with 77 additions and 59 deletions

View File

@@ -1,11 +1,17 @@
"""Test configuration and mocks for the google integration."""
from __future__ import annotations
from collections.abc import Callable
import datetime
from typing import Any, Generator, TypeVar
from unittest.mock import Mock, patch
from oauth2client.client import Credentials, OAuth2Credentials
import pytest
from homeassistant.components.google import GoogleCalendarService
from homeassistant.core import HomeAssistant
from homeassistant.util.dt import utcnow
ApiResult = Callable[[dict[str, Any]], None]
T = TypeVar("T")
@@ -36,6 +42,62 @@ def test_calendar():
return TEST_CALENDAR
class FakeStorage:
"""A fake storage object for persiting creds."""
def __init__(self) -> None:
"""Initialize FakeStorage."""
self._creds: Credentials | None = None
def get(self) -> Credentials | None:
"""Get credentials from storage."""
return self._creds
def put(self, creds: Credentials) -> None:
"""Put credentials in storage."""
self._creds = creds
@pytest.fixture
async def token_scopes() -> list[str]:
"""Fixture for scopes used during test."""
return ["https://www.googleapis.com/auth/calendar"]
@pytest.fixture
async def creds(token_scopes: list[str]) -> OAuth2Credentials:
"""Fixture that defines creds used in the test."""
token_expiry = utcnow() + datetime.timedelta(days=7)
return OAuth2Credentials(
access_token="ACCESS_TOKEN",
client_id="client-id",
client_secret="client-secret",
refresh_token="REFRESH_TOKEN",
token_expiry=token_expiry,
token_uri="http://example.com",
user_agent="n/a",
scopes=token_scopes,
)
@pytest.fixture(autouse=True)
async def storage() -> YieldFixture[FakeStorage]:
"""Fixture to populate an existing token file for read on startup."""
storage = FakeStorage()
with patch("homeassistant.components.google.Storage", return_value=storage):
yield storage
@pytest.fixture
async def mock_token_read(
hass: HomeAssistant,
creds: OAuth2Credentials,
storage: FakeStorage,
) -> None:
"""Fixture to populate an existing token file for read on startup."""
storage.put(creds)
@pytest.fixture
def mock_next_event():
"""Mock the google calendar data."""