Use JSON fixture helpers in tests (6/6) (#180840)

This commit is contained in:
Joost Lekkerkerker
2026-08-30 19:09:14 +02:00
committed by GitHub
parent 17495c0608
commit 9c81f63f98
13 changed files with 56 additions and 61 deletions
+2 -3
View File
@@ -1,6 +1,5 @@
"""Test Subaru diagnostics."""
import json
from unittest.mock import patch
import pytest
@@ -18,7 +17,7 @@ from .conftest import (
advance_time_to_next_fetch,
)
from tests.common import async_load_fixture
from tests.common import async_load_json_object_fixture
from tests.components.diagnostics import (
get_diagnostics_for_config_entry,
get_diagnostics_for_device,
@@ -58,7 +57,7 @@ async def test_device_diagnostics(
)
assert reg_device is not None
raw_data = json.loads(await async_load_fixture(hass, "raw_api_data.json", DOMAIN))
raw_data = await async_load_json_object_fixture(hass, "raw_api_data.json", DOMAIN)
with patch(MOCK_API_GET_RAW_DATA, return_value=raw_data) as mock_get_raw_data:
assert (
await get_diagnostics_for_device(
@@ -1,7 +1,6 @@
"""Common fixtures for the swiss_public_transport tests."""
from collections.abc import Generator
import json
from unittest.mock import AsyncMock, patch
import pytest
@@ -12,7 +11,7 @@ from homeassistant.components.swiss_public_transport.const import (
DOMAIN,
)
from tests.common import MockConfigEntry, load_fixture
from tests.common import MockConfigEntry, load_json_array_fixture
START = "Zürich"
DESTINATION = "Bern"
@@ -35,7 +34,7 @@ def mock_opendata_client() -> Generator[AsyncMock]:
client.async_get_data.return_value = None
client.from_name = START
client.to_name = DESTINATION
client.connections = json.loads(load_fixture("connections.json", DOMAIN))[0:3]
client.connections = load_json_array_fixture("connections.json", DOMAIN)[0:3]
yield client
@@ -1,6 +1,5 @@
"""Tests for the swiss_public_transport sensor platform."""
import json
from unittest.mock import AsyncMock, patch
from opendata_transport.exceptions import (
@@ -25,7 +24,7 @@ from . import setup_integration
from tests.common import (
MockConfigEntry,
async_fire_time_changed,
async_load_fixture,
async_load_json_array_fixture,
snapshot_platform,
)
from tests.test_config_entries import FrozenDateTimeFactory
@@ -93,8 +92,8 @@ async def test_fetching_data(
assert hass.states.get("sensor.zurich_bern_line").state == "T10"
# Set new data and verify it
mock_opendata_client.connections = json.loads(
await async_load_fixture(hass, "connections.json", DOMAIN)
mock_opendata_client.connections = (
await async_load_json_array_fixture(hass, "connections.json", DOMAIN)
)[3:6]
freezer.tick(DEFAULT_UPDATE_TIME)
async_fire_time_changed(hass)
@@ -113,8 +112,8 @@ async def test_fetching_data(
# Recover and fetch new data again
mock_opendata_client.async_get_data.side_effect = None
mock_opendata_client.connections = json.loads(
await async_load_fixture(hass, "connections.json", DOMAIN)
mock_opendata_client.connections = (
await async_load_json_array_fixture(hass, "connections.json", DOMAIN)
)[6:9]
freezer.tick(DEFAULT_UPDATE_TIME)
async_fire_time_changed(hass)
@@ -1,6 +1,5 @@
"""Test the swiss_public_transport service."""
import json
import logging
from unittest.mock import AsyncMock, patch
@@ -27,7 +26,7 @@ from homeassistant.exceptions import HomeAssistantError, ServiceValidationError
from . import setup_integration
from tests.common import MockConfigEntry, async_load_fixture
from tests.common import MockConfigEntry, async_load_json_array_fixture
_LOGGER = logging.getLogger(__name__)
@@ -68,8 +67,8 @@ async def test_service_call_fetch_connections_success(
"homeassistant.components.swiss_public_transport.OpendataTransport",
return_value=AsyncMock(),
) as mock:
mock().connections = json.loads(
await async_load_fixture(hass, "connections.json", DOMAIN)
mock().connections = (
await async_load_json_array_fixture(hass, "connections.json", DOMAIN)
)[0 : data.get(ATTR_LIMIT, CONNECTIONS_COUNT) + 2]
await setup_integration(hass, config_entry)
@@ -136,8 +135,8 @@ async def test_service_call_fetch_connections_error(
"homeassistant.components.swiss_public_transport.OpendataTransport",
return_value=AsyncMock(),
) as mock:
mock().connections = json.loads(
await async_load_fixture(hass, "connections.json", DOMAIN)
mock().connections = await async_load_json_array_fixture(
hass, "connections.json", DOMAIN
)
await setup_integration(hass, config_entry)
@@ -178,8 +177,8 @@ async def test_service_call_load_unload(
"homeassistant.components.swiss_public_transport.OpendataTransport",
return_value=AsyncMock(),
) as mock:
mock().connections = json.loads(
await async_load_fixture(hass, "connections.json", DOMAIN)
mock().connections = await async_load_json_array_fixture(
hass, "connections.json", DOMAIN
)
await setup_integration(hass, config_entry)
@@ -1,6 +1,5 @@
"""Test the SwitchBee Smart Home config flow."""
import json
from unittest.mock import patch
import pytest
@@ -14,15 +13,15 @@ from homeassistant.data_entry_flow import FlowResultType
from . import MOCK_FAILED_TO_LOGIN_MSG, MOCK_INVALID_TOKEN_MGS
from tests.common import MockConfigEntry, async_load_fixture
from tests.common import MockConfigEntry, async_load_json_object_fixture
@pytest.mark.parametrize("test_cucode_in_coordinator_data", [False, True])
async def test_form(hass: HomeAssistant, test_cucode_in_coordinator_data) -> None:
"""Test we get the form."""
coordinator_data = json.loads(
await async_load_fixture(hass, "switchbee.json", DOMAIN)
coordinator_data = await async_load_json_object_fixture(
hass, "switchbee.json", DOMAIN
)
if test_cucode_in_coordinator_data:
@@ -140,8 +139,8 @@ async def test_form_unknown_error(hass: HomeAssistant) -> None:
async def test_form_entry_exists(hass: HomeAssistant) -> None:
"""Test we handle an already existing entry."""
coordinator_data = json.loads(
await async_load_fixture(hass, "switchbee.json", DOMAIN)
coordinator_data = await async_load_json_object_fixture(
hass, "switchbee.json", DOMAIN
)
MockConfigEntry(
unique_id="a8:21:08:e7:67:b6",
+2 -3
View File
@@ -1,7 +1,6 @@
"""Fixtures for Tedee integration tests."""
from collections.abc import Generator
import json
from unittest.mock import AsyncMock, MagicMock, patch
from aiotedee.models import TedeeBridge, TedeeLock
@@ -13,7 +12,7 @@ from homeassistant.core import HomeAssistant
from . import setup_integration
from tests.common import MockConfigEntry, load_fixture
from tests.common import MockConfigEntry, load_json_array_fixture
WEBHOOK_ID = "bq33efxmdi3vxy55q2wbnudbra7iv8mjrq9x0gea33g4zqtd87093pwveg8xcb33"
@@ -66,7 +65,7 @@ def mock_tedee() -> Generator[MagicMock]:
tedee.register_webhook.return_value = 1
tedee.delete_webhooks.return_value = None
locks_json = json.loads(load_fixture("locks.json", DOMAIN))
locks_json = load_json_array_fixture("locks.json", DOMAIN)
lock_list = [TedeeLock.from_dict(lock) for lock in locks_json]
tedee.locks_dict = {lock.id: lock for lock in lock_list}
+2 -3
View File
@@ -1,11 +1,10 @@
"""Configure py.test."""
import json
from unittest.mock import PropertyMock, patch
import pytest
from tests.common import load_fixture
from tests.common import load_json_object_fixture
@pytest.fixture(name="tomorrowio_config_flow_connect", autouse=True)
@@ -24,7 +23,7 @@ def tomorrowio_config_entry_update_fixture():
with (
patch(
"homeassistant.components.tomorrowio.TomorrowioV4.realtime_and_all_forecasts",
return_value=json.loads(load_fixture("v4.json", "tomorrowio")),
return_value=load_json_object_fixture("v4.json", "tomorrowio"),
) as mock_update,
patch(
"homeassistant.components.tomorrowio.TomorrowioV4.max_requests_per_day",
@@ -9,7 +9,7 @@ from tplink_omada_client.clients import OmadaWirelessClient
from homeassistant.components.tplink_omada.const import DOMAIN
from homeassistant.core import HomeAssistant
from tests.common import MockConfigEntry, async_load_fixture
from tests.common import MockConfigEntry, async_load_json_array_fixture
from tests.components.diagnostics import get_diagnostics_for_config_entry
from tests.typing import ClientSessionGenerator
@@ -21,8 +21,8 @@ async def test_entry_diagnostics(
snapshot: SnapshotAssertion,
) -> None:
"""Test config entry diagnostics payload and redaction."""
connected_clients_data = json.loads(
await async_load_fixture(hass, "connected-clients.json", DOMAIN)
connected_clients_data = await async_load_json_array_fixture(
hass, "connected-clients.json", DOMAIN
)
controller = init_integration.runtime_data
+7 -7
View File
@@ -19,7 +19,7 @@ from homeassistant.helpers.typing import UNDEFINED
from homeassistant.setup import async_setup_component
from homeassistant.util.uuid import random_uuid_hex
from tests.common import async_load_fixture
from tests.common import async_load_json_object_fixture
from tests.typing import WebSocketGenerator
@@ -452,8 +452,8 @@ async def test_restore_traces(
msg_id += 1
return msg_id
saved_traces = json.loads(
await async_load_fixture(hass, f"{domain}_saved_traces.json", "trace")
saved_traces = await async_load_json_object_fixture(
hass, f"{domain}_saved_traces.json", "trace"
)
hass_storage["trace.saved_traces"] = saved_traces
await _setup_automation_or_script(hass, domain, [])
@@ -633,8 +633,8 @@ async def test_restore_traces_overflow(
msg_id += 1
return msg_id
saved_traces = json.loads(
await async_load_fixture(hass, f"{domain}_saved_traces.json", "trace")
saved_traces = await async_load_json_object_fixture(
hass, f"{domain}_saved_traces.json", "trace"
)
hass_storage["trace.saved_traces"] = saved_traces
sun_config = {
@@ -716,8 +716,8 @@ async def test_restore_traces_late_overflow(
msg_id += 1
return msg_id
saved_traces = json.loads(
await async_load_fixture(hass, f"{domain}_saved_traces.json", "trace")
saved_traces = await async_load_json_object_fixture(
hass, f"{domain}_saved_traces.json", "trace"
)
hass_storage["trace.saved_traces"] = saved_traces
sun_config = {
+9 -10
View File
@@ -1,7 +1,6 @@
"""Tests for the YouTube integration."""
from collections.abc import AsyncGenerator
import json
from youtubeaio.models import YouTubeChannel, YouTubePlaylistItem, YouTubeSubscription
from youtubeaio.types import AuthScope
@@ -9,7 +8,7 @@ from youtubeaio.types import AuthScope
from homeassistant.components.youtube import DOMAIN
from homeassistant.core import HomeAssistant
from tests.common import async_load_fixture
from tests.common import async_load_json_object_fixture
class MockYouTube:
@@ -39,8 +38,8 @@ class MockYouTube:
async def get_user_channels(self) -> AsyncGenerator[YouTubeChannel]:
"""Get channels for authenticated user."""
channels = json.loads(
await async_load_fixture(self.hass, self._channel_fixture, DOMAIN)
channels = await async_load_json_object_fixture(
self.hass, self._channel_fixture, DOMAIN
)
for item in channels["items"]:
yield YouTubeChannel(**item)
@@ -51,8 +50,8 @@ class MockYouTube:
"""Get channels."""
if self._thrown_error is not None:
raise self._thrown_error
channels = json.loads(
await async_load_fixture(self.hass, self._channel_fixture, DOMAIN)
channels = await async_load_json_object_fixture(
self.hass, self._channel_fixture, DOMAIN
)
for item in channels["items"]:
yield YouTubeChannel(**item)
@@ -61,16 +60,16 @@ class MockYouTube:
self, playlist_id: str, amount: int
) -> AsyncGenerator[YouTubePlaylistItem]:
"""Get channels."""
channels = json.loads(
await async_load_fixture(self.hass, self._playlist_items_fixture, DOMAIN)
channels = await async_load_json_object_fixture(
self.hass, self._playlist_items_fixture, DOMAIN
)
for item in channels["items"]:
yield YouTubePlaylistItem(**item)
async def get_user_subscriptions(self) -> AsyncGenerator[YouTubeSubscription]:
"""Get channels for authenticated user."""
channels = json.loads(
await async_load_fixture(self.hass, self._subscriptions_fixture, DOMAIN)
channels = await async_load_json_object_fixture(
self.hass, self._subscriptions_fixture, DOMAIN
)
for item in channels["items"]:
yield YouTubeSubscription(**item)
+2 -3
View File
@@ -1,7 +1,6 @@
"""Fixtures for Zamg integration tests."""
from collections.abc import Generator
import json
from unittest.mock import MagicMock, patch
import pytest
@@ -10,7 +9,7 @@ from zamg import ZamgData as ZamgDevice
from homeassistant.components.zamg.const import CONF_STATION_ID, DOMAIN
from homeassistant.core import HomeAssistant
from tests.common import MockConfigEntry, load_fixture
from tests.common import MockConfigEntry, load_json_object_fixture
TEST_STATION_ID = "11240"
TEST_STATION_NAME = "Graz/Flughafen"
@@ -44,7 +43,7 @@ def mock_zamg_config_flow() -> Generator[MagicMock]:
) as zamg_mock:
zamg = zamg_mock.return_value
zamg.update.return_value = ZamgDevice(
json.loads(load_fixture("zamg/data.json"))
load_json_object_fixture("zamg/data.json")
)
zamg.get_data.return_value = zamg.get_data(TEST_STATION_ID)
yield zamg
+7 -3
View File
@@ -13,7 +13,11 @@ from homeassistant.helpers import entity_registry as er
from . import setup_integration
from tests.common import MockConfigEntry, async_load_fixture, snapshot_platform
from tests.common import (
MockConfigEntry,
async_load_json_object_fixture,
snapshot_platform,
)
async def test_all_entities(
@@ -36,8 +40,8 @@ async def test_max_output_when_unlocked(
mock_config_entry: MockConfigEntry,
) -> None:
"""Test max_output value stays within its own bound once output is unlocked."""
fixture_data = json.loads(
await async_load_fixture(hass, "current_state.json", DOMAIN)
fixture_data = await async_load_json_object_fixture(
hass, "current_state.json", DOMAIN
)
fixture_data["globalSettings"]["maxOutputUnlocked"] = True
mock_zinvolt_client.get_battery_status.return_value = BatteryState.from_json(
@@ -15,7 +15,7 @@ from homeassistant.components.zwave_js.scripts.convert_device_diagnostics_to_fix
main,
)
from tests.common import load_fixture
from tests.common import load_fixture, load_json_object_fixture
def _minify(text: str) -> str:
@@ -25,7 +25,7 @@ def _minify(text: str) -> str:
def test_fixture_functions() -> None:
"""Test functions related to the fixture."""
diagnostics_data = json.loads(load_fixture("zwave_js/device_diagnostics.json"))
diagnostics_data = load_json_object_fixture("zwave_js/device_diagnostics.json")
state = extract_fixture_data(copy.deepcopy(diagnostics_data))
assert isinstance(state["values"], list)
assert (
@@ -54,7 +54,7 @@ def test_load_file() -> None:
"""Test load file."""
assert load_file(
Path(__file__).parents[1] / "fixtures" / "device_diagnostics.json"
) == json.loads(load_fixture("zwave_js/device_diagnostics.json"))
) == load_json_object_fixture("zwave_js/device_diagnostics.json")
def test_main(capfd: pytest.CaptureFixture[str]) -> None: