Debian Codegraph @

tests/profiles/test_profile.py

raw
1 """Unit tests for profile."""
2
3 # pylint: disable=protected-access
4
5 import asyncio
6 import time
7 from datetime import timedelta
8 from unittest.mock import Mock
9
10 import pytest
11
12 from async_upnp_client.client_factory import UpnpFactory
13 from async_upnp_client.const import HttpResponse
14 from async_upnp_client.exceptions import (
15 UpnpActionResponseError,
16 UpnpCommunicationError,
17 UpnpConnectionError,
18 UpnpResponseError,
19 )
20 from async_upnp_client.profiles.dlna import DmrDevice
21 from async_upnp_client.profiles.igd import IgdDevice
22
23 from ..conftest import RESPONSE_MAP, UpnpTestNotifyServer, UpnpTestRequester, read_file
24
25
26 class TestUpnpProfileDevice:
27 """Test UPnpProfileDevice."""
28
29 @pytest.mark.asyncio
30 async def test_action_exists(self) -> None:
31 """Test getting existing action."""
32 requester = UpnpTestRequester(RESPONSE_MAP)
33 factory = UpnpFactory(requester)
34 device = await factory.async_create_device("http://dlna_dmr:1234/device.xml")
35 notify_server = UpnpTestNotifyServer(
36 requester=requester,
37 source=("192.168.1.2", 8090),
38 )
39 event_handler = notify_server.event_handler
40 profile = DmrDevice(device, event_handler=event_handler)
41
42 # doesn't error
43 assert profile._action("RC", "GetMute") is not None
44
45 @pytest.mark.asyncio
46 async def test_action_not_exists(self) -> None:
47 """Test getting non-existing action."""
48 requester = UpnpTestRequester(RESPONSE_MAP)
49 factory = UpnpFactory(requester)
50 device = await factory.async_create_device("http://dlna_dmr:1234/device.xml")
51 notify_server = UpnpTestNotifyServer(
52 requester=requester,
53 source=("192.168.1.2", 8090),
54 )
55 event_handler = notify_server.event_handler
56 profile = DmrDevice(device, event_handler=event_handler)
57
58 # doesn't error
59 assert profile._action("RC", "NonExisting") is None
60
61 @pytest.mark.asyncio
62 async def test_icon(self) -> None:
63 """Test getting an icon returns the best available."""
64 requester = UpnpTestRequester(RESPONSE_MAP)
65 factory = UpnpFactory(requester)
66 device = await factory.async_create_device("http://dlna_dmr:1234/device.xml")
67 notify_server = UpnpTestNotifyServer(
68 requester=requester,
69 source=("192.168.1.2", 8090),
70 )
71 event_handler = notify_server.event_handler
72 profile = DmrDevice(device, event_handler=event_handler)
73
74 assert profile.icon == "http://dlna_dmr:1234/device_icon_120.png"
75
76 @pytest.mark.asyncio
77 async def test_is_profile_device(self) -> None:
78 """Test is_profile_device works for root and embedded devices."""
79 requester = UpnpTestRequester(RESPONSE_MAP)
80 factory = UpnpFactory(requester)
81 device = await factory.async_create_device("http://dlna_dmr:1234/device.xml")
82 embedded = await factory.async_create_device("http://dlna_dmr:1234/device_embedded.xml")
83 no_services = await factory.async_create_device("http://dlna_dmr:1234/device_incomplete.xml")
84 igd_device = await factory.async_create_device("http://igd:1234/device.xml")
85
86 assert DmrDevice.is_profile_device(device) is True
87 assert DmrDevice.is_profile_device(embedded) is True
88 assert DmrDevice.is_profile_device(no_services) is False
89 assert DmrDevice.is_profile_device(igd_device) is False
90
91 assert IgdDevice.is_profile_device(device) is False
92 assert IgdDevice.is_profile_device(embedded) is False
93 assert IgdDevice.is_profile_device(no_services) is False
94 assert IgdDevice.is_profile_device(igd_device) is True
95
96 @pytest.mark.asyncio
97 async def test_is_profile_device_non_strict(self) -> None:
98 """Test is_profile_device works for root and embedded devices."""
99 requester = UpnpTestRequester(RESPONSE_MAP)
100 factory = UpnpFactory(requester, non_strict=True)
101 device = await factory.async_create_device("http://dlna_dmr:1234/device.xml")
102 embedded = await factory.async_create_device("http://dlna_dmr:1234/device_embedded.xml")
103 no_services = await factory.async_create_device("http://dlna_dmr:1234/device_incomplete.xml")
104 empty_descriptor = await factory.async_create_device("http://dlna_dmr:1234/device_with_empty_descriptor.xml")
105 igd_device = await factory.async_create_device("http://igd:1234/device.xml")
106
107 assert DmrDevice.is_profile_device(device) is True
108 assert DmrDevice.is_profile_device(embedded) is True
109 assert DmrDevice.is_profile_device(no_services) is False
110 assert DmrDevice.is_profile_device(igd_device) is False
111
112 assert IgdDevice.is_profile_device(device) is False
113 assert IgdDevice.is_profile_device(embedded) is False
114 assert IgdDevice.is_profile_device(no_services) is False
115 assert IgdDevice.is_profile_device(empty_descriptor) is False
116 assert IgdDevice.is_profile_device(igd_device) is True
117
118 @pytest.mark.asyncio
119 async def test_subscribe_manual_resubscribe(self) -> None:
120 """Test subscribing, resub, unsub, without auto_resubscribe."""
121 now = time.monotonic()
122 requester = UpnpTestRequester(RESPONSE_MAP)
123 factory = UpnpFactory(requester)
124 device = await factory.async_create_device("http://dlna_dmr:1234/device.xml")
125 notify_server = UpnpTestNotifyServer(
126 requester=requester,
127 source=("192.168.1.2", 8090),
128 )
129 event_handler = notify_server.event_handler
130 profile = DmrDevice(device, event_handler=event_handler)
131
132 # Test subscription
133 timeout = await profile.async_subscribe_services(auto_resubscribe=False)
134 assert timeout is not None
135 # Timeout incorporates time tolerance, and is minimal renewal time
136 assert timedelta(seconds=149 - 60) <= timeout <= timedelta(seconds=151 - 60)
137
138 assert set(profile._subscriptions.keys()) == {
139 "uuid:dummy-avt1",
140 "uuid:dummy-cm1",
141 "uuid:dummy",
142 }
143
144 # 3 timeouts, ~ 150, ~ 175, and ~ 300 seconds
145 timeouts = sorted(profile._subscriptions.values())
146 assert timeouts[0] == pytest.approx(now + 150, abs=1)
147 assert timeouts[1] == pytest.approx(now + 175, abs=1)
148 assert timeouts[2] == pytest.approx(now + 300, abs=1)
149
150 # Tweak timeouts to check resubscription did something
151 entry = requester.response_map[("SUBSCRIBE", "http://dlna_dmr:1234/upnp/event/RenderingControl1")]
152 requester.response_map[("SUBSCRIBE", "http://dlna_dmr:1234/upnp/event/RenderingControl1")] = HttpResponse(
153 entry.status_code, {**entry.headers, "timeout": "Second-90"}, entry.body
154 )
155
156 # Check subscriptions again, now timeouts should have changed
157 timeout = await profile.async_subscribe_services(auto_resubscribe=False)
158 assert timeout is not None
159 assert timedelta(seconds=89 - 60) <= timeout <= timedelta(seconds=91 - 60)
160 assert set(profile._subscriptions.keys()) == {
161 "uuid:dummy-avt1",
162 "uuid:dummy-cm1",
163 "uuid:dummy",
164 }
165 timeouts = sorted(profile._subscriptions.values())
166 assert timeouts[0] == pytest.approx(now + 90, abs=1)
167 assert timeouts[1] == pytest.approx(now + 150, abs=1)
168
169 # Test unsubscription
170 await profile.async_unsubscribe_services()
171 assert not profile._subscriptions
172
173 @pytest.mark.asyncio
174 async def test_subscribe_auto_resubscribe(self) -> None:
175 """Test subscribing, resub, unsub, with auto_resubscribe."""
176 now = time.monotonic()
177 requester = UpnpTestRequester(RESPONSE_MAP)
178 factory = UpnpFactory(requester)
179 device = await factory.async_create_device("http://dlna_dmr:1234/device.xml")
180 notify_server = UpnpTestNotifyServer(
181 requester=requester,
182 source=("192.168.1.2", 8090),
183 )
184 event_handler = notify_server.event_handler
185 profile = DmrDevice(device, event_handler=event_handler)
186
187 # Tweak timeouts to get a resubscription in a time suitable for testing.
188 # Resubscription tolerance (60 seconds) + 1 second to get set up
189 entry = requester.response_map[("SUBSCRIBE", "http://dlna_dmr:1234/upnp/event/RenderingControl1")]
190 requester.response_map[("SUBSCRIBE", "http://dlna_dmr:1234/upnp/event/RenderingControl1")] = HttpResponse(
191 entry.status_code,
192 {
193 **entry.headers,
194 "timeout": "Second-61",
195 },
196 entry.body,
197 )
198
199 # Test subscription
200 timeout = await profile.async_subscribe_services(auto_resubscribe=True)
201 assert timeout is None
202 assert profile.is_subscribed is True
203
204 # Check subscriptions are correct
205 assert set(profile._subscriptions.keys()) == {
206 "uuid:dummy-avt1",
207 "uuid:dummy-cm1",
208 "uuid:dummy",
209 }
210 timeouts = sorted(profile._subscriptions.values())
211 assert timeouts[0] == pytest.approx(now + 61, abs=1)
212 assert timeouts[1] == pytest.approx(now + 150, abs=1)
213
214 # Check task is running
215 assert isinstance(profile._resubscriber_task, asyncio.Task)
216 assert not profile._resubscriber_task.cancelled()
217 assert not profile._resubscriber_task.done()
218
219 # Re-tweak timeouts to check resubscription did something
220 entry = requester.response_map[("SUBSCRIBE", "http://dlna_dmr:1234/upnp/event/AVTransport1")]
221 requester.response_map[("SUBSCRIBE", "http://dlna_dmr:1234/upnp/event/AVTransport1")] = HttpResponse(
222 entry.status_code,
223 {
224 **entry.headers,
225 "timeout": "Second-90",
226 },
227 entry.body,
228 )
229
230 # Wait for an auto-resubscribe
231 await asyncio.sleep(1.5)
232 now = time.monotonic()
233
234 # Check subscriptions and task again
235 assert set(profile._subscriptions.keys()) == {
236 "uuid:dummy-avt1",
237 "uuid:dummy-cm1",
238 "uuid:dummy",
239 }
240 timeouts = sorted(profile._subscriptions.values())
241 assert timeouts[0] == pytest.approx(now + 61, abs=1)
242 assert timeouts[1] == pytest.approx(now + 90, abs=1)
243 assert isinstance(profile._resubscriber_task, asyncio.Task)
244 assert not profile._resubscriber_task.cancelled()
245 assert not profile._resubscriber_task.done()
246 assert profile.is_subscribed is True
247
248 # Unsubscribe
249 await profile.async_unsubscribe_services()
250
251 # Task and subscriptions should be gone
252 assert profile._resubscriber_task is None
253 assert not profile._subscriptions
254 assert profile.is_subscribed is False
255
256 @pytest.mark.asyncio
257 async def test_subscribe_fail(self) -> None:
258 """Test subscribing fails with UpnpError if device is offline."""
259 requester = UpnpTestRequester(RESPONSE_MAP)
260 factory = UpnpFactory(requester)
261 device = await factory.async_create_device("http://dlna_dmr:1234/device.xml")
262 notify_server = UpnpTestNotifyServer(
263 requester=requester,
264 source=("192.168.1.2", 8090),
265 )
266 event_handler = notify_server.event_handler
267 profile = DmrDevice(device, event_handler=event_handler)
268
269 # First request is fine, 2nd raises an exception, when trying to subscribe
270 requester.exceptions.append(None)
271 requester.exceptions.append(UpnpCommunicationError())
272
273 with pytest.raises(UpnpCommunicationError):
274 await profile.async_subscribe_services(True)
275
276 # Subscriptions and resubscribe task should not exist
277 assert not profile._subscriptions
278 assert profile._resubscriber_task is None
279 assert profile.is_subscribed is False
280
281 @pytest.mark.asyncio
282 async def test_subscribe_rejected(self) -> None:
283 """Test subscribing rejected by device."""
284 requester = UpnpTestRequester(RESPONSE_MAP)
285 factory = UpnpFactory(requester)
286 device = await factory.async_create_device("http://dlna_dmr:1234/device.xml")
287 notify_server = UpnpTestNotifyServer(
288 requester=requester,
289 source=("192.168.1.2", 8090),
290 )
291 event_handler = notify_server.event_handler
292 profile = DmrDevice(device, event_handler=event_handler)
293
294 # All requests give a response error
295 requester.exceptions.append(UpnpResponseError(status=501))
296 requester.exceptions.append(UpnpResponseError(status=501))
297
298 with pytest.raises(UpnpResponseError):
299 await profile.async_subscribe_services(True)
300
301 # Subscriptions and resubscribe task should not exist
302 assert not profile._subscriptions
303 assert profile._resubscriber_task is None
304 assert profile.is_subscribed is False
305
306 @pytest.mark.asyncio
307 async def test_auto_resubscribe_fail(self) -> None:
308 """Test auto-resubscription when the device goes offline."""
309 requester = UpnpTestRequester(RESPONSE_MAP)
310 factory = UpnpFactory(requester)
311 device = await factory.async_create_device("http://dlna_dmr:1234/device.xml")
312 notify_server = UpnpTestNotifyServer(
313 requester=requester,
314 source=("192.168.1.2", 8090),
315 )
316 event_handler = notify_server.event_handler
317 profile = DmrDevice(device, event_handler=event_handler)
318 assert device.available is True
319
320 # Register an event handler
321 on_event_mock = Mock(return_value=None)
322 profile.on_event = on_event_mock
323
324 # Setup for auto-resubscription
325 entry = requester.response_map[("SUBSCRIBE", "http://dlna_dmr:1234/upnp/event/RenderingControl1")]
326 requester.response_map[("SUBSCRIBE", "http://dlna_dmr:1234/upnp/event/RenderingControl1")] = HttpResponse(
327 entry.status_code, {**entry.headers, "timeout": "Second-61"}, entry.body
328 )
329 await profile.async_subscribe_services(auto_resubscribe=True)
330
331 # Exception raised when trying to resubscribe and subsequent retry subscribe
332 requester.exceptions.append(UpnpCommunicationError("resubscribe"))
333 requester.exceptions.append(UpnpConnectionError("subscribe"))
334
335 # Wait for an auto-resubscribe
336 await asyncio.sleep(1.5)
337
338 # Device should now be offline, and an event notification sent
339 assert device.available is False
340 on_event_mock.assert_called_once_with(device.services["urn:schemas-upnp-org:service:RenderingControl:1"], [])
341 # Device will still be subscribed because a notification was sent via
342 # on_event instead of raising an exception.
343 assert profile.is_subscribed is True
344
345 # Unsubscribe should still work
346 await profile.async_unsubscribe_services()
347 assert profile.is_subscribed is False
348
349 # Task and subscriptions should be gone
350 assert profile._resubscriber_task is None
351 assert not profile._subscriptions
352 assert profile.is_subscribed is False
353
354 @pytest.mark.asyncio
355 async def test_resubscribe_drops_stale_subscription(self) -> None:
356 """Regression test for #302: stale subscriptions must be dropped, not spun on."""
357 requester = UpnpTestRequester(RESPONSE_MAP)
358 factory = UpnpFactory(requester)
359 device = await factory.async_create_device("http://dlna_dmr:1234/device.xml")
360 notify_server = UpnpTestNotifyServer(
361 requester=requester,
362 source=("192.168.1.2", 8090),
363 )
364 event_handler = notify_server.event_handler
365 profile = DmrDevice(device, event_handler=event_handler)
366
367 on_event_mock = Mock(return_value=None)
368 profile.on_event = on_event_mock
369
370 await profile.async_subscribe_services(auto_resubscribe=False)
371 assert profile.is_subscribed is True
372
373 # Force every subscription's renewal_time well past the stale threshold.
374 stale_time = time.monotonic() - 3600.0
375 stale_sids = list(profile._subscriptions)
376 for sid in stale_sids:
377 profile._subscriptions[sid] = stale_time
378
379 # Call the resubscribe path directly with notify_errors=True (as the loop does).
380 # Without the fix this would leave the stale entries in place; with the fix every
381 # stale entry is removed and listeners are notified with an empty state change.
382 await profile._async_resubscribe_services(notify_errors=True)
383
384 assert not profile._subscriptions
385
386 notified_services = {call.args[0] for call in on_event_mock.call_args_list}
387 expected_services = {event_handler.service_for_sid(sid) for sid in stale_sids}
388 assert notified_services == expected_services
389 for call in on_event_mock.call_args_list:
390 assert call.args[1] == []
391
392 @pytest.mark.asyncio
393 async def test_subscribe_no_event_handler(self) -> None:
394 """Test no event handler."""
395 requester = UpnpTestRequester(RESPONSE_MAP)
396 factory = UpnpFactory(requester)
397 device = await factory.async_create_device("http://dlna_dmr:1234/device.xml")
398 profile = DmrDevice(device, event_handler=None)
399
400 # Doesn't error, but also doesn't do anything.
401 await profile.async_subscribe_services()
402
403 @pytest.mark.asyncio
404 async def test_poll_state_variables(self) -> None:
405 """Test polling state variables by calling a Get* action."""
406 requester = UpnpTestRequester(RESPONSE_MAP)
407 requester.response_map[("POST", "http://dlna_dmr:1234/upnp/control/AVTransport1")] = HttpResponse(
408 200, {}, read_file("dlna/dmr/action_GetPositionInfo.xml")
409 )
410
411 factory = UpnpFactory(requester)
412 device = await factory.async_create_device("http://dlna_dmr:1234/device.xml")
413 notify_server = UpnpTestNotifyServer(
414 requester=requester,
415 source=("192.168.1.2", 8090),
416 )
417 event_handler = notify_server.event_handler
418 profile = DmrDevice(device, event_handler=event_handler)
419 assert device.available is True
420
421 # Register an event handler, it should be called when variable is updated
422 on_event_mock = Mock(return_value=None)
423 profile.on_event = on_event_mock
424 assert profile.is_subscribed is False
425
426 # Check state variables are currently empty
427 assert profile.media_track_number is None
428 assert profile.media_duration is None
429 assert profile.current_track_uri is None
430 assert profile._current_track_meta_data is None
431 assert profile.media_title is None
432 assert profile.media_artist is None
433
434 # Call the Get action
435 await profile._async_poll_state_variables("AVT", ["GetPositionInfo"], InstanceID=0)
436
437 # on_event should be called with all changed variables
438 expected_service = device.services["urn:schemas-upnp-org:service:AVTransport:1"]
439 expected_changes = [
440 expected_service.state_variables[name]
441 for name in (
442 "CurrentTrack",
443 "CurrentTrackDuration",
444 "CurrentTrackMetaData",
445 "CurrentTrackURI",
446 "RelativeTimePosition",
447 "AbsoluteTimePosition",
448 "RelativeCounterPosition",
449 "AbsoluteCounterPosition",
450 )
451 ]
452 on_event_mock.assert_called_once_with(expected_service, expected_changes)
453
454 # Corresponding state variables should be updated
455 assert profile.media_track_number == 1
456 assert profile.media_duration == 194
457 assert profile.current_track_uri == "uri://1.mp3"
458 assert profile._current_track_meta_data is not None
459 assert profile.media_title == "Test track"
460 assert profile.media_artist == "A & B > C"
461
462 @pytest.mark.asyncio
463 async def test_poll_state_variables_missing_action(self) -> None:
464 """Test missing action used when polling state variables is handled gracefully."""
465 requester = UpnpTestRequester(RESPONSE_MAP)
466 requester.response_map[("POST", "http://dlna_dmr:1234/upnp/control/AVTransport1")] = HttpResponse(
467 200, {}, read_file("dlna/dmr/action_GetPositionInfo.xml")
468 )
469
470 factory = UpnpFactory(requester)
471 device = await factory.async_create_device("http://dlna_dmr:1234/device.xml")
472 profile = DmrDevice(device, event_handler=None)
473 assert device.available is True
474
475 # Register an event handler, it should be called when variable is updated
476 on_event_mock = Mock(return_value=None)
477 profile.on_event = on_event_mock
478 assert profile.is_subscribed is False
479
480 # Check state variables are currently empty
481 assert profile.media_track_number is None
482 assert profile.media_duration is None
483 assert profile.current_track_uri is None
484 assert profile._current_track_meta_data is None
485 assert profile.media_title is None
486 assert profile.media_artist is None
487
488 # Call an invalid and a valid Get action, in one function call
489 await profile._async_poll_state_variables("AVT", ["GetInvalidAction", "GetPositionInfo"], InstanceID=0)
490
491 # Missing (invalid) action should have no effect on valid action
492
493 # on_event should be called with all changed variables
494 expected_service = device.services["urn:schemas-upnp-org:service:AVTransport:1"]
495 expected_changes = [
496 expected_service.state_variables[name]
497 for name in (
498 "CurrentTrack",
499 "CurrentTrackDuration",
500 "CurrentTrackMetaData",
501 "CurrentTrackURI",
502 "RelativeTimePosition",
503 "AbsoluteTimePosition",
504 "RelativeCounterPosition",
505 "AbsoluteCounterPosition",
506 )
507 ]
508 on_event_mock.assert_called_once_with(expected_service, expected_changes)
509
510 # Corresponding state variables should be updated
511 assert profile.media_track_number == 1
512 assert profile.media_duration == 194
513 assert profile.current_track_uri == "uri://1.mp3"
514 assert profile._current_track_meta_data is not None
515 assert profile.media_title == "Test track"
516 assert profile.media_artist == "A & B > C"
517
518 @pytest.mark.asyncio
519 async def test_poll_state_variables_failed_action(self) -> None:
520 """Test failed action used when polling state variables is handled gracefully."""
521 requester = UpnpTestRequester(RESPONSE_MAP)
522 # Good action response
523 requester.response_map[("POST", "http://dlna_dmr:1234/upnp/control/AVTransport1")] = HttpResponse(
524 200, {}, read_file("dlna/dmr/action_GetPositionInfo.xml")
525 )
526
527 factory = UpnpFactory(requester)
528 device = await factory.async_create_device("http://dlna_dmr:1234/device.xml")
529 profile = DmrDevice(device, event_handler=None)
530 assert device.available is True
531
532 # Register an event handler, it should be called when variable is updated
533 on_event_mock = Mock(return_value=None)
534 profile.on_event = on_event_mock
535 assert profile.is_subscribed is False
536
537 # Check state variables are currently empty
538 assert profile.media_track_number is None
539 assert profile.media_duration is None
540 assert profile.current_track_uri is None
541 assert profile._current_track_meta_data is None
542 assert profile.media_title is None
543 assert profile.media_artist is None
544
545 # Failed GetTransportInfo action resulting in an exception
546 requester.exceptions.append(UpnpActionResponseError(status=500, error_code=602, error_desc="Not implemented"))
547
548 # Call a failing and a valid Get action, in one function call
549 await profile._async_poll_state_variables("AVT", ["GetTransportInfo", "GetPositionInfo"], InstanceID=0)
550
551 # Missing (invalid) action should have no effect on valid action
552
553 # on_event should be called with all changed variables
554 expected_service = device.services["urn:schemas-upnp-org:service:AVTransport:1"]
555 expected_changes = [
556 expected_service.state_variables[name]
557 for name in (
558 "CurrentTrack",
559 "CurrentTrackDuration",
560 "CurrentTrackMetaData",
561 "CurrentTrackURI",
562 "RelativeTimePosition",
563 "AbsoluteTimePosition",
564 "RelativeCounterPosition",
565 "AbsoluteCounterPosition",
566 )
567 ]
568 on_event_mock.assert_called_once_with(expected_service, expected_changes)
569
570 # Corresponding state variables should be updated
571 assert profile.media_track_number == 1
572 assert profile.media_duration == 194
573 assert profile.current_track_uri == "uri://1.mp3"
574 assert profile._current_track_meta_data is not None
575 assert profile.media_title == "Test track"
576 assert profile.media_artist == "A & B > C"