File: test_include_parameter.py

package info (click to toggle)
python-bsblan 4.2.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 1,196 kB
  • sloc: python: 6,864; makefile: 3
file content (575 lines) | stat: -rw-r--r-- 19,746 bytes parent folder | download
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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
"""Tests for the include parameter in fetch methods."""

# pylint: disable=duplicate-code
# pylint: disable=protected-access
# pylint: disable=too-many-arguments

from __future__ import annotations

import json
from typing import Any
from unittest.mock import AsyncMock

import aiohttp
import pytest

from bsblan import BSBLAN, BSBLANConfig, State, StaticState
from bsblan.constants import (
    API_V3,
    EMPTY_INCLUDE_LIST_ERROR_MSG,
    INVALID_INCLUDE_PARAMS_ERROR_MSG,
)
from bsblan.exceptions import BSBLANError
from bsblan.utility import APIValidator

from . import load_fixture

# ========== Parametrized tests for section-based methods ==========


@pytest.mark.asyncio
@pytest.mark.parametrize(
    ("method_name", "section", "test_params"),
    [
        ("state", "heating", {"include": "hvac_mode", "param_id": "700"}),
        ("sensor", "sensor", {"include": "outside_temperature", "param_id": "8700"}),
        ("info", "device", {"include": "device_identification", "param_id": "6224"}),
    ],
    ids=["state", "sensor", "info"],
)
async def test_section_method_with_include_single_param(
    monkeypatch: Any,
    method_name: str,
    section: str,
    test_params: dict[str, str],
) -> None:
    """Test section methods with a single parameter in include list."""
    include_param = test_params["include"]
    param_id = test_params["param_id"]

    async with aiohttp.ClientSession() as session:
        config = BSBLANConfig(host="example.com")
        bsblan = BSBLAN(config, session=session)

        monkeypatch.setattr(bsblan, "_firmware_version", "1.0.38-20200730234859")
        monkeypatch.setattr(bsblan, "_api_version", "v3")
        monkeypatch.setattr(bsblan, "_api_data", API_V3)

        api_validator = APIValidator(API_V3)
        api_validator.validated_sections.add(section)
        bsblan._api_validator = api_validator

        # Load appropriate fixture based on method
        fixture_map = {
            "state": "state.json",
            "sensor": "sensor.json",
            "info": "info.json",
        }
        fixture_data = json.loads(load_fixture(fixture_map[method_name]))
        partial_response = {param_id: fixture_data[param_id]}

        request_mock: AsyncMock = AsyncMock(return_value=partial_response)
        monkeypatch.setattr(bsblan, "_request", request_mock)

        # Get the method and call it
        method = getattr(bsblan, method_name)
        result = await method(include=[include_param])

        # Verify correct parameter was requested
        request_mock.assert_awaited_once()
        call_args = request_mock.call_args
        assert call_args.kwargs["params"]["Parameter"] == param_id

        # Verify the attribute is populated
        assert getattr(result, include_param) is not None


@pytest.mark.asyncio
@pytest.mark.parametrize(
    ("method_name", "section"),
    [
        ("state", "heating"),
        ("sensor", "sensor"),
        ("static_values", "staticValues"),
        ("info", "device"),
    ],
    ids=["state", "sensor", "static_values", "info"],
)
async def test_section_method_with_empty_include_list(
    monkeypatch: Any,
    method_name: str,
    section: str,
) -> None:
    """Test section methods with empty include list raises specific error."""
    async with aiohttp.ClientSession() as session:
        config = BSBLANConfig(host="example.com")
        bsblan = BSBLAN(config, session=session)

        monkeypatch.setattr(bsblan, "_firmware_version", "1.0.38-20200730234859")
        monkeypatch.setattr(bsblan, "_api_version", "v3")
        monkeypatch.setattr(bsblan, "_api_data", API_V3)

        api_validator = APIValidator(API_V3)
        api_validator.validated_sections.add(section)
        bsblan._api_validator = api_validator

        request_mock: AsyncMock = AsyncMock()
        monkeypatch.setattr(bsblan, "_request", request_mock)

        method = getattr(bsblan, method_name)
        with pytest.raises(BSBLANError) as exc_info:
            await method(include=[])

        assert str(exc_info.value) == EMPTY_INCLUDE_LIST_ERROR_MSG
        request_mock.assert_not_awaited()


@pytest.mark.asyncio
@pytest.mark.parametrize(
    ("method_name", "section"),
    [
        ("state", "heating"),
        ("sensor", "sensor"),
        ("static_values", "staticValues"),
        ("info", "device"),
    ],
    ids=["state", "sensor", "static_values", "info"],
)
async def test_section_method_with_invalid_params(
    monkeypatch: Any,
    method_name: str,
    section: str,
) -> None:
    """Test section methods with all invalid parameters raises error."""
    async with aiohttp.ClientSession() as session:
        config = BSBLANConfig(host="example.com")
        bsblan = BSBLAN(config, session=session)

        monkeypatch.setattr(bsblan, "_firmware_version", "1.0.38-20200730234859")
        monkeypatch.setattr(bsblan, "_api_version", "v3")
        monkeypatch.setattr(bsblan, "_api_data", API_V3)

        api_validator = APIValidator(API_V3)
        api_validator.validated_sections.add(section)
        bsblan._api_validator = api_validator

        request_mock: AsyncMock = AsyncMock()
        monkeypatch.setattr(bsblan, "_request", request_mock)

        method = getattr(bsblan, method_name)
        with pytest.raises(BSBLANError) as exc_info:
            await method(include=["nonexistent_param"])

        assert str(exc_info.value) == INVALID_INCLUDE_PARAMS_ERROR_MSG
        request_mock.assert_not_awaited()


# ========== Tests for _validate_api_section with include parameter ==========


@pytest.mark.asyncio
async def test_validate_api_section_with_include_filter(monkeypatch: Any) -> None:
    """Test _validate_api_section filters params when include is specified."""
    async with aiohttp.ClientSession() as session:
        config = BSBLANConfig(host="example.com")
        bsblan = BSBLAN(config, session=session)

        monkeypatch.setattr(bsblan, "_firmware_version", "1.0.38-20200730234859")
        monkeypatch.setattr(bsblan, "_api_version", "v3")

        # Set up API data with multiple params
        api_data = {
            "heating": {
                "700": "hvac_mode",
                "710": "target_temperature",
                "8740": "current_temperature",
            },
            "sensor": {},
            "staticValues": {},
            "device": {},
            "hot_water": {},
        }
        bsblan._api_data = api_data  # type: ignore[assignment]

        api_validator = APIValidator(api_data)
        bsblan._api_validator = api_validator

        # Mock request to return only the filtered param
        request_mock = AsyncMock(
            return_value={"700": {"value": "1", "unit": "", "desc": "Auto"}}
        )
        monkeypatch.setattr(bsblan, "_request", request_mock)

        # Validate with include filter - should only request hvac_mode
        result = await bsblan._validate_api_section("heating", include=["hvac_mode"])

        # Verify only filtered param was requested
        request_mock.assert_awaited_once()
        call_args = request_mock.call_args
        assert call_args.kwargs["params"]["Parameter"] == "700"

        # Result should contain the response data
        assert result is not None
        assert "700" in result


@pytest.mark.asyncio
async def test_validate_section_skips_params_not_in_include() -> None:
    """Test validate_section skips params not in include list."""
    # Set up API config with multiple params
    api_config = {
        "heating": {
            "700": "hvac_mode",
            "710": "target_temperature",
            "8740": "current_temperature",
        },
    }

    api_validator = APIValidator(api_config)

    # Mock request data with only one param (simulating filtered response)
    request_data = {"700": {"value": "1", "unit": "", "desc": "Auto"}}

    # Validate with include filter - should skip params not in include
    api_validator.validate_section("heating", request_data, include=["hvac_mode"])

    # Section should be validated
    assert api_validator.is_section_validated("heating")

    # hvac_mode (700) should still be in config since it was valid
    # Other params should NOT be removed since they weren't in include
    assert "700" in api_validator.api_config["heating"]
    # 710 and 8740 were not validated (skipped), so they remain
    assert "710" in api_validator.api_config["heating"]
    assert "8740" in api_validator.api_config["heating"]


# ========== Additional state() specific tests ==========


@pytest.mark.asyncio
async def test_state_with_include_multiple_params(monkeypatch: Any) -> None:
    """Test state() with multiple parameters in include list."""
    async with aiohttp.ClientSession() as session:
        config = BSBLANConfig(host="example.com")
        bsblan = BSBLAN(config, session=session)

        monkeypatch.setattr(bsblan, "_firmware_version", "1.0.38-20200730234859")
        monkeypatch.setattr(bsblan, "_api_version", "v3")
        monkeypatch.setattr(bsblan, "_api_data", API_V3)

        api_validator = APIValidator(API_V3)
        api_validator.validated_sections.add("heating")
        bsblan._api_validator = api_validator

        state_data = json.loads(load_fixture("state.json"))
        partial_response = {
            "700": state_data["700"],
            "8740": state_data["8740"],
        }

        request_mock: AsyncMock = AsyncMock(return_value=partial_response)
        monkeypatch.setattr(bsblan, "_request", request_mock)

        state: State = await bsblan.state(include=["hvac_mode", "current_temperature"])

        assert state.hvac_mode is not None
        assert state.hvac_mode.value == 3
        assert state.current_temperature is not None
        assert state.current_temperature.value == 19.3


@pytest.mark.asyncio
async def test_state_with_include_mixed_valid_invalid_params(monkeypatch: Any) -> None:
    """Test state() with mixed valid and invalid parameters.

    Documents intended behavior: valid params are fetched, invalid ones filtered out.
    """
    async with aiohttp.ClientSession() as session:
        config = BSBLANConfig(host="example.com")
        bsblan = BSBLAN(config, session=session)

        monkeypatch.setattr(bsblan, "_firmware_version", "1.0.38-20200730234859")
        monkeypatch.setattr(bsblan, "_api_version", "v3")
        monkeypatch.setattr(bsblan, "_api_data", API_V3)

        api_validator = APIValidator(API_V3)
        api_validator.validated_sections.add("heating")
        bsblan._api_validator = api_validator

        state_data = json.loads(load_fixture("state.json"))
        partial_response = {"700": state_data["700"]}

        request_mock: AsyncMock = AsyncMock(return_value=partial_response)
        monkeypatch.setattr(bsblan, "_request", request_mock)

        state: State = await bsblan.state(
            include=["hvac_mode", "nonexistent_param", "another_invalid"]
        )

        # Verify only valid parameter was requested
        call_args = request_mock.call_args
        assert call_args.kwargs["params"]["Parameter"] == "700"

        assert state.hvac_mode is not None
        assert state.hvac_mode.value == 3
        assert state.target_temperature is None


@pytest.mark.asyncio
async def test_state_without_include(monkeypatch: Any) -> None:
    """Test state() without include parameter fetches all params."""
    async with aiohttp.ClientSession() as session:
        config = BSBLANConfig(host="example.com")
        bsblan = BSBLAN(config, session=session)

        monkeypatch.setattr(bsblan, "_firmware_version", "1.0.38-20200730234859")
        monkeypatch.setattr(bsblan, "_api_version", "v3")
        monkeypatch.setattr(bsblan, "_api_data", API_V3)

        api_validator = APIValidator(API_V3)
        api_validator.validated_sections.add("heating")
        bsblan._api_validator = api_validator

        request_mock: AsyncMock = AsyncMock(
            return_value=json.loads(load_fixture("state.json"))
        )
        monkeypatch.setattr(bsblan, "_request", request_mock)

        state: State = await bsblan.state()

        assert state.hvac_mode is not None
        assert state.target_temperature is not None
        assert state.current_temperature is not None


# ========== Tests for static_values() with include ==========


@pytest.mark.asyncio
async def test_static_values_with_include(monkeypatch: Any) -> None:
    """Test static_values() with include parameter."""
    async with aiohttp.ClientSession() as session:
        config = BSBLANConfig(host="example.com")
        bsblan = BSBLAN(config, session=session)

        monkeypatch.setattr(bsblan, "_firmware_version", "1.0.38-20200730234859")
        monkeypatch.setattr(bsblan, "_api_version", "v3")
        monkeypatch.setattr(bsblan, "_api_data", API_V3)

        api_validator = APIValidator(API_V3)
        api_validator.validated_sections.add("staticValues")
        bsblan._api_validator = api_validator

        partial_response = {
            "714": {
                "name": "Min temp",
                "unit": "°C",
                "desc": "",
                "value": "8.0",
                "dataType": 0,
                "error": 0,
                "readonly": 0,
                "readwrite": 0,
            },
        }

        request_mock: AsyncMock = AsyncMock(return_value=partial_response)
        monkeypatch.setattr(bsblan, "_request", request_mock)

        static: StaticState = await bsblan.static_values(include=["min_temp"])

        assert static.min_temp is not None
        assert static.max_temp is None


# ========== Parametrized tests for hot water methods ==========


@pytest.mark.asyncio
@pytest.mark.parametrize(
    ("method_name", "group_name", "test_params"),
    [
        (
            "hot_water_state",
            "essential",
            {
                "param_cache": {"1600": "operating_mode", "1610": "nominal_setpoint"},
                "include_param": "operating_mode",
                "param_id": "1600",
            },
        ),
        (
            "hot_water_config",
            "config",
            {
                "param_cache": {
                    "1645": "legionella_function_setpoint",
                    "1640": "legionella_function",
                },
                "include_param": "legionella_function_setpoint",
                "param_id": "1645",
            },
        ),
        (
            "hot_water_schedule",
            "schedule",
            {
                "param_cache": {
                    "561": "dhw_time_program_monday",
                    "562": "dhw_time_program_tuesday",
                },
                "include_param": "dhw_time_program_monday",
                "param_id": "561",
            },
        ),
    ],
    ids=["hot_water_state", "hot_water_config", "hot_water_schedule"],
)
async def test_hot_water_method_with_include(
    monkeypatch: Any,
    method_name: str,
    group_name: str,
    test_params: dict[str, Any],
) -> None:
    """Test hot water methods with include parameter."""
    param_cache = test_params["param_cache"]
    include_param = test_params["include_param"]
    param_id = test_params["param_id"]

    async with aiohttp.ClientSession() as session:
        config = BSBLANConfig(host="example.com")
        bsblan = BSBLAN(config, session=session)

        monkeypatch.setattr(bsblan, "_firmware_version", "1.0.38-20200730234859")
        monkeypatch.setattr(bsblan, "_api_version", "v3")
        monkeypatch.setattr(bsblan, "_api_data", API_V3)

        monkeypatch.setattr(bsblan, "_hot_water_param_cache", param_cache)
        bsblan._validated_hot_water_groups.add(group_name)

        # Create mock response
        mock_response = {
            param_id: {
                "name": include_param,
                "value": "1",
                "unit": "",
                "desc": "",
                "dataType": 0,
                "error": 0,
                "readonly": 0,
                "readwrite": 0,
            },
        }

        request_mock: AsyncMock = AsyncMock(return_value=mock_response)
        monkeypatch.setattr(bsblan, "_request", request_mock)

        method = getattr(bsblan, method_name)
        await method(include=[include_param])

        request_mock.assert_awaited_once()
        call_args = request_mock.call_args
        assert call_args.kwargs["params"]["Parameter"] == param_id


@pytest.mark.asyncio
@pytest.mark.parametrize(
    ("method_name", "group_name", "param_cache"),
    [
        (
            "hot_water_state",
            "essential",
            {"1600": "operating_mode", "1610": "nominal_setpoint"},
        ),
        (
            "hot_water_config",
            "config",
            {"1645": "legionella_function_setpoint"},
        ),
        (
            "hot_water_schedule",
            "schedule",
            {"561": "dhw_time_program_monday"},
        ),
    ],
    ids=["hot_water_state", "hot_water_config", "hot_water_schedule"],
)
async def test_hot_water_method_with_empty_include_list(
    monkeypatch: Any,
    method_name: str,
    group_name: str,
    param_cache: dict[str, str],
) -> None:
    """Test hot water methods with empty include list raises error."""
    async with aiohttp.ClientSession() as session:
        config = BSBLANConfig(host="example.com")
        bsblan = BSBLAN(config, session=session)

        monkeypatch.setattr(bsblan, "_firmware_version", "1.0.38-20200730234859")
        monkeypatch.setattr(bsblan, "_api_version", "v3")
        monkeypatch.setattr(bsblan, "_api_data", API_V3)

        monkeypatch.setattr(bsblan, "_hot_water_param_cache", param_cache)
        bsblan._validated_hot_water_groups.add(group_name)

        request_mock: AsyncMock = AsyncMock()
        monkeypatch.setattr(bsblan, "_request", request_mock)

        method = getattr(bsblan, method_name)
        with pytest.raises(BSBLANError) as exc_info:
            await method(include=[])

        assert str(exc_info.value) == EMPTY_INCLUDE_LIST_ERROR_MSG
        request_mock.assert_not_awaited()


@pytest.mark.asyncio
@pytest.mark.parametrize(
    ("method_name", "group_name", "param_cache"),
    [
        (
            "hot_water_state",
            "essential",
            {"1600": "operating_mode", "1610": "nominal_setpoint"},
        ),
        (
            "hot_water_config",
            "config",
            {"1645": "legionella_function_setpoint"},
        ),
        (
            "hot_water_schedule",
            "schedule",
            {"561": "dhw_time_program_monday"},
        ),
    ],
    ids=["hot_water_state", "hot_water_config", "hot_water_schedule"],
)
async def test_hot_water_method_with_invalid_params(
    monkeypatch: Any,
    method_name: str,
    group_name: str,
    param_cache: dict[str, str],
) -> None:
    """Test hot water methods with all invalid parameters raises error."""
    async with aiohttp.ClientSession() as session:
        config = BSBLANConfig(host="example.com")
        bsblan = BSBLAN(config, session=session)

        monkeypatch.setattr(bsblan, "_firmware_version", "1.0.38-20200730234859")
        monkeypatch.setattr(bsblan, "_api_version", "v3")
        monkeypatch.setattr(bsblan, "_api_data", API_V3)

        monkeypatch.setattr(bsblan, "_hot_water_param_cache", param_cache)
        bsblan._validated_hot_water_groups.add(group_name)

        request_mock: AsyncMock = AsyncMock()
        monkeypatch.setattr(bsblan, "_request", request_mock)

        method = getattr(bsblan, method_name)
        with pytest.raises(BSBLANError) as exc_info:
            await method(include=["nonexistent_param"])

        assert str(exc_info.value) == INVALID_INCLUDE_PARAMS_ERROR_MSG
        request_mock.assert_not_awaited()