1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
|
"""Tests for BSBLAN initialization methods."""
# file deepcode ignore W0212: this is a testfile
# pylint: disable=protected-access
import json
from typing import Any
from unittest.mock import MagicMock
import aiohttp
import pytest
from aresponses import ResponsesMockServer
from bsblan import BSBLAN
from bsblan.bsblan import BSBLANConfig
from bsblan.constants import (
API_VERSION_ERROR_MSG,
)
from bsblan.exceptions import BSBLANError
@pytest.mark.asyncio
async def test_initialize_api_data_v1(aresponses: ResponsesMockServer) -> None:
"""Test initialization of API data with v1 version."""
# Mock the device config endpoint for v1
aresponses.add(
"example.com",
"/JQ",
"POST",
aresponses.Response(
status=200,
headers={"Content-Type": "application/json"},
text=json.dumps(
{
"Brötje": {
"5870": "Some Parameter",
}
}
),
),
)
async with aiohttp.ClientSession() as session:
bsblan = BSBLAN(BSBLANConfig(host="example.com"), session=session)
bsblan._api_version = "v1"
await bsblan._initialize_api_data()
# Verify API data was initialized
assert bsblan._api_data is not None
@pytest.mark.asyncio
async def test_initialize_api_data_v3(aresponses: ResponsesMockServer) -> None:
"""Test initialization of API data with v3 version."""
# Mock the device info endpoint for v3
aresponses.add(
"example.com",
"/JQ",
"POST",
aresponses.Response(
status=200,
headers={"Content-Type": "application/json"},
text=json.dumps(
{
"knownDevices": {
"0": {
"device": "Test Device",
"family": "123",
"type": "456",
"var": "789",
}
}
}
),
),
)
async with aiohttp.ClientSession() as session:
bsblan = BSBLAN(BSBLANConfig(host="example.com"), session=session)
bsblan._api_version = "v3"
await bsblan._initialize_api_data()
# Verify API data was initialized
assert bsblan._api_data is not None
@pytest.mark.asyncio
async def test_api_version_error() -> None:
"""Test error when API version is not set."""
async with aiohttp.ClientSession() as session:
bsblan = BSBLAN(BSBLANConfig(host="example.com"), session=session)
# Force api_version to None to test error condition
bsblan._api_version = None
with pytest.raises(BSBLANError, match=API_VERSION_ERROR_MSG):
await bsblan._initialize_api_data()
@pytest.mark.asyncio
async def test_context_manager(aresponses: ResponsesMockServer) -> None:
"""Test the context manager functionality."""
# Mock the API responses to enable a successful initialization
aresponses.add(
"example.com",
"/JC",
"GET",
aresponses.Response(
status=200,
headers={"Content-Type": "application/json"},
text=json.dumps({"version": "1.0"}),
),
)
# Mock a simple success response for any remaining API calls
aresponses.add(
"example.com",
"/JQ",
"POST",
aresponses.Response(
status=200,
headers={"Content-Type": "application/json"},
text=json.dumps({"success": True}),
),
repeat=True,
)
# Patch the initialize method
original_initialize = BSBLAN.initialize
try:
async def mock_initialize(self: BSBLAN) -> None:
self._initialized = True
BSBLAN.initialize = mock_initialize # type: ignore[method-assign]
# Now test the context manager
async with BSBLAN(BSBLANConfig(host="example.com")) as bsblan:
assert bsblan.session is not None
assert bsblan._close_session is True
finally:
# Restore the original method
BSBLAN.initialize = original_initialize
@pytest.mark.asyncio
async def test_initialize_with_session(aresponses: ResponsesMockServer) -> None:
"""Test initialize method with existing session."""
# Mock responses
aresponses.add(
"example.com",
"/JC",
"GET",
aresponses.Response(
status=200,
headers={"Content-Type": "application/json"},
text=json.dumps({"version": "1.0"}),
),
)
aresponses.add(
"example.com",
"/JQ",
"POST",
aresponses.Response(
status=200,
headers={"Content-Type": "application/json"},
text=json.dumps({"success": True}),
),
repeat=True,
)
async with aiohttp.ClientSession() as session:
bsblan = BSBLAN(BSBLANConfig(host="example.com"), session=session)
# Save original methods
original_fetch_firmware = bsblan._fetch_firmware_version
original_setup_validator = bsblan._setup_api_validator
try:
# Replace with async mock functions
async def mock_fetch_firmware() -> None:
pass
async def mock_setup_validator() -> None:
pass
bsblan._fetch_firmware_version = mock_fetch_firmware # type: ignore[method-assign]
bsblan._setup_api_validator = mock_setup_validator # type: ignore[method-assign]
await bsblan.initialize()
assert bsblan._initialized is True
assert bsblan._close_session is False
finally:
# Restore original methods
bsblan._fetch_firmware_version = original_fetch_firmware # type: ignore[method-assign]
bsblan._setup_api_validator = original_setup_validator # type: ignore[method-assign]
@pytest.mark.asyncio
async def test_initialize_api_validator() -> None:
"""Test initialize_api_validator method."""
async with aiohttp.ClientSession() as session:
bsblan = BSBLAN(BSBLANConfig(host="example.com"), session=session)
bsblan._api_version = "v3"
bsblan._api_data = {
"heating": {},
"sensor": {},
"staticValues": {},
"device": {},
"hot_water": {},
}
# Create a coroutine mock for _validate_api_section that returns response data
async def mock_validate_section(section: str) -> dict[str, Any]:
# Return mock response for heating to trigger temperature extraction
if section == "heating":
return {
"710": {
"name": "Target Temperature",
"value": "20.0",
"unit": "°C",
}
}
return {}
bsblan._validate_api_section = mock_validate_section # type: ignore[method-assign]
await bsblan._initialize_api_validator()
assert bsblan._api_validator is not None
# Verify temperature unit was extracted from heating section
assert bsblan._temperature_unit == "°C"
@pytest.mark.asyncio
async def test_initialize_already_initialized() -> None:
"""Test that initialize() is a no-op when already initialized."""
async with aiohttp.ClientSession() as session:
bsblan = BSBLAN(BSBLANConfig(host="example.com"), session=session)
# Mark as already initialized
bsblan._initialized = True
# Track if _fetch_firmware_version is called
fetch_called = False
async def mock_fetch() -> None:
nonlocal fetch_called
fetch_called = True
bsblan._fetch_firmware_version = mock_fetch # type: ignore[method-assign]
# Should not call _fetch_firmware_version since already initialized
await bsblan.initialize()
assert not fetch_called
assert bsblan._initialized is True
@pytest.mark.asyncio
async def test_fetch_firmware_version_already_set() -> None:
"""Test that _fetch_firmware_version skips when version already set."""
async with aiohttp.ClientSession() as session:
bsblan = BSBLAN(BSBLANConfig(host="example.com"), session=session)
# Pre-set firmware version
bsblan._firmware_version = "3.0.0"
# Track if device() is called
device_called = False
async def mock_device() -> Any:
nonlocal device_called
device_called = True
return MagicMock(version="3.0.0")
bsblan.device = mock_device # type: ignore[method-assign]
# Should not call device() since version already set
await bsblan._fetch_firmware_version()
assert not device_called
assert bsblan._firmware_version == "3.0.0"
|