8000 Modernize tests for smhi by gjohansson-ST · Pull Request #139334 · home-assistant/core · GitHub
[go: up one dir, main page]

Skip to content

Modernize tests for smhi #139334

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
May 28, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
138 changes: 125 additions & 13 deletions tests/components/smhi/conftest.py
Original file line number Diff line number Diff line change
@@ -1,25 +1,137 @@
"""Provide common smhi fixtures."""

from __future__ import annotations

from collections.abc import AsyncGenerator, Generator
import json
from typing import Any
from unittest.mock import AsyncMock, MagicMock, patch

from pysmhi.smhi_forecast import SMHIForecast, SMHIPointForecast
import pytest

from homeassistant.components.smhi import PLATFORMS
from homeassistant.components.smhi.const import DOMAIN
from homeassistant.const import CONF_LATITUDE, CONF_LOCATION, CONF_LONGITUDE, Platform
from homeassistant.core import HomeAssistant

from . import TEST_CONFIG

from tests.common import MockConfigEntry, load_fixture
from tests.test_util.aiohttp import AiohttpClientMocker


@pytest.fixture
def mock_setup_entry() -> Generator[AsyncMock]:
"""Override async_setup_entry."""
with patch(
"homeassistant.components.smhi.async_setup_entry", return_value=True
) as mock_setup_entry:
yield mock_setup_entry


@pytest.fixture(name="load_platforms")
async def patch_platform_constant() -> list[Platform]:
"""Return list of platforms to load."""
return PLATFORMS


@pytest.fixture
async def load_int(
hass: HomeAssistant,
mock_client: SMHIPointForecast,
load_platforms: list[Platform],
) -> MockConfigEntry:
"""Set up the SMHI integration."""
hass.config.latitude = "59.32624"
hass.config.longitude = "17.84197"
config_entry = MockConfigEntry(
domain=DOMAIN,
data=TEST_CONFIG,
entry_id="01JMZDH8N5PFHGJNYKKYCSCWER",
unique_id="59.32624-17.84197",
version=3,
title="Test",
)

config_entry.add_to_hass(hass)

with patch("homeassistant.components.smhi.PLATFORMS", load_platforms):
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()

return config_entry


@pytest.fixture(name="mock_client")
async def get_client(
hass: HomeAssistant,
get_data: tuple[list[SMHIForecast], list[SMHIForecast], list[SMHIForecast]],
) -> AsyncGenerator[MagicMock]:
"""Mock SMHIPointForecast client."""

with (
patch(
"homeassistant.components.smhi.coordinator.SMHIPointForecast",
autospec=True,
) as mock_client,
patch(
"homeassistant.components.smhi.config_flow.SMHIPointForecast",
return_value=mock_client.return_value,
),
):
client = mock_client.return_value
client.async_get_daily_forecast.return_value = get_data[0]
client.async_get_twice_daily_forecast.return_value = get_data[1]
client.async_get_hourly_forecast.return_value = get_data[2]
yield client


@pytest.fixture(name="get_data")
async def get_data_from_library(
hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker,
load_json: dict[str, Any],
) -> AsyncGenerator[tuple[list[SMHIForecast], list[SMHIForecast], list[SMHIForecast]]]:
"""Get data from api."""
client = SMHIPointForecast(
TEST_CONFIG[CONF_LOCATION][CONF_LONGITUDE],
TEST_CONFIG[CONF_LOCATION][CONF_LATITUDE],
aioclient_mock.create_session(hass.loop),
)
with patch.object(
client._api,
"async_get_data",
return_value=load_json,
):
data_daily = await client.async_get_daily_forecast()
data_twice_daily = await client.async_get_twice_daily_forecast()
data_hourly = await client.async_get_hourly_forecast()

from tests.common import load_fixture
yield (data_daily, data_twice_daily, data_hourly)
await client._api._session.close()


@pytest.fixture(scope="package")
def api_response():
"""Return an API response."""
return load_fixture("smhi.json", DOMAIN)
@pytest.fixture(name="load_json")
def load_json_from_fixture(
load_data: tuple[str, str, str],
to_load: int,
) -> dict[str, Any]:
"""Load fixture with json data and return."""
return json.loads(load_data[to_load])


@pytest.fixture(scope="package")
def api_response_night():
"""Return an API response for night only."""
return load_fixture("smhi_night.json", DOMAIN)
@pytest.fixture(name="load_data", scope="package")
def load_data_from_fixture() -> tuple[str, str, str]:
"""Load fixture with fixture data and return."""
return (
load_fixture("smhi.json", "smhi"),
load_fixture("smhi_night.json", "smhi"),
load_fixture("smhi_short.json", "smhi"),
)


@pytest.fixture(scope="package")
def api_response_lack_data():
"""Return an API response."""
return load_fixture("smhi_short.json", DOMAIN)
@pytest.fixture
def to_load() -> int:
"""Fixture to load."""
return 0
20 changes: 10 additions & 10 deletions tests/components/smhi/snapshots/test_weather.ambr
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# serializer version: 1
# name: test_clear_night[clear-night_forecast]
# name: test_clear_night[1][clear-night_forecast]
dict({
'weather.smhi_test': dict({
'forecast': list([
Expand Down Expand Up @@ -59,11 +59,11 @@
}),
})
# ---
# name: test_clear_night[clear_night]
# name: test_clear_night[1][clear_night]
ReadOnlyDict({
'attribution': 'Swedish weather institute (SMHI)',
'cloud_coverage': 100,
'friendly_name': 'test',
'friendly_name': 'Test',
'humidity': 100,
'precipitation_unit': <UnitOfPrecipitationDepth.MILLIMETERS: 'mm'>,
'pressure': 992.4,
Expand All @@ -80,7 +80,7 @@
'wind_speed_unit': <UnitOfSpeed.KILOMETERS_PER_HOUR: 'km/h'>,
})
# ---
# name: test_forecast_service[get_forecasts]
# name: test_forecast_service[load_platforms0]
dict({
'weather.smhi_test': dict({
'forecast': list([
Expand Down Expand Up @@ -218,7 +218,7 @@
}),
})
# ---
# name: test_forecast_services
# name: test_forecast_services[load_platforms0]
dict({
'cloud_coverage': 100,
'condition': 'cloudy',
Expand All @@ -233,7 +233,7 @@
'wind_speed': 10.08,
})
# ---
# name: test_forecast_services.1
# name: test_forecast_services[load_platforms0].1
dict({
'cloud_coverage': 75,
'condition': 'partlycloudy',
Expand All @@ -248,7 +248,7 @@
'wind_speed': 14.76,
})
# ---
# name: test_forecast_services.2
# name: test_forecast_services[load_platforms0].2
dict({
'cloud_coverage': 100,
'condition': 'fog',
Expand All @@ -263,7 +263,7 @@
'wind_speed': 9.72,
})
# ---
# name: test_forecast_services.3
# name: test_forecast_services[load_platforms0].3
dict({
'cloud_coverage': 100,
'condition': 'cloudy',
Expand All @@ -278,11 +278,11 @@
'wind_speed': 12.24,
})
# ---
# name: test_setup_hass
# name: test_setup_hass[load_platforms0]
ReadOnlyDict({
'attribution': 'Swedish weather institute (SMHI)',
'cloud_coverage': 100,
'friendly_name': 'test',
'friendly_name': 'Test',
'humidity': 100,
'precipitation_unit': <UnitOfPrecipitationDepth.MILLIMETERS: 'mm'>,
'pressure': 992.4,
Expand Down
Loading
0