-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathtest_models.py
More file actions
680 lines (586 loc) · 25.3 KB
/
test_models.py
File metadata and controls
680 lines (586 loc) · 25.3 KB
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
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
"""Unit tests for models (Device, State and States helpers)."""
from __future__ import annotations
import json
from pathlib import Path
import pytest
from pyoverkiz._case import decamelize
from pyoverkiz.enums import DataType, Protocol
from pyoverkiz.models import (
CommandDefinitions,
Definition,
Device,
EventState,
Setup,
State,
StateDefinition,
States,
)
from pyoverkiz.obfuscate import obfuscate_id
RAW_STATES = [
{"name": "core:NameState", "type": 3, "value": "alarm name"},
{"name": "internal:CurrentAlarmModeState", "type": 3, "value": "off"},
{"name": "internal:AlarmDelayState", "type": 1, "value": 60},
]
RAW_DEVICES = {
"creationTime": 1495389504000,
"lastUpdateTime": 1495389504000,
"label": "roller shutter 1",
"deviceURL": "io://1234-5678-9012/10077486",
"shortcut": False,
"controllableName": "io:RollerShutterGenericIOComponent",
"definition": {
"commands": [
{"commandName": "close", "nparams": 0},
{"commandName": "open", "nparams": 0},
],
"states": [
{"type": "ContinuousState", "qualifiedName": "core:ClosureState"},
{
"type": "DiscreteState",
"values": ["good", "low", "normal", "verylow"],
"qualifiedName": "core:DiscreteRSSILevelState",
},
{
"type": "ContinuousState",
"qualifiedName": "core:Memorized1PositionState",
},
],
"dataProperties": [{"value": "500", "qualifiedName": "core:identifyInterval"}],
"widgetName": "PositionableRollerShutter",
"uiProfiles": [
"StatefulCloseableShutter",
"Closeable",
],
"uiClass": "RollerShutter",
"qualifiedName": "io:RollerShutterGenericIOComponent",
"type": "ACTUATOR",
},
"states": [
{"name": "core:StatusState", "type": 3, "value": "available"},
{"name": "core:DiscreteRSSILevelState", "type": 3, "value": "good"},
{"name": "core:ClosureState", "type": 1, "value": 100},
],
"available": True,
"enabled": True,
"placeOID": "28750a0f-79c0-4815-8c52-fac9de92a0e1",
"widget": "PositionableRollerShutter",
"type": 1,
"oid": "ebca1376-5a33-4d2b-85b6-df73220687a2",
"uiClass": "RollerShutter",
}
STATE = "core:NameState"
FIXTURES_DIR = Path(__file__).resolve().parent / "fixtures" / "setup"
class TestSetup:
"""Tests for setup-level ID parsing and redaction behavior."""
def test_id_is_raw_but_repr_is_redacted_when_present(self):
"""When API provides `id`, keep raw value but redact it in repr output."""
raw_setup = json.loads(
(FIXTURES_DIR / "setup_tahoma_1.json").read_text(encoding="utf-8")
)
setup = Setup(**decamelize(raw_setup))
raw_id = "SETUP-1234-1234-8044"
redacted_id = obfuscate_id(raw_id)
assert setup.id == raw_id
assert redacted_id in repr(setup)
assert raw_id not in repr(setup)
def test_id_is_none_when_missing(self):
"""When API omits `id`, setup.id should stay None."""
raw_setup = json.loads(
(FIXTURES_DIR / "setup_local.json").read_text(encoding="utf-8")
)
setup = Setup(**decamelize(raw_setup))
assert setup.id is None
def test_id_is_none_without_input_id(self):
"""Constructing setup without an id keeps setup.id as None."""
setup = Setup(gateways=[], devices=[])
assert setup.id is None
class TestDevice:
"""Tests for Device model parsing and property extraction."""
@pytest.mark.parametrize(
(
"device_url",
"protocol",
"gateway_id",
"device_address",
"subsystem_id",
"is_sub_device",
),
[
(
"io://1234-5678-9012/10077486",
Protocol.IO,
"1234-5678-9012",
"10077486",
None,
False,
),
(
"io://1234-5678-9012/10077486#8",
Protocol.IO,
"1234-5678-9012",
"10077486",
8,
True,
),
(
"hue://1234-1234-4411/001788676dde/lights/10",
Protocol.HUE,
"1234-1234-4411",
"001788676dde/lights/10",
None,
False,
),
(
"hue://1234-1234-4411/001788676dde/lights/10#5",
Protocol.HUE,
"1234-1234-4411",
"001788676dde/lights/10",
5,
True,
),
(
"upnpcontrol://1234-1234-4411/uuid:RINCON_000E586B571601400",
Protocol.UPNP_CONTROL,
"1234-1234-4411",
"uuid:RINCON_000E586B571601400",
None,
False,
),
(
"upnpcontrol://1234-1234-4411/uuid:RINCON_000E586B571601400#7",
Protocol.UPNP_CONTROL,
"1234-1234-4411",
"uuid:RINCON_000E586B571601400",
7,
True,
),
(
"zigbee://1234-1234-1234/9876/1",
Protocol.ZIGBEE,
"1234-1234-1234",
"9876/1",
None,
False,
),
(
"zigbee://1234-1234-1234/9876/1#2",
Protocol.ZIGBEE,
"1234-1234-1234",
"9876/1",
2,
True,
),
(
"eliot://ELIOT-000000000000000000000000000ABCDE/00000000000000000000000000125abc",
Protocol.ELIOT,
"ELIOT-000000000000000000000000000ABCDE",
"00000000000000000000000000125abc",
None,
False,
),
(
"eliot://ELIOT-000000000000000000000000000ABCDE/00000000000000000000000000125abc#1",
Protocol.ELIOT,
"ELIOT-000000000000000000000000000ABCDE",
"00000000000000000000000000125abc",
1,
False,
),
],
)
def test_base_url_parsing(
self,
device_url: str,
protocol: Protocol,
gateway_id: str,
device_address: str,
subsystem_id: int | None,
is_sub_device: bool,
):
"""Ensure device URL parsing extracts protocol, gateway and address correctly."""
test_device = {
**RAW_DEVICES,
"deviceURL": device_url,
}
device_data = decamelize(test_device)
device = Device(**device_data)
assert device.identifier.protocol == protocol
assert device.identifier.gateway_id == gateway_id
assert device.identifier.device_address == device_address
assert device.identifier.subsystem_id == subsystem_id
assert device.identifier.is_sub_device == is_sub_device
@pytest.mark.parametrize(
"device_url",
[
"foo://whatever",
"io://1234-5678-9012/10077486#8 trailing",
],
)
def test_invalid_device_url_raises(self, device_url: str):
"""Invalid device URLs should raise during identifier parsing."""
test_device = {
**RAW_DEVICES,
"deviceURL": device_url,
}
device_data = decamelize(test_device)
with pytest.raises(ValueError, match="Invalid device URL"):
Device(**device_data)
def test_none_states(self):
"""Devices without a `states` field should provide an empty States object."""
device_data = decamelize(RAW_DEVICES)
del device_data["states"]
device = Device(**device_data)
assert not device.states.get(STATE)
def test_select_first_command(self):
"""Device.select_first_command() returns first supported command from list."""
device_data = decamelize(RAW_DEVICES)
device = Device(**device_data)
assert device.select_first_command(["nonexistent", "open", "close"]) == "open"
assert device.select_first_command(["nonexistent"]) is None
def test_supports_command(self):
"""Device.supports_command() checks if device supports a single command."""
device_data = decamelize(RAW_DEVICES)
device = Device(**device_data)
assert device.supports_command("open")
assert not device.supports_command("nonexistent")
def test_supports_any_command(self):
"""Device.supports_any_command() checks if device supports any command."""
device_data = decamelize(RAW_DEVICES)
device = Device(**device_data)
assert device.supports_any_command(["nonexistent", "open"])
assert not device.supports_any_command(["nonexistent"])
def test_get_state_value(self):
"""Device.get_state_value() returns value of a single state."""
device_data = decamelize(RAW_DEVICES)
device = Device(**device_data)
value = device.get_state_value("core:ClosureState")
assert value == 100
assert device.get_state_value("nonexistent") is None
def test_select_first_state_value(self):
"""Device.select_first_state_value() returns value of first matching state from list."""
device_data = decamelize(RAW_DEVICES)
device = Device(**device_data)
value = device.select_first_state_value(["nonexistent", "core:ClosureState"])
assert value == 100
def test_has_state_value(self):
"""Device.has_state_value() checks if a single state exists with non-None value."""
device_data = decamelize(RAW_DEVICES)
device = Device(**device_data)
assert device.has_state_value("core:ClosureState")
assert not device.has_state_value("nonexistent")
def test_has_any_state_value(self):
"""Device.has_any_state_value() checks if any state exists with non-None value."""
device_data = decamelize(RAW_DEVICES)
device = Device(**device_data)
assert device.has_any_state_value(["nonexistent", "core:ClosureState"])
assert not device.has_any_state_value(["nonexistent"])
def test_get_state_definition(self):
"""Device.get_state_definition() returns StateDefinition for a single state."""
device_data = decamelize(RAW_DEVICES)
device = Device(**device_data)
state_def = device.get_state_definition("core:ClosureState")
assert state_def is not None
assert state_def.qualified_name == "core:ClosureState"
assert device.get_state_definition("nonexistent") is None
def test_select_first_state_definition(self):
"""Device.select_first_state_definition() returns first matching StateDefinition from list."""
device_data = decamelize(RAW_DEVICES)
device = Device(**device_data)
state_def = device.select_first_state_definition(
["nonexistent", "core:ClosureState"]
)
assert state_def is not None
assert state_def.qualified_name == "core:ClosureState"
def test_get_attribute_value(self):
"""Device.get_attribute_value() returns value of a single attribute."""
test_device = {
**RAW_DEVICES,
"attributes": [
{"name": "core:Manufacturer", "type": 3, "value": "VELUX"},
{"name": "core:Model", "type": 3, "value": "WINDOW 100"},
],
}
device_data = decamelize(test_device)
device = Device(**device_data)
value = device.get_attribute_value("core:Model")
assert value == "WINDOW 100"
assert device.get_attribute_value("nonexistent") is None
def test_select_first_attribute_value_returns_first_match(self):
"""Device.select_first_attribute_value() returns value of first matching attribute from list."""
test_device = {
**RAW_DEVICES,
"attributes": [
{"name": "core:Manufacturer", "type": 3, "value": "VELUX"},
{"name": "core:Model", "type": 3, "value": "WINDOW 100"},
],
}
device_data = decamelize(test_device)
device = Device(**device_data)
value = device.select_first_attribute_value(
["nonexistent", "core:Model", "core:Manufacturer"]
)
assert value == "WINDOW 100"
def test_select_first_attribute_value_returns_none_when_no_match(self):
"""Device.select_first_attribute_value() returns None when no attribute matches."""
device_data = decamelize(RAW_DEVICES)
device = Device(**device_data)
value = device.select_first_attribute_value(["nonexistent", "also_nonexistent"])
assert value is None
def test_select_first_attribute_value_empty_attributes(self):
"""Device.select_first_attribute_value() returns None for devices with no attributes."""
test_device = {**RAW_DEVICES, "attributes": []}
device_data = decamelize(test_device)
device = Device(**device_data)
value = device.select_first_attribute_value(["core:Manufacturer"])
assert value is None
def test_select_first_attribute_value_with_none_values(self):
"""Device.select_first_attribute_value() skips attributes with None values."""
test_device = {
**RAW_DEVICES,
"attributes": [
{"name": "core:Model", "type": 3, "value": None},
{"name": "core:Manufacturer", "type": 3, "value": "VELUX"},
],
}
device_data = decamelize(test_device)
device = Device(**device_data)
value = device.select_first_attribute_value(["core:Model", "core:Manufacturer"])
assert value == "VELUX"
class TestStates:
"""Tests for the States container behaviour and getter semantics."""
def test_empty_states(self):
"""An empty list yields an empty States object with no state found."""
states = States([])
assert not states
assert not states.get(STATE)
def test_none_states(self):
"""A None value for states should behave as empty."""
states = States(None)
assert not states
assert not states.get(STATE)
def test_getter(self):
"""Retrieve a known state and validate its properties."""
states = States(RAW_STATES)
state = states.get(STATE)
assert state
assert state.name == STATE
assert state.type == DataType.STRING
assert state.value == "alarm name"
def test_getter_missing(self):
"""Requesting a missing state returns falsy (None)."""
states = States(RAW_STATES)
state = states.get("FooState")
assert not state
def test_select_returns_first_match(self):
"""select() returns the first state with a non-None value."""
states = States(RAW_STATES)
state = states.select(
["nonexistent", "core:NameState", "internal:AlarmDelayState"]
)
assert state is not None
assert state.name == "core:NameState"
def test_select_returns_none_when_no_match(self):
"""select() returns None when no state matches."""
states = States(RAW_STATES)
assert states.select(["nonexistent", "also_nonexistent"]) is None
def test_select_value_returns_first_value(self):
"""select_value() returns the value of the first matching state."""
states = States(RAW_STATES)
value = states.select_value(["nonexistent", "core:NameState"])
assert value == "alarm name"
def test_select_value_returns_none_when_no_match(self):
"""select_value() returns None when no state matches."""
states = States(RAW_STATES)
assert states.select_value(["nonexistent"]) is None
def test_has_any_true(self):
"""has_any() returns True when at least one state exists."""
states = States(RAW_STATES)
assert states.has_any(["nonexistent", "core:NameState"])
def test_has_any_false(self):
"""has_any() returns False when no state exists."""
states = States(RAW_STATES)
assert not states.has_any(["nonexistent", "also_nonexistent"])
class TestCommandDefinitions:
"""Tests for CommandDefinitions container and helper methods."""
def test_select_returns_first_match(self):
"""select() returns the first command name that exists."""
cmds = CommandDefinitions(
[
{"command_name": "close", "nparams": 0},
{"command_name": "open", "nparams": 0},
{"command_name": "setPosition", "nparams": 1},
]
)
assert cmds.select(["nonexistent", "open", "close"]) == "open"
def test_select_returns_none_when_no_match(self):
"""select() returns None when no command matches."""
cmds = CommandDefinitions([{"command_name": "close", "nparams": 0}])
assert cmds.select(["nonexistent", "also_nonexistent"]) is None
def test_has_any_true(self):
"""has_any() returns True when at least one command exists."""
cmds = CommandDefinitions([{"command_name": "close", "nparams": 0}])
assert cmds.has_any(["nonexistent", "close"])
def test_has_any_false(self):
"""has_any() returns False when no command matches."""
cmds = CommandDefinitions([{"command_name": "close", "nparams": 0}])
assert not cmds.has_any(["nonexistent", "also_nonexistent"])
class TestDefinition:
"""Tests for Definition model and its helper methods."""
def test_get_state_definition_returns_first_match(self):
"""get_state_definition() returns the first StateDefinition in definition.states.
The definition is matched by `qualified_name` against the input list.
"""
definition = Definition(
commands=[],
states=[
{"qualified_name": "core:ClosureState", "type": "ContinuousState"},
{
"qualified_name": "core:TargetClosureState",
"type": "ContinuousState",
},
],
)
# Iterates definition.states in order, returns first match found
state_def = definition.get_state_definition(
["core:TargetClosureState", "core:ClosureState"]
)
assert state_def is not None
# core:ClosureState appears first in definition.states, so it's returned
assert state_def.qualified_name == "core:ClosureState"
# Only asking for TargetClosureState works
state_def2 = definition.get_state_definition(["core:TargetClosureState"])
assert state_def2 is not None
assert state_def2.qualified_name == "core:TargetClosureState"
def test_get_state_definition_returns_none_when_no_match(self):
"""get_state_definition() returns None when no state definition matches."""
definition = Definition(commands=[], states=[])
assert definition.get_state_definition(["nonexistent"]) is None
def test_has_state_definition_returns_true(self):
"""has_state_definition() returns True when a state definition matches."""
definition = Definition(
commands=[],
states=[
{"qualified_name": "core:ClosureState", "type": "ContinuousState"},
{
"qualified_name": "core:TargetClosureState",
"type": "ContinuousState",
},
],
)
assert definition.has_state_definition(["core:ClosureState"])
assert definition.has_state_definition(
["nonexistent", "core:TargetClosureState"]
)
def test_has_state_definition_returns_false(self):
"""has_state_definition() returns False when no state definition matches."""
definition = Definition(
commands=[],
states=[
{"qualified_name": "core:ClosureState", "type": "ContinuousState"},
],
)
assert not definition.has_state_definition(["nonexistent", "also_nonexistent"])
def test_has_state_definition_empty_states(self):
"""has_state_definition() returns False for definitions with no states."""
definition = Definition(commands=[], states=[])
assert not definition.has_state_definition(["core:ClosureState"])
class TestStateDefinition:
"""Tests for StateDefinition initialization behavior."""
def test_requires_name_or_qualified_name(self):
"""StateDefinition should reject payloads with neither identifier field."""
with pytest.raises(
ValueError,
match=r"StateDefinition requires either `name` or `qualified_name`\.",
):
StateDefinition()
class TestState:
"""Unit tests for State value accessors and type validation."""
def test_int_value(self):
"""Integer typed state returns proper integer accessor."""
state = State(name="state", type=DataType.INTEGER, value=1)
assert state.value_as_int == 1
def test_bad_int_value(self):
"""Accessor raises TypeError if the state type mismatches expected int."""
state = State(name="state", type=DataType.BOOLEAN, value=False)
with pytest.raises(TypeError):
assert state.value_as_int
def test_float_value(self):
"""Float typed state returns proper float accessor."""
state = State(name="state", type=DataType.FLOAT, value=1.0)
assert state.value_as_float == 1.0
def test_bad_float_value(self):
"""Accessor raises TypeError if the state type mismatches expected float."""
state = State(name="state", type=DataType.BOOLEAN, value=False)
with pytest.raises(TypeError):
assert state.value_as_float
def test_bool_value(self):
"""Boolean typed state returns proper boolean accessor."""
state = State(name="state", type=DataType.BOOLEAN, value=True)
assert state.value_as_bool
def test_bad_bool_value(self):
"""Accessor raises TypeError if the state type mismatches expected bool."""
state = State(name="state", type=DataType.INTEGER, value=1)
with pytest.raises(TypeError):
assert state.value_as_bool
def test_str_value(self):
"""String typed state returns proper string accessor."""
state = State(name="state", type=DataType.STRING, value="foo")
assert state.value_as_str == "foo"
def test_bad_str_value(self):
"""Accessor raises TypeError if the state type mismatches expected string."""
state = State(name="state", type=DataType.BOOLEAN, value=False)
with pytest.raises(TypeError):
assert state.value_as_str
def test_dict_value(self):
"""JSON object typed state returns proper dict accessor."""
state = State(name="state", type=DataType.JSON_OBJECT, value={"foo": "bar"})
assert state.value_as_dict == {"foo": "bar"}
def test_bad_dict_value(self):
"""Accessor raises TypeError if the state type mismatches expected dict."""
state = State(name="state", type=DataType.BOOLEAN, value=False)
with pytest.raises(TypeError):
assert state.value_as_dict
def test_list_value(self):
"""JSON array typed state returns proper list accessor."""
state = State(name="state", type=DataType.JSON_ARRAY, value=[1, 2])
assert state.value_as_list == [1, 2]
def test_bad_list_value(self):
"""Accessor raises TypeError if the state type mismatches expected list."""
state = State(name="state", type=DataType.BOOLEAN, value=False)
with pytest.raises(TypeError):
assert state.value_as_list
class TestEventState:
"""Unit tests for EventState cloud payload casting behavior."""
def test_json_string_is_parsed(self):
"""Valid JSON payload strings are cast to typed Python values."""
state = EventState(name="state", type=DataType.JSON_OBJECT, value='{"foo": 1}')
assert state.value == {"foo": 1}
def test_invalid_json_string_raises(self):
"""Malformed JSON payload strings raise ValueError."""
with pytest.raises(ValueError, match="Invalid JSON for event state"):
EventState(
name="state",
type=DataType.JSON_ARRAY,
value="[not-valid-json",
)
def test_command_to_payload_omits_none():
"""Command.to_payload omits None fields from the resulting payload."""
from pyoverkiz.enums.command import OverkizCommand
from pyoverkiz.models import Command
cmd = Command(name=OverkizCommand.CLOSE, parameters=None, type=None)
payload = cmd.to_payload()
assert payload == {"name": "close"}
def test_action_to_payload_and_parameters_conversion():
"""Action.to_payload converts nested Command enums to primitives."""
from pyoverkiz.enums.command import OverkizCommand, OverkizCommandParam
from pyoverkiz.models import Action, Command
cmd = Command(
name=OverkizCommand.SET_LEVEL, parameters=[10, OverkizCommandParam.A], type=1
)
action = Action("rts://2025-8464-6867/16756006", [cmd])
payload = action.to_payload()
assert payload["device_url"] == "rts://2025-8464-6867/16756006"
assert payload["commands"][0]["name"] == "setLevel"
assert payload["commands"][0]["type"] == 1
# parameters should be converted to primitives (enum -> str)
assert payload["commands"][0]["parameters"] == [10, "A"]