init home-assistant
This commit is contained in:
11
home-assistant/tests/components/microbees/__init__.py
Normal file
11
home-assistant/tests/components/microbees/__init__.py
Normal file
@@ -0,0 +1,11 @@
|
||||
"""Tests for the MicroBees component."""
|
||||
|
||||
from homeassistant.core import HomeAssistant
|
||||
|
||||
from tests.common import MockConfigEntry
|
||||
|
||||
|
||||
async def setup_integration(hass: HomeAssistant, config_entry: MockConfigEntry) -> None:
|
||||
"""Fixture for setting up the component."""
|
||||
config_entry.add_to_hass(hass)
|
||||
await hass.config_entries.async_setup(config_entry.entry_id)
|
||||
97
home-assistant/tests/components/microbees/conftest.py
Normal file
97
home-assistant/tests/components/microbees/conftest.py
Normal file
@@ -0,0 +1,97 @@
|
||||
"""Conftest for microBees tests."""
|
||||
|
||||
import time
|
||||
from unittest.mock import AsyncMock, patch
|
||||
|
||||
from microBeesPy import Bee, MicroBees, Profile
|
||||
import pytest
|
||||
|
||||
from homeassistant.components.application_credentials import (
|
||||
ClientCredential,
|
||||
async_import_client_credential,
|
||||
)
|
||||
from homeassistant.components.microbees.const import DOMAIN
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.setup import async_setup_component
|
||||
|
||||
from tests.common import (
|
||||
MockConfigEntry,
|
||||
load_json_array_fixture,
|
||||
load_json_object_fixture,
|
||||
)
|
||||
|
||||
CLIENT_ID = "1234"
|
||||
CLIENT_SECRET = "5678"
|
||||
TITLE = "MicroBees"
|
||||
MICROBEES_AUTH_URI = "https://dev.microbees.com/oauth/authorize"
|
||||
MICROBEES_TOKEN_URI = "https://dev.microbees.com/oauth/token"
|
||||
|
||||
SCOPES = ["read", "write"]
|
||||
|
||||
|
||||
@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 YouTube entry in Home Assistant."""
|
||||
return MockConfigEntry(
|
||||
domain=DOMAIN,
|
||||
title=TITLE,
|
||||
unique_id=54321,
|
||||
data={
|
||||
"auth_implementation": DOMAIN,
|
||||
"token": {
|
||||
"access_token": "mock-access-token",
|
||||
"refresh_token": "mock-refresh-token",
|
||||
"expires_at": expires_at,
|
||||
"scope": " ".join(scopes),
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture(name="microbees")
|
||||
def mock_microbees():
|
||||
"""Mock microbees."""
|
||||
|
||||
devices_json = load_json_array_fixture("microbees/bees.json")
|
||||
devices = [Bee.from_dict(device) for device in devices_json]
|
||||
profile_json = load_json_object_fixture("microbees/profile.json")
|
||||
profile = Profile.from_dict(profile_json)
|
||||
mock = AsyncMock(spec=MicroBees)
|
||||
mock.getBees.return_value = devices
|
||||
mock.getMyProfile.return_value = profile
|
||||
|
||||
with (
|
||||
patch(
|
||||
"homeassistant.components.microbees.config_flow.MicroBees",
|
||||
return_value=mock,
|
||||
) as mock,
|
||||
patch(
|
||||
"homeassistant.components.microbees.MicroBees",
|
||||
return_value=mock,
|
||||
),
|
||||
):
|
||||
yield mock
|
||||
87
home-assistant/tests/components/microbees/fixtures/bees.json
Normal file
87
home-assistant/tests/components/microbees/fixtures/bees.json
Normal file
@@ -0,0 +1,87 @@
|
||||
[
|
||||
{
|
||||
"id": 24907,
|
||||
"label": "Test this",
|
||||
"serial": "10521CB7C864",
|
||||
"gate_serial": "cde153cb-d55c-4230-be93-340eff8f53c2",
|
||||
"gate_id": 4466,
|
||||
"lastUpdate": 1707812698995,
|
||||
"name": "Test this",
|
||||
"active": true,
|
||||
"productID": 46,
|
||||
"prototypeName": "SocketBee Italy",
|
||||
"rssi": -67,
|
||||
"lastActivation": 1707768436222,
|
||||
"icon": "https://products.microbees.com/wp-content/uploads/2020/10/new-foto-socketbee-italia.png",
|
||||
"configuration": {},
|
||||
"sensors": [
|
||||
{
|
||||
"id": 59754,
|
||||
"name": "Sensore Assorbimento",
|
||||
"lastUpdate": 1707812700120,
|
||||
"deviceID": 462,
|
||||
"prototypeID": 223,
|
||||
"prototypeName": "Sensore Assorbimento",
|
||||
"device_type": 0,
|
||||
"dc_type": "Power",
|
||||
"unit": "Wh",
|
||||
"payload": [1, 1, 2, 0.5, 226, 0.013107268, 2, -67],
|
||||
"value": 1
|
||||
},
|
||||
{
|
||||
"id": 59755,
|
||||
"name": "Stato Interruttore Test this",
|
||||
"lastUpdate": 1707812700129,
|
||||
"deviceID": 463,
|
||||
"prototypeID": 224,
|
||||
"prototypeName": "Stato Interruttore",
|
||||
"device_type": 1,
|
||||
"dc_type": "Uptime",
|
||||
"unit": "",
|
||||
"payload": [1, 1, 2, 0.5, 226, 0.013107268, 2, -67],
|
||||
"value": 1
|
||||
}
|
||||
],
|
||||
"actuators": [
|
||||
{
|
||||
"id": 25497,
|
||||
"name": "Test this",
|
||||
"prototypeName": "Interruttore",
|
||||
"deviceID": 461,
|
||||
"configuration": {
|
||||
"actuator_type": "1",
|
||||
"icon": "power_button"
|
||||
},
|
||||
"starred": true,
|
||||
"uptime": 2812005,
|
||||
"sensorID": 59755,
|
||||
"payload": [1, 1, 2, 0.5, 226, 0.013107268, 2, -67],
|
||||
"value": 1,
|
||||
"rooms": []
|
||||
}
|
||||
],
|
||||
"rooms": [],
|
||||
"status_string": [
|
||||
{
|
||||
"name": "Seriale",
|
||||
"value": "10521CB7C864",
|
||||
"icon": "numeric"
|
||||
},
|
||||
{
|
||||
"name": "Ultimo Aggiornamento",
|
||||
"value": "09:25",
|
||||
"icon": "av-timer"
|
||||
},
|
||||
{
|
||||
"name": "Sensore Assorbimento",
|
||||
"value": "1W",
|
||||
"icon": "flash"
|
||||
},
|
||||
{
|
||||
"name": "Stato Interruttore Test This",
|
||||
"value": "on",
|
||||
"icon": "toggle-switch-on"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"id": 54321,
|
||||
"username": "test@microbees.com",
|
||||
"firstName": "Test",
|
||||
"lastName": "Microbees",
|
||||
"email": "test@microbees.com",
|
||||
"locale": "it",
|
||||
"timeZone": "Europe/Rome"
|
||||
}
|
||||
352
home-assistant/tests/components/microbees/test_config_flow.py
Normal file
352
home-assistant/tests/components/microbees/test_config_flow.py
Normal file
@@ -0,0 +1,352 @@
|
||||
"""Tests for config flow."""
|
||||
|
||||
from unittest.mock import AsyncMock, patch
|
||||
|
||||
from microBeesPy import MicroBeesException
|
||||
import pytest
|
||||
|
||||
from homeassistant.components.microbees.const import DOMAIN
|
||||
from homeassistant.config_entries import SOURCE_USER
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.data_entry_flow import FlowResultType
|
||||
from homeassistant.helpers import config_entry_oauth2_flow
|
||||
|
||||
from . import setup_integration
|
||||
from .conftest import CLIENT_ID, MICROBEES_AUTH_URI, MICROBEES_TOKEN_URI, SCOPES
|
||||
|
||||
from tests.common import MockConfigEntry
|
||||
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,
|
||||
aioclient_mock: AiohttpClientMocker,
|
||||
microbees: AsyncMock,
|
||||
) -> None:
|
||||
"""Check full flow."""
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={"source": 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["type"] is FlowResultType.EXTERNAL_STEP
|
||||
assert result["url"] == (
|
||||
f"{MICROBEES_AUTH_URI}?"
|
||||
f"response_type=code&client_id={CLIENT_ID}&"
|
||||
"redirect_uri=https://example.com/auth/external/callback&"
|
||||
f"state={state}"
|
||||
f"&scope={'+'.join(SCOPES)}"
|
||||
)
|
||||
|
||||
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(
|
||||
MICROBEES_TOKEN_URI,
|
||||
json={
|
||||
"access_token": "mock-access-token",
|
||||
"token_type": "bearer",
|
||||
"refresh_token": "mock-refresh-token",
|
||||
"expires_in": 99999,
|
||||
"scope": " ".join(SCOPES),
|
||||
"client_id": CLIENT_ID,
|
||||
},
|
||||
)
|
||||
|
||||
with patch(
|
||||
"homeassistant.components.microbees.async_setup_entry", return_value=True
|
||||
) as mock_setup:
|
||||
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["type"] is FlowResultType.CREATE_ENTRY
|
||||
assert result["title"] == "test@microbees.com"
|
||||
assert "result" in result
|
||||
assert result["result"].unique_id == 54321
|
||||
assert "token" in result["result"].data
|
||||
assert result["result"].data["token"]["access_token"] == "mock-access-token"
|
||||
assert result["result"].data["token"]["refresh_token"] == "mock-refresh-token"
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("current_request_with_host")
|
||||
async def test_config_non_unique_profile(
|
||||
hass: HomeAssistant,
|
||||
hass_client_no_auth: ClientSessionGenerator,
|
||||
microbees: AsyncMock,
|
||||
config_entry: MockConfigEntry,
|
||||
aioclient_mock: AiohttpClientMocker,
|
||||
) -> None:
|
||||
"""Test setup a non-unique profile."""
|
||||
await setup_integration(hass, config_entry)
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={"source": 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["type"] is FlowResultType.EXTERNAL_STEP
|
||||
assert result["url"] == (
|
||||
f"{MICROBEES_AUTH_URI}?"
|
||||
f"response_type=code&client_id={CLIENT_ID}&"
|
||||
"redirect_uri=https://example.com/auth/external/callback&"
|
||||
f"state={state}"
|
||||
f"&scope={'+'.join(SCOPES)}"
|
||||
)
|
||||
|
||||
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(
|
||||
MICROBEES_TOKEN_URI,
|
||||
json={
|
||||
"access_token": "mock-access-token",
|
||||
"token_type": "bearer",
|
||||
"refresh_token": "mock-refresh-token",
|
||||
"expires_in": 99999,
|
||||
"scope": " ".join(SCOPES),
|
||||
"client_id": CLIENT_ID,
|
||||
},
|
||||
)
|
||||
|
||||
result = await hass.config_entries.flow.async_configure(result["flow_id"])
|
||||
assert result["type"] is FlowResultType.ABORT
|
||||
assert result["reason"] == "already_configured"
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("current_request_with_host")
|
||||
async def test_config_reauth_profile(
|
||||
hass: HomeAssistant,
|
||||
hass_client_no_auth: ClientSessionGenerator,
|
||||
aioclient_mock: AiohttpClientMocker,
|
||||
config_entry: MockConfigEntry,
|
||||
microbees: AsyncMock,
|
||||
) -> None:
|
||||
"""Test reauth an existing profile reauthenticates the config entry."""
|
||||
await setup_integration(hass, config_entry)
|
||||
|
||||
result = await config_entry.start_reauth_flow(hass)
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
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"{MICROBEES_AUTH_URI}?"
|
||||
f"response_type=code&client_id={CLIENT_ID}&"
|
||||
"redirect_uri=https://example.com/auth/external/callback&"
|
||||
f"state={state}"
|
||||
f"&scope={'+'.join(SCOPES)}"
|
||||
)
|
||||
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(
|
||||
MICROBEES_TOKEN_URI,
|
||||
json={
|
||||
"access_token": "mock-access-token",
|
||||
"token_type": "bearer",
|
||||
"refresh_token": "mock-refresh-token",
|
||||
"expires_in": 99999,
|
||||
"scope": " ".join(SCOPES),
|
||||
"client_id": CLIENT_ID,
|
||||
},
|
||||
)
|
||||
|
||||
result = await hass.config_entries.flow.async_configure(result["flow_id"])
|
||||
assert result
|
||||
assert result["type"] is FlowResultType.ABORT
|
||||
assert result["reason"] == "reauth_successful"
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("current_request_with_host")
|
||||
async def test_config_reauth_wrong_account(
|
||||
hass: HomeAssistant,
|
||||
hass_client_no_auth: ClientSessionGenerator,
|
||||
aioclient_mock: AiohttpClientMocker,
|
||||
config_entry: MockConfigEntry,
|
||||
microbees: AsyncMock,
|
||||
) -> None:
|
||||
"""Test reauth with wrong account."""
|
||||
await setup_integration(hass, config_entry)
|
||||
microbees.return_value.getMyProfile.return_value.id = 12345
|
||||
result = await config_entry.start_reauth_flow(hass)
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
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"{MICROBEES_AUTH_URI}?"
|
||||
f"response_type=code&client_id={CLIENT_ID}&"
|
||||
"redirect_uri=https://example.com/auth/external/callback&"
|
||||
f"state={state}"
|
||||
f"&scope={'+'.join(SCOPES)}"
|
||||
)
|
||||
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(
|
||||
MICROBEES_TOKEN_URI,
|
||||
json={
|
||||
"access_token": "mock-access-token",
|
||||
"token_type": "bearer",
|
||||
"refresh_token": "mock-refresh-token",
|
||||
"expires_in": 99999,
|
||||
"scope": " ".join(SCOPES),
|
||||
"client_id": CLIENT_ID,
|
||||
},
|
||||
)
|
||||
|
||||
result = await hass.config_entries.flow.async_configure(result["flow_id"])
|
||||
assert result
|
||||
assert result["type"] is FlowResultType.ABORT
|
||||
assert result["reason"] == "wrong_account"
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("current_request_with_host")
|
||||
async def test_config_flow_with_invalid_credentials(
|
||||
hass: HomeAssistant,
|
||||
hass_client_no_auth: ClientSessionGenerator,
|
||||
aioclient_mock: AiohttpClientMocker,
|
||||
microbees: AsyncMock,
|
||||
) -> None:
|
||||
"""Test flow with invalid credentials."""
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={"source": 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["type"] is FlowResultType.EXTERNAL_STEP
|
||||
assert result["url"] == (
|
||||
f"{MICROBEES_AUTH_URI}?"
|
||||
f"response_type=code&client_id={CLIENT_ID}&"
|
||||
"redirect_uri=https://example.com/auth/external/callback&"
|
||||
f"state={state}"
|
||||
f"&scope={'+'.join(SCOPES)}"
|
||||
)
|
||||
|
||||
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(
|
||||
MICROBEES_TOKEN_URI,
|
||||
json={
|
||||
"status": 401,
|
||||
"error": "Invalid Params: invalid client id/secret",
|
||||
},
|
||||
)
|
||||
|
||||
result = await hass.config_entries.flow.async_configure(result["flow_id"])
|
||||
assert result
|
||||
assert result["type"] is FlowResultType.ABORT
|
||||
assert result["reason"] == "oauth_error"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("exception", "error"),
|
||||
[
|
||||
(MicroBeesException("Invalid auth"), "invalid_auth"),
|
||||
(Exception("Unexpected error"), "unknown"),
|
||||
],
|
||||
)
|
||||
@pytest.mark.usefixtures("current_request_with_host")
|
||||
async def test_unexpected_exceptions(
|
||||
hass: HomeAssistant,
|
||||
hass_client_no_auth: ClientSessionGenerator,
|
||||
aioclient_mock: AiohttpClientMocker,
|
||||
config_entry: MockConfigEntry,
|
||||
microbees: AsyncMock,
|
||||
exception: Exception,
|
||||
error: str,
|
||||
) -> None:
|
||||
"""Test unknown error from server."""
|
||||
await setup_integration(hass, config_entry)
|
||||
microbees.return_value.getMyProfile.side_effect = exception
|
||||
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={"source": 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["type"] is FlowResultType.EXTERNAL_STEP
|
||||
assert result["url"] == (
|
||||
f"{MICROBEES_AUTH_URI}?"
|
||||
f"response_type=code&client_id={CLIENT_ID}&"
|
||||
"redirect_uri=https://example.com/auth/external/callback&"
|
||||
f"state={state}"
|
||||
f"&scope={'+'.join(SCOPES)}"
|
||||
)
|
||||
|
||||
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(
|
||||
MICROBEES_TOKEN_URI,
|
||||
json={
|
||||
"access_token": "mock-access-token",
|
||||
"token_type": "bearer",
|
||||
"refresh_token": "mock-refresh-token",
|
||||
"expires_in": 99999,
|
||||
"scope": " ".join(SCOPES),
|
||||
"client_id": CLIENT_ID,
|
||||
},
|
||||
)
|
||||
|
||||
result = await hass.config_entries.flow.async_configure(result["flow_id"])
|
||||
assert result
|
||||
assert result["type"] is FlowResultType.ABORT
|
||||
assert result["reason"] == error
|
||||
Reference in New Issue
Block a user