-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathtest_client.py
More file actions
746 lines (663 loc) · 25.8 KB
/
test_client.py
File metadata and controls
746 lines (663 loc) · 25.8 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
"""Unit tests for the high-level OverkizClient behaviour and responses."""
# ruff: noqa: ASYNC230, S106
# S106: Test credentials use dummy values.
# ASYNC230: Blocking open() is acceptable for reading test fixtures
from __future__ import annotations
import json
import os
from unittest.mock import AsyncMock, patch
import aiohttp
import pytest
from pytest_asyncio import fixture
from pyoverkiz import exceptions
from pyoverkiz.auth.credentials import (
LocalTokenCredentials,
UsernamePasswordCredentials,
)
from pyoverkiz.client import OverkizClient
from pyoverkiz.enums import APIType, DataType, Server
from pyoverkiz.models import Option
from pyoverkiz.response_handler import check_response
from pyoverkiz.utils import create_local_server_config
CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
class TestOverkizClient:
"""Tests for the public OverkizClient behaviour (API type, devices, events, setup and diagnostics)."""
@fixture
async def client(self):
"""Fixture providing an OverkizClient configured for the cloud server."""
return OverkizClient(
server=Server.SOMFY_EUROPE,
credentials=UsernamePasswordCredentials("username", "password"),
)
@fixture
async def local_client(self):
"""Fixture providing an OverkizClient configured for a local (developer) server."""
return OverkizClient(
server=create_local_server_config(host="gateway-1234-5678-1243.local:8443"),
credentials=LocalTokenCredentials(token="token"),
)
@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 open(
os.path.join(CURRENT_DIR, "devices.json"), 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 open(
os.path.join(CURRENT_DIR, "fixtures/event/" + fixture_name),
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 open(
os.path.join(CURRENT_DIR, "fixtures/event/events.json"), 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 open(
os.path.join(CURRENT_DIR, "fixtures/event/" + fixture_name),
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 open(
os.path.join(CURRENT_DIR, "fixtures/setup/" + fixture_name),
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
assert device.identifier.device_address
assert device.identifier.protocol
@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 open(
os.path.join(CURRENT_DIR, "fixtures/setup/" + fixture_name),
encoding="utf-8",
) as setup_mock:
resp = MockResponse(setup_mock.read())
with patch.object(aiohttp.ClientSession, "get", return_value=resp):
diagnostics = await client.get_diagnostic_data()
assert 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 open(
os.path.join(CURRENT_DIR, "fixtures/setup/setup_tahoma_1.json"),
encoding="utf-8",
) as setup_mock:
resp = MockResponse(setup_mock.read())
with (
patch.object(aiohttp.ClientSession, "get", return_value=resp),
patch(
"pyoverkiz.client.obfuscate_sensitive_data",
return_value={"masked": True},
) as obfuscate,
):
diagnostics = await client.get_diagnostic_data()
assert diagnostics == {"masked": True}
obfuscate.assert_called_once()
@pytest.mark.asyncio
async def test_get_diagnostic_data_without_masking(self, client: OverkizClient):
"""Ensure diagnostics can be returned without masking when requested."""
with open(
os.path.join(CURRENT_DIR, "fixtures/setup/setup_tahoma_1.json"),
encoding="utf-8",
) as setup_mock:
raw_setup = setup_mock.read()
resp = MockResponse(raw_setup)
with (
patch.object(aiohttp.ClientSession, "get", return_value=resp),
patch("pyoverkiz.client.obfuscate_sensitive_data") as obfuscate,
):
diagnostics = await client.get_diagnostic_data(mask_sensitive_data=False)
assert diagnostics == json.loads(raw_setup)
obfuscate.assert_not_called()
@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,
),
(
"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.OverkizError,
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 open(
os.path.join(CURRENT_DIR, "fixtures/exceptions/" + fixture_name),
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 open(
os.path.join(CURRENT_DIR, "fixtures/endpoints/setup-options.json"),
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(
"rts://2025-8464-6867/16756006",
[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 open(
os.path.join(CURRENT_DIR, "fixtures/endpoints/" + fixture_name),
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", "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 open(
os.path.join(CURRENT_DIR, "fixtures/action_groups/" + fixture_name),
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 action_group.oid
assert action_group.label is not None
assert action_group.actions
for action in action_group.actions:
assert action.device_url
assert action.commands
for command in action.commands:
assert command.name
class MockResponse:
"""Simple stand-in for aiohttp responses used in tests."""
def __init__(self, text, status=200, url=""):
"""Create a mock response with text payload and optional status/url."""
self._text = text
self.status = status
self.url = url
async def text(self):
"""Return text payload asynchronously."""
return self._text
# pylint: disable=unused-argument
async def json(self, content_type=None):
"""Return parsed JSON payload asynchronously."""
return json.loads(self._text)
async def __aexit__(self, exc_type, exc, tb):
"""Context manager exit (noop)."""
async def __aenter__(self):
"""Context manager enter returning self."""
return self