-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathtest_client.py
More file actions
1238 lines (1095 loc) · 45.4 KB
/
test_client.py
File metadata and controls
1238 lines (1095 loc) · 45.4 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
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Unit tests for the high-level OverkizClient behaviour and responses."""
from __future__ import annotations
import json
from pathlib import Path
from unittest.mock import AsyncMock, patch
import aiohttp
import pytest
from pyoverkiz import exceptions
from pyoverkiz.action_queue import ActionQueueSettings
from pyoverkiz.auth import UsernamePasswordCredentials
from pyoverkiz.client import OverkizClient
from pyoverkiz.client_settings import OverkizClientSettings
from pyoverkiz.enums import (
APIType,
DataType,
ExecutionState,
ExecutionSubType,
ExecutionType,
Server,
)
from pyoverkiz.models import (
Action,
Command,
Execution,
HistoryExecution,
Option,
PersistedActionGroup,
Place,
State,
)
from pyoverkiz.response_handler import check_response
from tests.helpers import MockResponse
CURRENT_DIR = Path(__file__).resolve().parent
class TestOverkizClient:
"""Tests for the public OverkizClient behaviour (API type, devices, events, setup and diagnostics)."""
@pytest.mark.asyncio
async def test_get_api_type_cloud(self, client: OverkizClient):
"""Verify that a cloud-configured client reports APIType.CLOUD."""
assert client.server_config.api_type == APIType.CLOUD
@pytest.mark.asyncio
async def test_get_api_type_local(self, local_client: OverkizClient):
"""Verify that a local-configured client reports APIType.LOCAL."""
assert local_client.server_config.api_type == APIType.LOCAL
@pytest.mark.asyncio
async def test_get_devices_basic(self, client: OverkizClient):
"""Ensure the client can fetch and parse the basic devices fixture."""
with (CURRENT_DIR / "devices.json").open(encoding="utf-8") as raw_devices:
resp = MockResponse(raw_devices.read())
with patch.object(aiohttp.ClientSession, "get", return_value=resp):
devices = await client.get_devices()
assert len(devices) == 23
@pytest.mark.parametrize(
("fixture_name", "event_length"),
[
("events.json", 16),
("local_events.json", 3),
],
)
@pytest.mark.asyncio
async def test_fetch_events_basic(
self, client: OverkizClient, fixture_name: str, event_length: int
):
"""Parameterised test that fetches events fixture and checks the expected count."""
with (CURRENT_DIR / "fixtures" / "event" / fixture_name).open(
encoding="utf-8",
) as raw_events:
resp = MockResponse(raw_events.read())
with patch.object(aiohttp.ClientSession, "post", return_value=resp):
events = await client.fetch_events()
assert len(events) == event_length
@pytest.mark.asyncio
async def test_fetch_events_simple_cast(self, client: OverkizClient):
"""Check that event state values from the cloud (strings) are cast to appropriate types."""
with (CURRENT_DIR / "fixtures" / "event" / "events.json").open(
encoding="utf-8",
) as raw_events:
resp = MockResponse(raw_events.read())
with patch.object(aiohttp.ClientSession, "post", return_value=resp):
events = await client.fetch_events()
# check if str to integer cast was succesfull
int_state_event = events[2].device_states[0]
assert int_state_event.value == 23247220
assert isinstance(int_state_event.value, int)
assert int_state_event.type == DataType.INTEGER
@pytest.mark.asyncio
async def test_backoff_relogin_on_auth_error(self, client: OverkizClient):
"""Ensure auth backoff retries and triggers `login()` on failure."""
client.login = AsyncMock()
with (
patch("backoff._async.asyncio.sleep", new=AsyncMock()) as sleep_mock,
patch.object(
OverkizClient,
"_get",
new=AsyncMock(
side_effect=[
exceptions.NotAuthenticatedError("expired"),
{"protocolVersion": "1"},
]
),
) as get_mock,
):
result = await client.get_api_version()
assert result == "1"
assert get_mock.await_count == 2
assert client.login.await_count == 1
assert sleep_mock.await_count == 1
@pytest.mark.asyncio
async def test_backoff_refresh_listener_on_listener_error(
self, client: OverkizClient
) -> None:
"""Ensure listener backoff retries and triggers `register_event_listener()`."""
client.event_listener_id = "listener-1"
client.register_event_listener = AsyncMock(return_value="listener-2")
with (
patch("backoff._async.asyncio.sleep", new=AsyncMock()) as sleep_mock,
patch.object(
OverkizClient,
"_post",
new=AsyncMock(
side_effect=[
exceptions.InvalidEventListenerIdError("bad listener"),
[],
]
),
) as post_mock,
):
events = await client.fetch_events()
assert events == []
assert post_mock.await_count == 2
assert client.register_event_listener.await_count == 1
assert sleep_mock.await_count == 1
@pytest.mark.asyncio
async def test_backoff_retries_on_concurrent_requests(
self, client: OverkizClient
) -> None:
"""Ensure concurrent request backoff retries and succeeds afterwards."""
with (
patch("backoff._async.asyncio.sleep", new=AsyncMock()) as sleep_mock,
patch.object(
OverkizClient,
"_post",
new=AsyncMock(
side_effect=[
exceptions.TooManyConcurrentRequestsError("busy"),
{"id": "listener-3"},
]
),
) as post_mock,
):
listener_id = await client.register_event_listener()
assert listener_id == "listener-3"
assert post_mock.await_count == 2
assert sleep_mock.await_count == 1
@pytest.mark.parametrize(
"fixture_name",
[
("events.json"),
("local_events.json"),
],
)
@pytest.mark.asyncio
async def test_fetch_events_casting(self, client: OverkizClient, fixture_name: str):
"""Validate that fetched event states are cast to the expected Python types for each data type."""
with (CURRENT_DIR / "fixtures" / "event" / fixture_name).open(
encoding="utf-8",
) as raw_events:
resp = MockResponse(raw_events.read())
with patch.object(aiohttp.ClientSession, "post", return_value=resp):
events = await client.fetch_events()
for event in events:
for state in event.device_states:
if state.type == 0:
assert state.value is None
if state.type == 1:
assert isinstance(state.value, int)
if state.type == 2:
assert isinstance(state.value, float)
if state.type == 3:
assert isinstance(state.value, str)
if state.type == 6:
assert isinstance(state.value, bool)
if state.type == 10:
assert isinstance(state.value, list)
if state.type == 11:
assert isinstance(state.value, dict)
@pytest.mark.parametrize(
("fixture_name", "device_count", "gateway_count"),
[
("setup_3_gateways.json", 37, 3),
("setup_cozytouch.json", 12, 1),
("setup_cozytouch_v2.json", 5, 1),
("setup_cozytouch_2.json", 15, 1),
("setup_cozytouch_3.json", 15, 1),
("setup_hi_kumo.json", 3, 1),
("setup_hi_kumo_2.json", 3, 1),
("setup_hi_kumo_8_gateways.json", 16, 8),
("setup_nexity.json", 18, 1),
("setup_nexity_2.json", 17, 1),
("setup_rexel.json", 18, 1),
("setup_tahoma_1.json", 1, 1),
("setup_tahoma_3.json", 39, 1),
("setup_tahoma_climate.json", 19, 1),
("setup_tahoma_oceania.json", 3, 1),
("setup_tahoma_pro.json", 12, 1),
("setup_hue_and_low_speed.json", 40, 1),
("setup_tahoma_siren_io.json", 11, 1),
("setup_tahoma_siren_rtd.json", 31, 1),
("setup_tahoma_be.json", 15, 1),
("setup_local.json", 3, 1),
("setup_local_tahoma.json", 8, 1),
("setup_local_with_climate.json", 33, 1),
],
)
@pytest.mark.asyncio
async def test_get_setup(
self,
client: OverkizClient,
fixture_name: str,
device_count: int,
gateway_count: int,
):
"""Ensure setup parsing yields expected device and gateway counts and device metadata."""
with (CURRENT_DIR / "fixtures" / "setup" / fixture_name).open(
encoding="utf-8",
) as setup_mock:
resp = MockResponse(setup_mock.read())
with patch.object(aiohttp.ClientSession, "get", return_value=resp):
setup = await client.get_setup()
assert len(setup.devices) == device_count
assert len(setup.gateways) == gateway_count
if fixture_name.startswith("setup_local"):
assert setup.id is None
for device in setup.devices:
assert device.identifier.gateway_id is not None
assert device.identifier.device_address is not None
assert device.identifier.protocol is not None
@pytest.mark.parametrize(
"fixture_name",
[
("setup_3_gateways.json"),
("setup_cozytouch.json"),
("setup_cozytouch_v2.json"),
("setup_cozytouch_2.json"),
("setup_cozytouch_3.json"),
("setup_cozytouch_4.json"),
("setup_hi_kumo.json"),
("setup_hi_kumo_2.json"),
("setup_hi_kumo_8_gateways.json"),
("setup_nexity.json"),
("setup_nexity_2.json"),
("setup_rexel.json"),
("setup_tahoma_1.json"),
("setup_tahoma_3.json"),
("setup_tahoma_climate.json"),
("setup_tahoma_oceania.json"),
("setup_tahoma_pro.json"),
("setup_hue_and_low_speed.json"),
("setup_tahoma_siren_io.json"),
("setup_tahoma_siren_rtd.json"),
("setup_tahoma_be.json"),
("setup_local.json"),
("setup_local_tahoma.json"),
("setup_local_with_climate.json"),
],
)
@pytest.mark.asyncio
async def test_get_diagnostic_data(self, client: OverkizClient, fixture_name: str):
"""Verify that diagnostic data can be fetched and is not empty."""
with (CURRENT_DIR / "fixtures" / "setup" / fixture_name).open(
encoding="utf-8",
) as setup_mock:
setup_resp = MockResponse(setup_mock.read())
with (
CURRENT_DIR
/ "fixtures"
/ "action_groups"
/ "action-group-tahoma-switch.json"
).open(
encoding="utf-8",
) as ag_mock:
ag_resp = MockResponse(ag_mock.read())
responses = iter([setup_resp, ag_resp])
with patch.object(
aiohttp.ClientSession, "get", side_effect=lambda *a, **kw: next(responses)
):
diagnostics = await client.get_diagnostic_data()
assert diagnostics
assert "setup" in diagnostics
assert "action_groups" in diagnostics
@pytest.mark.asyncio
async def test_get_diagnostic_data_redacted_by_default(self, client: OverkizClient):
"""Ensure diagnostics are redacted when no argument is provided."""
with (CURRENT_DIR / "fixtures" / "setup" / "setup_tahoma_1.json").open(
encoding="utf-8",
) as setup_mock:
setup_resp = MockResponse(setup_mock.read())
with (
CURRENT_DIR
/ "fixtures"
/ "action_groups"
/ "action-group-tahoma-switch.json"
).open(
encoding="utf-8",
) as ag_mock:
ag_resp = MockResponse(ag_mock.read())
responses = iter([setup_resp, ag_resp])
with (
patch.object(
aiohttp.ClientSession,
"get",
side_effect=lambda *a, **kw: next(responses),
),
patch(
"pyoverkiz.client.obfuscate_sensitive_data",
side_effect=[{"masked": True}, [{"masked": True}]],
) as obfuscate,
):
diagnostics = await client.get_diagnostic_data()
assert diagnostics == {
"setup": {"masked": True},
"action_groups": [{"masked": True}],
}
assert obfuscate.call_count == 2
@pytest.mark.asyncio
async def test_get_diagnostic_data_without_masking(self, client: OverkizClient):
"""Ensure diagnostics can be returned without masking when requested."""
with (CURRENT_DIR / "fixtures" / "setup" / "setup_tahoma_1.json").open(
encoding="utf-8",
) as setup_mock:
raw_setup = setup_mock.read()
setup_resp = MockResponse(raw_setup)
with (
CURRENT_DIR
/ "fixtures"
/ "action_groups"
/ "action-group-tahoma-switch.json"
).open(
encoding="utf-8",
) as ag_mock:
raw_ag = ag_mock.read()
ag_resp = MockResponse(raw_ag)
responses = iter([setup_resp, ag_resp])
with (
patch.object(
aiohttp.ClientSession,
"get",
side_effect=lambda *a, **kw: next(responses),
),
patch("pyoverkiz.client.obfuscate_sensitive_data") as obfuscate,
):
diagnostics = await client.get_diagnostic_data(mask_sensitive_data=False)
assert diagnostics == {
"setup": json.loads(raw_setup),
"action_groups": json.loads(raw_ag),
}
obfuscate.assert_not_called()
@pytest.mark.asyncio
async def test_get_diagnostic_data_returns_structured_dict(
self, client: OverkizClient
):
"""Verify diagnostic data returns a dict with setup and action_groups sections."""
with (CURRENT_DIR / "fixtures" / "setup" / "setup_tahoma_1.json").open(
encoding="utf-8",
) as setup_mock:
setup_resp = MockResponse(setup_mock.read())
with (
CURRENT_DIR
/ "fixtures"
/ "action_groups"
/ "action-group-tahoma-switch.json"
).open(
encoding="utf-8",
) as ag_mock:
ag_resp = MockResponse(ag_mock.read())
responses = iter([setup_resp, ag_resp])
with patch.object(
aiohttp.ClientSession, "get", side_effect=lambda *a, **kw: next(responses)
):
diagnostics = await client.get_diagnostic_data(mask_sensitive_data=False)
assert "setup" in diagnostics
assert "action_groups" in diagnostics
assert isinstance(diagnostics["action_groups"], list)
@pytest.mark.parametrize(
("fixture_name", "exception", "status_code"),
[
("cloud/503-empty.html", exceptions.ServiceUnavailableError, 503),
("cloud/503-maintenance.html", exceptions.MaintenanceError, 503),
(
"cloud/access-denied-to-gateway.json",
exceptions.AccessDeniedToGatewayError,
400,
),
(
"cloud/application-not-allowed.json",
exceptions.ApplicationNotAllowedError,
400,
),
(
"cloud/bad-credentials.json",
exceptions.BadCredentialsError,
400,
),
(
"cloud/missing-authorization-token.json",
exceptions.MissingAuthorizationTokenError,
400,
),
(
"cloud/no-registered-event-listener.json",
exceptions.NoRegisteredEventListenerError,
400,
),
(
"cloud/too-many-concurrent-requests.json",
exceptions.TooManyConcurrentRequestsError,
400,
),
(
"cloud/too-many-executions.json",
exceptions.TooManyExecutionsError,
400,
),
(
"cloud/too-many-requests.json",
exceptions.TooManyRequestsError,
400,
),
(
"cloud/no-such-resource.json",
exceptions.NoSuchResourceError,
400,
),
(
"cloud/exec-queue-full.json",
exceptions.ExecutionQueueFullError,
400,
),
(
"cloud/missing-api-key.json",
exceptions.MissingAPIKeyError,
400,
),
(
"cloud/unknown-user-account.json",
exceptions.UnknownUserError,
400,
),
(
"cloud/no-such-command.json",
exceptions.InvalidCommandError,
400,
),
(
"cloud/invalid-event-listener-id.json",
exceptions.InvalidEventListenerIdError,
400,
),
(
"cloud/session-and-bearer.json",
exceptions.SessionAndBearerInSameRequestError,
400,
),
(
"cloud/too-many-attempts-banned.json",
exceptions.TooManyAttemptsBannedError,
400,
),
(
"cloud/invalid-token.json",
exceptions.InvalidTokenError,
400,
),
(
"cloud/not-such-token.json",
exceptions.NoSuchTokenError,
400,
),
(
"cloud/unknown-auth-error.json",
exceptions.BadCredentialsError,
400,
),
(
"cloud/unknown-resource-access-denied.json",
exceptions.ResourceAccessDeniedError,
400,
),
(
"cloud/resource-access-denied-device-setup-mismatch.json",
exceptions.ResourceAccessDeniedError,
400,
),
(
"cloud/resource-access-denied-gateway-not-in-setup.json",
exceptions.ResourceAccessDeniedError,
400,
),
(
"cloud/no-such-action-group.json",
exceptions.NoSuchActionGroupError,
404,
),
(
"cloud/action-group-setup-not-found.json",
exceptions.ActionGroupSetupNotFoundError,
400,
),
(
"cloud/no-such-controllable.json",
exceptions.OverkizError,
400,
),
(
"cloud/no-such-ui-profile.json",
exceptions.OverkizError,
400,
),
(
"local/400-bad-parameters.json",
exceptions.OverkizError,
400,
),
("local/400-bus-error.json", exceptions.OverkizError, 400),
(
"local/400-malformed-action-group.json",
exceptions.OverkizError,
400,
),
(
"local/400-malformed-fetch-id.json",
exceptions.OverkizError,
400,
),
(
"local/400-missing-execution-id.json",
exceptions.OverkizError,
400,
),
(
"local/400-missing-parameters.json",
exceptions.OverkizError,
400,
),
(
"local/400-duplicate-action-on-device.json",
exceptions.DuplicateActionOnDeviceError,
400,
),
(
"local/400-action-group-setup-not-found.json",
exceptions.ActionGroupSetupNotFoundError,
400,
),
(
"local/400-no-registered-event-listener.json",
exceptions.NoRegisteredEventListenerError,
400,
),
(
"local/400-no-such-device.json",
exceptions.NoSuchDeviceError,
400,
),
(
"local/400-unknown-object.json",
exceptions.UnknownObjectError,
400,
),
(
"local/400-unspecified-error.json",
exceptions.OverkizError,
400,
),
(
"local/401-missing-authorization-token.json",
exceptions.MissingAuthorizationTokenError,
401,
),
(
"local/401-not-authenticated.json",
exceptions.NotAuthenticatedError,
401,
),
],
)
@pytest.mark.asyncio
async def test_check_response_exception_handling(
self,
fixture_name: str,
status_code: int,
exception: Exception,
):
"""Ensure client raises the correct error for various error fixtures/status codes."""
if fixture_name:
with (CURRENT_DIR / "fixtures" / "exceptions" / fixture_name).open(
encoding="utf-8",
) as raw_events:
resp = MockResponse(raw_events.read(), status_code)
else:
resp = MockResponse(None, status_code)
with pytest.raises(exception):
await check_response(resp)
@pytest.mark.asyncio
async def test_get_setup_options(
self,
client: OverkizClient,
):
"""Check that setup options are parsed and return the expected number of Option instances."""
with (CURRENT_DIR / "fixtures" / "endpoints" / "setup-options.json").open(
encoding="utf-8",
) as raw_events:
resp = MockResponse(raw_events.read())
with patch.object(aiohttp.ClientSession, "get", return_value=resp):
options = await client.get_setup_options()
assert len(options) == 3
for option in options:
assert isinstance(option, Option)
@pytest.mark.asyncio
async def test_get_returns_none_for_204_without_json_parse(
self, client: OverkizClient
) -> None:
"""Ensure `_get` skips JSON parsing for 204 responses and returns `None`."""
resp = MockResponse("", status=204)
resp.json = AsyncMock(return_value={})
with (
patch.object(client, "_refresh_token_if_expired", new=AsyncMock()),
patch.object(aiohttp.ClientSession, "get", return_value=resp),
):
result = await client._get("setup/options")
assert result is None
assert not resp.json.called
@pytest.mark.asyncio
async def test_post_returns_none_for_204_without_json_parse(
self, client: OverkizClient
) -> None:
"""Ensure `_post` skips JSON parsing for 204 responses and returns `None`."""
resp = MockResponse("", status=204)
resp.json = AsyncMock(return_value={})
with (
patch.object(client, "_refresh_token_if_expired", new=AsyncMock()),
patch.object(aiohttp.ClientSession, "post", return_value=resp),
):
result = await client._post("setup/devices/states/refresh")
assert result is None
assert not resp.json.called
@pytest.mark.asyncio
async def test_execute_action_group_omits_none_fields(self, client: OverkizClient):
"""Ensure `type` and `parameters` that are None are omitted from the request payload."""
from pyoverkiz.enums.command import OverkizCommand
from pyoverkiz.models import Action, Command
action = Action(
device_url="rts://2025-8464-6867/16756006",
commands=[Command(name=OverkizCommand.CLOSE, parameters=None, type=None)],
)
resp = MockResponse('{"execId": "exec-123"}')
with patch.object(aiohttp.ClientSession, "post") as mock_post:
mock_post.return_value = resp
exec_id = await client.execute_action_group([action])
assert exec_id == "exec-123"
assert mock_post.called
_, kwargs = mock_post.call_args
sent_json = kwargs.get("json")
assert sent_json is not None
# The client should have converted payload to camelCase and applied
# abbreviation fixes (deviceURL) before sending.
action_sent = sent_json["actions"][0]
assert action_sent.get("deviceURL") == action.device_url
cmd = action_sent["commands"][0]
assert "type" not in cmd
assert "parameters" not in cmd
assert cmd["name"] == "close"
@pytest.mark.parametrize(
("fixture_name", "option_name", "instance"),
[
(
"setup-options-developerMode.json",
"developerMode-1234-5678-1234",
Option,
),
("setup-options-empty.json", "test", None),
],
)
@pytest.mark.asyncio
async def test_get_setup_option(
self,
client: OverkizClient,
fixture_name: str,
option_name: str,
instance: Option | None,
):
"""Verify retrieval of a single setup option by name, including non-existent options."""
with (CURRENT_DIR / "fixtures" / "endpoints" / fixture_name).open(
encoding="utf-8",
) as raw_events:
resp = MockResponse(raw_events.read())
with patch.object(aiohttp.ClientSession, "get", return_value=resp):
option = await client.get_setup_option(option_name)
if instance is None:
assert option is None
else:
assert isinstance(option, instance)
@pytest.mark.parametrize(
"fixture_name",
[
"exec-current-empty-object.json",
"exec-current-empty-list.json",
],
)
@pytest.mark.asyncio
async def test_get_current_execution_returns_none_for_empty_response(
self,
client: OverkizClient,
fixture_name: str,
):
"""Cloud returns {} and local returns [] for non-existent exec_ids."""
with (CURRENT_DIR / "fixtures" / "endpoints" / fixture_name).open(
encoding="utf-8",
) as f:
resp = MockResponse(f.read())
with patch.object(aiohttp.ClientSession, "get", return_value=resp):
result = await client.get_current_execution(
"00000000-0000-0000-0000-000000000000"
)
assert result is None
@pytest.mark.parametrize(
("fixture_name", "scenario_count"),
[
("action-group-cozytouch.json", 9),
("action-group-tahoma-box-v1.json", 17),
("action-group-tahoma-classic-v2.json", 2),
("action-group-tahoma-switch.json", 1),
],
)
@pytest.mark.asyncio
async def test_get_action_groups(
self,
client: OverkizClient,
fixture_name: str,
scenario_count: int,
):
"""Ensure action groups (scenarios) are parsed correctly and contain actions and commands."""
with (CURRENT_DIR / "fixtures" / "action_groups" / fixture_name).open(
encoding="utf-8",
) as action_group_mock:
resp = MockResponse(action_group_mock.read())
with patch.object(aiohttp.ClientSession, "get", return_value=resp):
action_groups = await client.get_action_groups()
assert len(action_groups) == scenario_count
for action_group in action_groups:
assert isinstance(action_group, PersistedActionGroup)
assert isinstance(action_group.oid, str)
assert action_group.actions
for action in action_group.actions:
assert action.device_url is not None
assert action.commands
for command in action.commands:
assert command.name is not None
@pytest.mark.asyncio
async def test_get_current_execution_returns_execution(self, client: OverkizClient):
"""Verify a running execution is parsed into an Execution model."""
with (CURRENT_DIR / "fixtures" / "exec" / "current-single.json").open(
encoding="utf-8",
) as f:
resp = MockResponse(f.read())
with patch.object(aiohttp.ClientSession, "get", return_value=resp):
result = await client.get_current_execution(
"699dd967-0a19-0481-7a62-99b990a2feb8"
)
assert isinstance(result, Execution)
assert result.id == "699dd967-0a19-0481-7a62-99b990a2feb8"
assert result.state == ExecutionState.TRANSMITTED
assert result.start_time == 1767003511145
assert result.execution_type == ExecutionType.IMMEDIATE_EXECUTION
assert result.execution_sub_type == ExecutionSubType.MANUAL_CONTROL
assert not isinstance(result.action_group, PersistedActionGroup)
assert (
result.action_group.actions[0].device_url
== "rts://1234-5678-1234/12345678"
)
@pytest.mark.asyncio
async def test_get_current_executions(self, client: OverkizClient):
"""Verify parsing a list of running executions with RTS device commands."""
with (CURRENT_DIR / "fixtures" / "exec" / "current-tahoma-switch.json").open(
encoding="utf-8",
) as f:
resp = MockResponse(f.read())
with patch.object(aiohttp.ClientSession, "get", return_value=resp):
executions = await client.get_current_executions()
assert len(executions) == 1
assert isinstance(executions[0], Execution)
assert executions[0].state == ExecutionState.TRANSMITTED
assert len(executions[0].action_group.actions) == 2
assert executions[0].action_group.actions[0].commands[0].name == "close"
assert executions[0].action_group.actions[1].commands[0].name == "identify"
@pytest.mark.asyncio
async def test_get_execution_history(self, client: OverkizClient):
"""Verify execution history parsing including completed and failed executions."""
with (CURRENT_DIR / "fixtures" / "endpoints" / "history-executions.json").open(
encoding="utf-8",
) as f:
resp = MockResponse(f.read())
with patch.object(aiohttp.ClientSession, "get", return_value=resp):
history = await client.get_execution_history()
assert len(history) == 2
completed = history[0]
assert isinstance(completed, HistoryExecution)
assert completed.state.value == "COMPLETED"
assert completed.failure_type == "NO_FAILURE"
assert completed.commands[0].command == "close"
assert completed.commands[0].device_url == "rts://2025-8464-6867/16756006"
failed = history[1]
assert failed.state.value == "FAILED"
assert failed.failure_type == "CMDCANCELLED"
assert failed.commands[0].command == "open"
@pytest.mark.asyncio
async def test_get_state(self, client: OverkizClient):
"""Verify device state retrieval and parsing."""
with (CURRENT_DIR / "fixtures" / "endpoints" / "device-states.json").open(
encoding="utf-8",
) as f:
resp = MockResponse(f.read())
with patch.object(aiohttp.ClientSession, "get", return_value=resp):
states = await client.get_state("io://1234-5678-1234/12345678")
assert len(states) == 3
assert all(isinstance(s, State) for s in states)
assert states[0].name == "core:StatusState"
assert states[0].value == "available"
assert states[1].name == "core:ClosureState"
assert states[1].value == 0
assert states[2].name == "core:OpenClosedState"
assert states[2].value == "open"
@pytest.mark.asyncio
async def test_get_places(self, client: OverkizClient):
"""Verify hierarchical place structure is parsed recursively."""
with (CURRENT_DIR / "fixtures" / "endpoints" / "setup-places.json").open(
encoding="utf-8",
) as f:
resp = MockResponse(f.read())
with patch.object(aiohttp.ClientSession, "get", return_value=resp):
places = await client.get_places()
assert isinstance(places, Place)
assert places.label == "My House"
assert len(places.sub_places) == 2
assert places.sub_places[0].label == "Living Room"
assert places.sub_places[1].label == "Bedroom"
assert places.sub_places[1].last_update_time is None
@pytest.mark.asyncio
async def test_execute_action_group_rts_close(self, client: OverkizClient):
"""Verify executing a close command on an RTS cover."""
action = Action(
device_url="rts://2025-8464-6867/16756006",
commands=[Command(name="close", parameters=None, type=1)],
)
resp = MockResponse('{"execId": "ee7a5676-c68f-43a3-956d-6f5efc745954"}')
with patch.object(aiohttp.ClientSession, "post") as mock_post:
mock_post.return_value = resp
exec_id = await client.execute_action_group([action])
assert exec_id == "ee7a5676-c68f-43a3-956d-6f5efc745954"
_, kwargs = mock_post.call_args
sent_json = kwargs.get("json")
assert (
sent_json["actions"][0]["deviceURL"] == "rts://2025-8464-6867/16756006"
)
assert sent_json["actions"][0]["commands"][0]["name"] == "close"
@pytest.mark.asyncio
async def test_execute_action_group_multiple_rts_devices(
self, client: OverkizClient
):
"""Verify executing commands on multiple RTS devices in a single action group."""
actions = [
Action(
device_url="rts://2025-8464-6867/16756006",
commands=[Command(name="close", parameters=None, type=1)],
),
Action(
device_url="rts://2025-8464-6867/16756007",
commands=[Command(name="open", parameters=None, type=1)],
),
]
resp = MockResponse('{"execId": "aaa-bbb-ccc"}')
with patch.object(aiohttp.ClientSession, "post") as mock_post:
mock_post.return_value = resp
exec_id = await client.execute_action_group(actions)
assert exec_id == "aaa-bbb-ccc"
_, kwargs = mock_post.call_args
sent_json = kwargs.get("json")
assert len(sent_json["actions"]) == 2
assert sent_json["actions"][0]["commands"][0]["name"] == "close"
assert sent_json["actions"][1]["commands"][0]["name"] == "open"
@pytest.mark.asyncio
async def test_execute_persisted_action_group(self, client: OverkizClient):
"""Verify executing a persisted action group by OID."""
resp = MockResponse('{"execId": "ee7a5676-c68f-43a3-956d-6f5efc745954"}')
with patch.object(aiohttp.ClientSession, "post", return_value=resp):