Debian Codegraph @

tests/test_client.py

raw symbols SCIP
1 """Unit tests for client_factory and client modules."""
2
3 # pylint: disable=too-many-lines
4
5 from datetime import datetime, timedelta, timezone
6 from typing import MutableMapping
7
8 import defusedxml.ElementTree as DET
9 import pytest
10
11 from async_upnp_client.client import UpnpStateVariable
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 UpnpActionError,
16 UpnpActionErrorCode,
17 UpnpActionResponseError,
18 UpnpError,
19 UpnpResponseError,
20 UpnpValueError,
21 UpnpXmlContentError,
22 UpnpXmlParseError,
23 )
24
25 from .conftest import RESPONSE_MAP, UpnpTestRequester, read_file
26
27
28 class TestUpnpStateVariable:
29 """Tests for UpnpStateVariable."""
30
31 @pytest.mark.asyncio
32 async def test_init(self) -> None:
33 """Test initialization of a UpnpDevice."""
34 requester = UpnpTestRequester(RESPONSE_MAP)
35 factory = UpnpFactory(requester)
36 device = await factory.async_create_device("http://dlna_dmr:1234/device.xml")
37 assert device
38 assert device.device_type == "urn:schemas-upnp-org:device:MediaRenderer:1"
39
40 service = device.service("urn:schemas-upnp-org:service:RenderingControl:1")
41 assert service
42
43 service_by_id = device.service_id("urn:upnp-org:serviceId:RenderingControl")
44 assert service_by_id == service
45
46 state_var = service.state_variable("Volume")
47 assert state_var
48
49 action = service.action("GetVolume")
50 assert action
51
52 argument = action.argument("InstanceID")
53 assert argument
54
55 @pytest.mark.asyncio
56 async def test_init_embedded_device(self) -> None:
57 """Test initialization of a embedded UpnpDevice."""
58 requester = UpnpTestRequester(RESPONSE_MAP)
59 factory = UpnpFactory(requester)
60 device = await factory.async_create_device("http://igd:1234/device.xml")
61 assert device
62 assert device.device_type == "urn:schemas-upnp-org:device:InternetGatewayDevice:1"
63
64 embedded_device = device.embedded_devices["urn:schemas-upnp-org:device:WANDevice:1"]
65 assert embedded_device
66 assert embedded_device.device_type == "urn:schemas-upnp-org:device:WANDevice:1"
67 assert embedded_device.parent_device == device
68
69 @pytest.mark.asyncio
70 async def test_init_xml(self) -> None:
71 """Test XML is stored on every part of the UpnpDevice."""
72 requester = UpnpTestRequester(RESPONSE_MAP)
73 factory = UpnpFactory(requester)
74 device = await factory.async_create_device("http://dlna_dmr:1234/device.xml")
75 assert device.xml is not None
76
77 service = device.service("urn:schemas-upnp-org:service:RenderingControl:1")
78 assert service.xml is not None
79
80 state_var = service.state_variable("Volume")
81 assert state_var.xml is not None
82
83 action = service.action("GetVolume")
84 assert action.xml is not None
85
86 argument = action.argument("InstanceID")
87 assert argument is not None
88 assert argument.xml is not None
89
90 @pytest.mark.asyncio
91 async def test_init_bad_xml(self) -> None:
92 """Test missing device element in device description."""
93 responses = dict(RESPONSE_MAP)
94 responses[("GET", "http://dlna_dmr:1234/device.xml")] = HttpResponse(
95 200,
96 {},
97 read_file("dlna/dmr/device_bad_namespace.xml"),
98 )
99 requester = UpnpTestRequester(responses)
100 factory = UpnpFactory(requester)
101 with pytest.raises(UpnpXmlContentError):
102 await factory.async_create_device("http://dlna_dmr:1234/device.xml")
103
104 @pytest.mark.asyncio
105 async def test_empty_descriptor(self) -> None:
106 """Test device with an empty descriptor file called in description.xml."""
107 responses = dict(RESPONSE_MAP)
108 responses[("GET", "http://dlna_dmr:1234/device.xml")] = HttpResponse(
109 200,
110 {},
111 read_file("dlna/dmr/device_with_empty_descriptor.xml"),
112 )
113 requester = UpnpTestRequester(responses)
114 factory = UpnpFactory(requester)
115 with pytest.raises(UpnpXmlParseError):
116 await factory.async_create_device("http://dlna_dmr:1234/device.xml")
117
118 @pytest.mark.asyncio
119 async def test_empty_descriptor_non_strict(self) -> None:
120 """Test device with an empty descriptor file called in description.xml."""
121 responses = dict(RESPONSE_MAP)
122 responses[("GET", "http://dlna_dmr:1234/device.xml")] = HttpResponse(
123 200,
124 {},
125 read_file("dlna/dmr/device_with_empty_descriptor.xml"),
126 )
127 requester = UpnpTestRequester(responses)
128 factory = UpnpFactory(requester, non_strict=True)
129 await factory.async_create_device("http://dlna_dmr:1234/device.xml")
130
131 @pytest.mark.asyncio
132 async def test_set_value_volume(self) -> None:
133 """Test calling parsing/reading values from UpnpStateVariable."""
134 requester = UpnpTestRequester(RESPONSE_MAP)
135 factory = UpnpFactory(requester)
136 device = await factory.async_create_device("http://dlna_dmr:1234/device.xml")
137 service = device.service("urn:schemas-upnp-org:service:RenderingControl:1")
138 state_var = service.state_variable("Volume")
139
140 state_var.value = 10
141 assert state_var.value == 10
142 assert state_var.upnp_value == "10"
143
144 state_var.upnp_value = "20"
145 assert state_var.value == 20
146 assert state_var.upnp_value == "20"
147
148 @pytest.mark.asyncio
149 async def test_set_value_mute(self) -> None:
150 """Test setting a boolean value."""
151 requester = UpnpTestRequester(RESPONSE_MAP)
152 factory = UpnpFactory(requester)
153 device = await factory.async_create_device("http://dlna_dmr:1234/device.xml")
154 service = device.service("urn:schemas-upnp-org:service:RenderingControl:1")
155 state_var = service.state_variable("Mute")
156
157 state_var.value = True
158 assert state_var.value is True
159 assert state_var.upnp_value == "1"
160
161 state_var.value = False
162 assert state_var.value is False
163 assert state_var.upnp_value == "0"
164
165 state_var.upnp_value = "1"
166 assert state_var.value is True
167 assert state_var.upnp_value == "1"
168
169 state_var.upnp_value = "0"
170 assert state_var.value is False
171 assert state_var.upnp_value == "0"
172
173 @pytest.mark.asyncio
174 async def test_value_min_max(self) -> None:
175 """Test min/max restrictions."""
176 requester = UpnpTestRequester(RESPONSE_MAP)
177 factory = UpnpFactory(requester)
178 device = await factory.async_create_device("http://dlna_dmr:1234/device.xml")
179 service = device.service("urn:schemas-upnp-org:service:RenderingControl:1")
180 state_var = service.state_variable("Volume")
181
182 assert state_var.min_value == 0
183 assert state_var.max_value == 100
184 assert state_var.step_value == 1
185
186 state_var.value = 10
187 assert state_var.value == 10
188
189 try:
190 state_var.value = -10
191 assert False
192 except UpnpValueError:
193 pass
194
195 try:
196 state_var.value = 110
197 assert False
198 except UpnpValueError:
199 pass
200
201 @pytest.mark.asyncio
202 async def test_value_min_max_validation_disable(self) -> None:
203 """Test if min/max validations can be disabled."""
204 requester = UpnpTestRequester(RESPONSE_MAP)
205 factory = UpnpFactory(requester, non_strict=True)
206 device = await factory.async_create_device("http://dlna_dmr:1234/device.xml")
207 service = device.service("urn:schemas-upnp-org:service:RenderingControl:1")
208 state_var = service.state_variable("Volume")
209
210 # min/max/step are set
211 assert state_var.min_value == 0
212 assert state_var.max_value == 100
213 assert state_var.step_value == 1
214
215 # min/max are not validated
216 state_var.value = -10
217 assert state_var.value == -10
218
219 state_var.value = 110
220 assert state_var.value == 110
221
222 @pytest.mark.asyncio
223 async def test_value_allowed_value(self) -> None:
224 """Test handling allowed values."""
225 requester = UpnpTestRequester(RESPONSE_MAP)
226 factory = UpnpFactory(requester)
227 device = await factory.async_create_device("http://dlna_dmr:1234/device.xml")
228 service = device.service("urn:schemas-upnp-org:service:RenderingControl:1")
229 state_var = service.state_variable("A_ARG_TYPE_Channel")
230
231 assert state_var.allowed_values == {"Master"}
232 assert state_var.normalized_allowed_values == {"master"}
233
234 # should be ok
235 state_var.value = "Master"
236 assert state_var.value == "Master"
237
238 try:
239 state_var.value = "Left"
240 assert False
241 except UpnpValueError:
242 pass
243
244 @pytest.mark.asyncio
245 async def test_value_upnp_value_error(self) -> None:
246 """Test handling invalid values in response."""
247 requester = UpnpTestRequester(RESPONSE_MAP)
248 factory = UpnpFactory(requester, non_strict=True)
249 device = await factory.async_create_device("http://dlna_dmr:1234/device.xml")
250 service = device.service("urn:schemas-upnp-org:service:RenderingControl:1")
251 state_var = service.state_variable("Volume")
252
253 # should be ok
254 state_var.upnp_value = "50"
255 assert state_var.value == 50
256
257 # should set UpnpStateVariable.UPNP_VALUE_ERROR
258 state_var.upnp_value = "abc"
259 assert state_var.value is None
260 assert state_var.value_unchecked is UpnpStateVariable.UPNP_VALUE_ERROR
261
262 @pytest.mark.asyncio
263 async def test_value_date_time(self) -> None:
264 """Test parsing of datetime."""
265 requester = UpnpTestRequester(RESPONSE_MAP)
266 factory = UpnpFactory(requester, non_strict=True)
267 device = await factory.async_create_device("http://dlna_dmr:1234/device.xml")
268 service = device.service("urn:schemas-upnp-org:service:RenderingControl:1")
269 state_var = service.state_variable("SV1")
270
271 # should be ok
272 state_var.upnp_value = "1985-04-12T10:15:30"
273 assert state_var.value == datetime(1985, 4, 12, 10, 15, 30)
274
275 @pytest.mark.asyncio
276 async def test_value_date_time_tz(self) -> None:
277 """Test parsing of date_time with a timezone."""
278 requester = UpnpTestRequester(RESPONSE_MAP)
279 factory = UpnpFactory(requester, non_strict=True)
280 device = await factory.async_create_device("http://dlna_dmr:1234/device.xml")
281 service = device.service("urn:schemas-upnp-org:service:RenderingControl:1")
282 state_var = service.state_variable("SV2")
283 assert state_var is not None
284
285 # should be ok
286 state_var.upnp_value = "1985-04-12T10:15:30+0400"
287 assert state_var.value == datetime(1985, 4, 12, 10, 15, 30, tzinfo=timezone(timedelta(hours=4)))
288 assert state_var.value.tzinfo is not None
289
290 @pytest.mark.asyncio
291 async def test_send_events(self) -> None:
292 """Test if send_events is properly handled."""
293 requester = UpnpTestRequester(RESPONSE_MAP)
294 factory = UpnpFactory(requester)
295 device = await factory.async_create_device("http://dlna_dmr:1234/device.xml")
296 service = device.service("urn:schemas-upnp-org:service:RenderingControl:1")
297
298 state_var = service.state_variable("A_ARG_TYPE_InstanceID") # old style
299 assert state_var.send_events is False
300
301 state_var = service.state_variable("A_ARG_TYPE_Channel") # new style
302 assert state_var.send_events is False
303
304 state_var = service.state_variable("Volume") # broken/none given
305 assert state_var.send_events is False
306
307 state_var = service.state_variable("LastChange")
308 assert state_var.send_events is True
309
310 @pytest.mark.asyncio
311 async def test_big_ints(self) -> None:
312 """Test state variable types i8 and ui8."""
313 responses = dict(RESPONSE_MAP)
314 responses[("GET", "http://dlna_dms:1234/ContentDirectory_1.xml")] = HttpResponse(
315 200,
316 {},
317 read_file("scpd_i8.xml"),
318 )
319 requester = UpnpTestRequester(responses)
320 factory = UpnpFactory(requester)
321 device = await factory.async_create_device("http://dlna_dms:1234/device.xml")
322 assert device is not None
323
324 @pytest.mark.asyncio
325 async def test_parse_state_variable_datetime_invalid_case_non_strict(self) -> None:
326 """Test that non-standard 'DateTime' is accepted in non-strict mode (issue #299)."""
327 responses = dict(RESPONSE_MAP)
328 responses[("GET", "http://dlna_dmr:1234/RenderingControl_1.xml")] = HttpResponse(
329 200,
330 {},
331 read_file("dlna/dmr/RenderingControl_1_invalid_datetime_case.xml"),
332 )
333
334 requester = UpnpTestRequester(responses)
335 factory = UpnpFactory(requester, non_strict=True)
336 device = await factory.async_create_device("http://dlna_dmr:1234/device.xml")
337 service = device.service("urn:schemas-upnp-org:service:RenderingControl:1")
338 state_var = service.state_variable("SV1")
339
340 state_var.upnp_value = "1985-04-12T10:15:30"
341 assert state_var.value == datetime(1985, 4, 12, 10, 15, 30)
342
343 @pytest.mark.asyncio
344 async def test_parse_state_variable_datetime_invalid_case_strict(self) -> None:
345 """Test that non-standard 'DateTime' fails in strict mode (issue #299)."""
346 responses = dict(RESPONSE_MAP)
347 responses[("GET", "http://dlna_dmr:1234/RenderingControl_1.xml")] = HttpResponse(
348 200,
349 {},
350 read_file("dlna/dmr/RenderingControl_1_invalid_datetime_case.xml"),
351 )
352
353 requester = UpnpTestRequester(responses)
354 factory = UpnpFactory(requester)
355
356 with pytest.raises(UpnpError, match="Unsupported data type"):
357 await factory.async_create_device("http://dlna_dmr:1234/device.xml")
358
359
360 class TestUpnpAction:
361 """Tests for UpnpAction."""
362
363 @pytest.mark.asyncio
364 async def test_init(self) -> None:
365 """Test Initializing a UpnpAction."""
366 requester = UpnpTestRequester(RESPONSE_MAP)
367 factory = UpnpFactory(requester)
368 device = await factory.async_create_device("http://dlna_dmr:1234/device.xml")
369 service = device.service("urn:schemas-upnp-org:service:RenderingControl:1")
370 action = service.action("GetVolume")
371
372 assert action
373 assert action.name == "GetVolume"
374
375 @pytest.mark.asyncio
376 async def test_valid_arguments(self) -> None:
377 """Test validating arguments of an action."""
378 requester = UpnpTestRequester(RESPONSE_MAP)
379 factory = UpnpFactory(requester)
380 device = await factory.async_create_device("http://dlna_dmr:1234/device.xml")
381 service = device.service("urn:schemas-upnp-org:service:RenderingControl:1")
382 action = service.action("SetVolume")
383
384 # all ok
385 action.validate_arguments(InstanceID=0, Channel="Master", DesiredVolume=10)
386
387 # invalid type for InstanceID
388 try:
389 action.validate_arguments(InstanceID="0", Channel="Master", DesiredVolume=10)
390 assert False
391 except UpnpValueError:
392 pass
393
394 # missing DesiredVolume
395 try:
396 action.validate_arguments(InstanceID="0", Channel="Master")
397 assert False
398 except UpnpValueError:
399 pass
400
401 @pytest.mark.asyncio
402 async def test_format_request(self) -> None:
403 """Test the request an action sends."""
404 requester = UpnpTestRequester(RESPONSE_MAP)
405 factory = UpnpFactory(requester)
406 device = await factory.async_create_device("http://dlna_dmr:1234/device.xml")
407 service = device.service("urn:schemas-upnp-org:service:RenderingControl:1")
408 action = service.action("SetVolume")
409
410 service_type = "urn:schemas-upnp-org:service:RenderingControl:1"
411 request = action.create_request(InstanceID=0, Channel="Master", DesiredVolume=10)
412
413 root = DET.fromstring(request.body)
414 namespace = {"rc_service": service_type}
415 assert root.find(".//rc_service:SetVolume", namespace) is not None
416 assert root.find(".//DesiredVolume", namespace) is not None
417
418 @pytest.mark.asyncio
419 async def test_format_request_escape(self) -> None:
420 """Test escaping the request an action sends."""
421 requester = UpnpTestRequester(RESPONSE_MAP)
422 factory = UpnpFactory(requester)
423 device = await factory.async_create_device("http://dlna_dmr:1234/device.xml")
424 service = device.service("urn:schemas-upnp-org:service:AVTransport:1")
425 action = service.action("SetAVTransportURI")
426
427 service_type = "urn:schemas-upnp-org:service:AVTransport:1"
428 metadata = "<item>test thing</item>"
429 request = action.create_request(
430 InstanceID=0,
431 CurrentURI="http://example.org/file.mp3",
432 CurrentURIMetaData=metadata,
433 )
434
435 root = DET.fromstring(request.body)
436 namespace = {"avt_service": service_type}
437 assert root.find(".//avt_service:SetAVTransportURI", namespace) is not None
438 assert root.find(".//CurrentURIMetaData", namespace) is not None
439 assert root.findtext(".//CurrentURIMetaData", None, namespace) == "<item>test thing</item>"
440
441 current_uri_metadata_el = root.find(".//CurrentURIMetaData", namespace)
442 assert current_uri_metadata_el is not None
443 # This shouldn't have any children, due to its contents being escaped.
444 assert current_uri_metadata_el.findall("./") == []
445
446 @pytest.mark.asyncio
447 async def test_parse_response(self) -> None:
448 """Test calling an action and handling its response."""
449 requester = UpnpTestRequester(RESPONSE_MAP)
450 factory = UpnpFactory(requester)
451 device = await factory.async_create_device("http://dlna_dmr:1234/device.xml")
452 service = device.service("urn:schemas-upnp-org:service:RenderingControl:1")
453 action = service.action("GetVolume")
454
455 service_type = "urn:schemas-upnp-org:service:RenderingControl:1"
456 response_body = read_file("dlna/dmr/action_GetVolume.xml")
457 response = HttpResponse(200, {}, response_body)
458 result = action.parse_response(service_type, response)
459 assert result == {"CurrentVolume": 3}
460
461 @pytest.mark.asyncio
462 async def test_parse_response_empty(self) -> None:
463 """Test calling an action and handling an empty XML response."""
464 requester = UpnpTestRequester(RESPONSE_MAP)
465 factory = UpnpFactory(requester)
466 device = await factory.async_create_device("http://dlna_dmr:1234/device.xml")
467 service = device.service("urn:schemas-upnp-org:service:RenderingControl:1")
468 action = service.action("SetVolume")
469
470 service_type = "urn:schemas-upnp-org:service:RenderingControl:1"
471 response_body = read_file("dlna/dmr/action_SetVolume.xml")
472 response = HttpResponse(200, {}, response_body)
473 result = action.parse_response(service_type, response)
474 assert result == {}
475
476 @pytest.mark.asyncio
477 async def test_parse_response_error(self) -> None:
478 """Test calling and action and handling an invalid XML response."""
479 requester = UpnpTestRequester(RESPONSE_MAP)
480 factory = UpnpFactory(requester)
481 device = await factory.async_create_device("http://dlna_dmr:1234/device.xml")
482 service = device.service("urn:schemas-upnp-org:service:RenderingControl:1")
483 action = service.action("GetVolume")
484
485 service_type = "urn:schemas-upnp-org:service:RenderingControl:1"
486 response_body = read_file("dlna/dmr/action_GetVolumeError.xml")
487 response = HttpResponse(200, {}, response_body)
488 with pytest.raises(UpnpActionError) as exc:
489 action.parse_response(service_type, response)
490 assert exc.value.error_code == UpnpActionErrorCode.INVALID_ARGS
491 assert exc.value.error_desc == "Invalid Args"
492
493 @pytest.mark.asyncio
494 async def test_parse_response_escape(self) -> None:
495 """Test calling an action and properly (not) escaping the response."""
496 requester = UpnpTestRequester(RESPONSE_MAP)
497 factory = UpnpFactory(requester)
498 device = await factory.async_create_device("http://dlna_dmr:1234/device.xml")
499 service = device.service("urn:schemas-upnp-org:service:AVTransport:1")
500 action = service.action("GetMediaInfo")
501
502 service_type = "urn:schemas-upnp-org:service:AVTransport:1"
503 response_body = read_file("dlna/dmr/action_GetMediaInfo.xml")
504 response = HttpResponse(200, {}, response_body)
505 result = action.parse_response(service_type, response)
506 assert result == {
507 "CurrentURI": "uri://1.mp3",
508 "CurrentURIMetaData": "<DIDL-Lite "
509 'xmlns="urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/" '
510 'xmlns:dc="http://purl.org/dc/elements/1.1/" '
511 'xmlns:dlna="urn:schemas-dlna-org:metadata-1-0/" '
512 'xmlns:sec="http://www.sec.co.kr/" '
513 'xmlns:upnp="urn:schemas-upnp-org:metadata-1-0/upnp/" '
514 'xmlns:xbmc="urn:schemas-xbmc-org:metadata-1-0/">'
515 '<item id="" parentID="" refID="" restricted="1">'
516 "<upnp:artist>A &amp; B &gt; C</upnp:artist>"
517 "</item>"
518 "</DIDL-Lite>",
519 "MediaDuration": "00:00:01",
520 "NextURI": "",
521 "NextURIMetaData": "",
522 "NrTracks": 1,
523 "PlayMedium": "NONE",
524 "RecordMedium": "NOT_IMPLEMENTED",
525 "WriteStatus": "NOT_IMPLEMENTED",
526 }
527
528 @pytest.mark.asyncio
529 async def test_parse_response_no_service_type_version(self) -> None:
530 """Test calling and action and handling a response without service type number."""
531 requester = UpnpTestRequester(RESPONSE_MAP)
532 factory = UpnpFactory(requester)
533 device = await factory.async_create_device("http://dlna_dmr:1234/device.xml")
534 service = device.service("urn:schemas-upnp-org:service:RenderingControl:1")
535 action = service.action("GetVolume")
536
537 service_type = "urn:schemas-upnp-org:service:RenderingControl:1"
538 response_body = read_file("dlna/dmr/action_GetVolumeInvalidServiceType.xml")
539 response = HttpResponse(200, {}, response_body)
540 try:
541 action.parse_response(service_type, response)
542 assert False
543 except UpnpError:
544 pass
545
546 @pytest.mark.asyncio
547 async def test_parse_response_no_service_type_version_2(self) -> None:
548 """Test calling and action and handling a response without service type number."""
549 requester = UpnpTestRequester(RESPONSE_MAP)
550 factory = UpnpFactory(requester)
551 device = await factory.async_create_device("http://dlna_dmr:1234/device.xml")
552 service = device.service("urn:schemas-upnp-org:service:AVTransport:1")
553 action = service.action("GetTransportInfo")
554
555 service_type = "urn:schemas-upnp-org:service:AVTransport:1"
556 response_body = read_file("dlna/dmr/action_GetTransportInfoInvalidServiceType.xml")
557 response = HttpResponse(200, {}, response_body)
558 try:
559 action.parse_response(service_type, response)
560 assert False
561 except UpnpError:
562 pass
563
564 @pytest.mark.asyncio
565 async def test_unknown_out_argument(self) -> None:
566 """Test calling an action and handling an unknown out-argument."""
567 requester = UpnpTestRequester(RESPONSE_MAP)
568 device_url = "http://dlna_dmr:1234/device.xml"
569 service_type = "urn:schemas-upnp-org:service:RenderingControl:1"
570 test_action = "GetVolume"
571
572 factory = UpnpFactory(requester)
573 device = await factory.async_create_device(device_url)
574 service = device.service(service_type)
575 action = service.action(test_action)
576
577 response_body = read_file("dlna/dmr/action_GetVolumeExtraOutParameter.xml")
578 response = HttpResponse(200, {}, response_body)
579 try:
580 action.parse_response(service_type, response)
581 assert False
582 except UpnpError:
583 pass
584
585 factory = UpnpFactory(requester, non_strict=True)
586 device = await factory.async_create_device(device_url)
587 service = device.service(service_type)
588 action = service.action(test_action)
589
590 try:
591 action.parse_response(service_type, response)
592 except UpnpError:
593 assert False
594
595 @pytest.mark.asyncio
596 async def test_response_invalid_xml_namespaces(self) -> None:
597 """Test parsing response with invalid XML namespaces."""
598 requester = UpnpTestRequester(RESPONSE_MAP)
599 device_url = "http://igd:1234/device.xml"
600 service_type = "urn:schemas-upnp-org:service:WANIPConnection:1"
601 test_action = "DeletePortMapping"
602
603 # Test strict mode.
604 factory = UpnpFactory(requester)
605 device = await factory.async_create_device(device_url)
606 service = device.find_service(service_type)
607 assert service is not None
608 action = service.action(test_action)
609
610 response_body = read_file("igd/action_WANPIPConnection_DeletePortMapping.xml")
611 response = HttpResponse(200, {}, response_body)
612 try:
613 action.parse_response(service_type, response)
614 assert False
615 except UpnpError:
616 pass
617
618 # Test non-strict mode.
619 factory = UpnpFactory(requester, non_strict=True)
620 device = await factory.async_create_device(device_url)
621 service = device.find_service(service_type)
622 assert service is not None
623 action = service.action(test_action)
624
625 try:
626 action.parse_response(service_type, response)
627 except UpnpError:
628 assert False
629
630
631 class TestUpnpService:
632 """Tests for UpnpService."""
633
634 @pytest.mark.asyncio
635 async def test_init(self) -> None:
636 """Test initializing a UpnpService."""
637 requester = UpnpTestRequester(RESPONSE_MAP)
638 factory = UpnpFactory(requester)
639 device = await factory.async_create_device("http://dlna_dmr:1234/device.xml")
640 service = device.service("urn:schemas-upnp-org:service:RenderingControl:1")
641
642 base_url = "http://dlna_dmr:1234"
643 assert service
644 assert service.service_type == "urn:schemas-upnp-org:service:RenderingControl:1"
645 assert service.control_url == base_url + "/upnp/control/RenderingControl1"
646 assert service.event_sub_url == base_url + "/upnp/event/RenderingControl1"
647 assert service.scpd_url == base_url + "/RenderingControl_1.xml"
648
649 @pytest.mark.asyncio
650 async def test_state_variables_actions(self) -> None:
651 """Test eding a UpnpStateVariable."""
652 requester = UpnpTestRequester(RESPONSE_MAP)
653 factory = UpnpFactory(requester)
654 device = await factory.async_create_device("http://dlna_dmr:1234/device.xml")
655 service = device.service("urn:schemas-upnp-org:service:RenderingControl:1")
656
657 state_var = service.state_variable("Volume")
658 assert state_var
659
660 action = service.action("GetVolume")
661 assert action
662
663 @pytest.mark.asyncio
664 async def test_call_action(self) -> None:
665 """Test calling a UpnpAction."""
666 responses: MutableMapping = {
667 (
668 "POST",
669 "http://dlna_dmr:1234/upnp/control/RenderingControl1",
670 ): HttpResponse(
671 200,
672 {},
673 read_file("dlna/dmr/action_GetVolume.xml"),
674 )
675 }
676 responses.update(RESPONSE_MAP)
677 requester = UpnpTestRequester(responses)
678 factory = UpnpFactory(requester)
679 device = await factory.async_create_device("http://dlna_dmr:1234/device.xml")
680 service = device.service("urn:schemas-upnp-org:service:RenderingControl:1")
681 action = service.action("GetVolume")
682
683 result = await service.async_call_action(action, InstanceID=0, Channel="Master")
684 assert result["CurrentVolume"] == 3
685
686 @pytest.mark.asyncio
687 async def test_soap_fault_http_error(self) -> None:
688 """Test an action response with HTTP error and SOAP fault raises exception."""
689 responses: MutableMapping = {
690 (
691 "POST",
692 "http://dlna_dmr:1234/upnp/control/RenderingControl1",
693 ): HttpResponse(
694 500,
695 {},
696 read_file("dlna/dmr/action_GetVolumeError.xml"),
697 )
698 }
699 responses.update(RESPONSE_MAP)
700 requester = UpnpTestRequester(responses)
701 factory = UpnpFactory(requester)
702 device = await factory.async_create_device("http://dlna_dmr:1234/device.xml")
703 service = device.service("urn:schemas-upnp-org:service:RenderingControl:1")
704 action = service.action("GetVolume")
705
706 with pytest.raises(UpnpActionResponseError) as exc:
707 await service.async_call_action(action, InstanceID=0, Channel="Master")
708 assert exc.value.error_code == UpnpActionErrorCode.INVALID_ARGS
709 assert exc.value.error_desc == "Invalid Args"
710 assert exc.value.status == 500
711
712 @pytest.mark.asyncio
713 async def test_http_error(self) -> None:
714 """Test an action response with HTTP error and blank body raises exception."""
715 responses: MutableMapping = {
716 (
717 "POST",
718 "http://dlna_dmr:1234/upnp/control/RenderingControl1",
719 ): HttpResponse(
720 500,
721 {},
722 "",
723 )
724 }
725 responses.update(RESPONSE_MAP)
726 requester = UpnpTestRequester(responses)
727 factory = UpnpFactory(requester)
728 device = await factory.async_create_device("http://dlna_dmr:1234/device.xml")
729 service = device.service("urn:schemas-upnp-org:service:RenderingControl:1")
730 action = service.action("GetVolume")
731
732 with pytest.raises(UpnpResponseError) as exc:
733 await service.async_call_action(action, InstanceID=0, Channel="Master")
734 assert exc.value.status == 500
735
736 @pytest.mark.asyncio
737 async def test_soap_fault_http_ok(self) -> None:
738 """Test an action response with HTTP OK but SOAP fault raises exception."""
739 responses: MutableMapping = {
740 (
741 "POST",
742 "http://dlna_dmr:1234/upnp/control/RenderingControl1",
743 ): HttpResponse(
744 200,
745 {},
746 read_file("dlna/dmr/action_GetVolumeError.xml"),
747 )
748 }
749 responses.update(RESPONSE_MAP)
750 requester = UpnpTestRequester(responses)
751 factory = UpnpFactory(requester)
752 device = await factory.async_create_device("http://dlna_dmr:1234/device.xml")
753 service = device.service("urn:schemas-upnp-org:service:RenderingControl:1")
754 action = service.action("GetVolume")
755
756 with pytest.raises(UpnpActionError) as exc:
757 await service.async_call_action(action, InstanceID=0, Channel="Master")
758 assert exc.value.error_code == UpnpActionErrorCode.INVALID_ARGS
759 assert exc.value.error_desc == "Invalid Args"
760
761 @pytest.mark.parametrize(
762 "rc_doc",
763 [
764 "dlna/dmr/RenderingControl_1_bad_namespace.xml", # Bad namespace
765 "dlna/dmr/RenderingControl_1_bad_root_tag.xml", # Wrong root tag
766 "dlna/dmr/RenderingControl_1_missing_state_table.xml", # Missing state table
767 ],
768 )
769 @pytest.mark.asyncio
770 async def test_bad_scpd_strict(self, rc_doc: str) -> None:
771 """Test handling of bad service descriptions in strict mode."""
772 responses = dict(RESPONSE_MAP)
773 responses[("GET", "http://dlna_dmr:1234/RenderingControl_1.xml")] = HttpResponse(
774 200,
775 {},
776 read_file(rc_doc),
777 )
778 requester = UpnpTestRequester(responses)
779 factory = UpnpFactory(requester)
780 with pytest.raises(UpnpXmlContentError):
781 await factory.async_create_device("http://dlna_dmr:1234/device.xml")
782
783 @pytest.mark.parametrize(
784 "rc_doc",
785 [
786 "dlna/dmr/RenderingControl_1_bad_namespace.xml", # Bad namespace
787 "dlna/dmr/RenderingControl_1_bad_root_tag.xml", # Wrong root tag
788 "dlna/dmr/RenderingControl_1_missing_state_table.xml", # Missing state table
789 ],
790 )
791 @pytest.mark.asyncio
792 async def test_bad_scpd_non_strict_fails(self, rc_doc: str) -> None:
793 """Test bad SCPD in non-strict mode."""
794 responses = dict(RESPONSE_MAP)
795 responses[("GET", "http://dlna_dmr:1234/RenderingControl_1.xml")] = HttpResponse(
796 200,
797 {},
798 read_file(rc_doc),
799 )
800 requester = UpnpTestRequester(responses)
801 factory = UpnpFactory(requester, non_strict=True)
802 device = await factory.async_create_device("http://dlna_dmr:1234/device.xml")
803 # Known good service
804 assert device.services["urn:schemas-upnp-org:service:AVTransport:1"]
805 # Bad service will also exist, to some extent
806 assert device.services["urn:schemas-upnp-org:service:RenderingControl:1"]
807
808
809 class TestServiceUrlSsrf:
810 """Tests that absolute service URLs to a foreign host are rejected (SSRF).
811
812 Per UDA 1.1/2.0, SCPDURL/controlURL/eventSubURL must be relative to the
813 device description URL. An absolute URL to a different host is treated as a
814 potential SSRF vector.
815 """
816
817 DEVICE_URL = "http://192.168.1.50:1234/device.xml"
818 SCPD_XML = (
819 '<?xml version="1.0"?>'
820 '<scpd xmlns="urn:schemas-upnp-org:service-1-0">'
821 "<specVersion><major>1</major><minor>0</minor></specVersion>"
822 "<actionList/><serviceStateTable/></scpd>"
823 )
824
825 def _device_xml(
826 self,
827 *,
828 control_url: str = "/svc/control",
829 scpd_url: str = "/svc.xml",
830 event_sub_url: str = "/svc/event",
831 ) -> str:
832 """Build a single-service device description."""
833 return (
834 '<?xml version="1.0"?>'
835 '<root xmlns="urn:schemas-upnp-org:device-1-0">'
836 "<specVersion><major>1</major><minor>0</minor></specVersion>"
837 "<device>"
838 "<deviceType>urn:schemas-upnp-org:device:Foo:1</deviceType>"
839 "<friendlyName>Foo</friendlyName>"
840 "<UDN>uuid:00000000-0000-0000-0000-0000000000aa</UDN>"
841 "<serviceList><service>"
842 "<serviceType>urn:schemas-upnp-org:service:Bar:1</serviceType>"
843 "<serviceId>urn:upnp-org:serviceId:Bar</serviceId>"
844 f"<SCPDURL>{scpd_url}</SCPDURL>"
845 f"<controlURL>{control_url}</controlURL>"
846 f"<eventSubURL>{event_sub_url}</eventSubURL>"
847 "</service></serviceList>"
848 "</device></root>"
849 )
850
851 @pytest.mark.asyncio
852 async def test_foreign_host_control_url_raises_in_strict_mode(self) -> None:
853 """A controlURL pointing at another host raises in strict mode."""
854 xml = self._device_xml(control_url="http://169.254.169.254/latest/meta-data/")
855 requester = UpnpTestRequester({("GET", self.DEVICE_URL): HttpResponse(200, {}, xml)})
856 factory = UpnpFactory(requester)
857
858 with pytest.raises(UpnpError):
859 await factory.async_create_device(self.DEVICE_URL)
860
861 @pytest.mark.asyncio
862 async def test_foreign_host_control_url_skipped_in_non_strict_mode(self) -> None:
863 """A controlURL pointing at another host is skipped (not fetched) in non-strict mode."""
864 xml = self._device_xml(control_url="http://169.254.169.254/latest/meta-data/")
865 # No response registered for the foreign host: if it were requested, it would KeyError.
866 requester = UpnpTestRequester({("GET", self.DEVICE_URL): HttpResponse(200, {}, xml)})
867 factory = UpnpFactory(requester, non_strict=True)
868
869 device = await factory.async_create_device(self.DEVICE_URL)
870
871 assert device.services == {}
872
873 @pytest.mark.asyncio
874 async def test_malformed_control_url_raises_upnp_error_not_value_error(self) -> None:
875 """A malformed service URL fails closed as UpnpError, not an unhandled ValueError."""
876 xml = self._device_xml(control_url="http://[::1") # unbalanced IPv6 bracket
877 requester = UpnpTestRequester({("GET", self.DEVICE_URL): HttpResponse(200, {}, xml)})
878 factory = UpnpFactory(requester)
879
880 with pytest.raises(UpnpError):
881 await factory.async_create_device(self.DEVICE_URL)
882
883 @pytest.mark.asyncio
884 async def test_malformed_control_url_skipped_in_non_strict_mode(self) -> None:
885 """A malformed service URL is skipped (not raised) in non-strict mode."""
886 xml = self._device_xml(control_url="http://[::1") # unbalanced IPv6 bracket
887 requester = UpnpTestRequester({("GET", self.DEVICE_URL): HttpResponse(200, {}, xml)})
888 factory = UpnpFactory(requester, non_strict=True)
889
890 device = await factory.async_create_device(self.DEVICE_URL)
891
892 assert device.services == {}
893
894 @pytest.mark.asyncio
895 async def test_foreign_host_scpd_url_raises_in_strict_mode(self) -> None:
896 """An SCPDURL pointing at another host raises before being fetched."""
897 xml = self._device_xml(scpd_url="http://127.0.0.1:8123/api/states")
898 requester = UpnpTestRequester({("GET", self.DEVICE_URL): HttpResponse(200, {}, xml)})
899 factory = UpnpFactory(requester)
900
901 with pytest.raises(UpnpError):
902 await factory.async_create_device(self.DEVICE_URL)
903
904 @pytest.mark.asyncio
905 async def test_absolute_same_host_urls_allowed(self) -> None:
906 """Absolute URLs to the device's own host are allowed (spec-compliant resolution)."""
907 xml = self._device_xml(
908 scpd_url="http://192.168.1.50:1234/svc.xml",
909 control_url="http://192.168.1.50:1234/svc/control",
910 event_sub_url="http://192.168.1.50:1234/svc/event",
911 )
912 requester = UpnpTestRequester(
913 {
914 ("GET", self.DEVICE_URL): HttpResponse(200, {}, xml),
915 ("GET", "http://192.168.1.50:1234/svc.xml"): HttpResponse(200, {}, self.SCPD_XML),
916 }
917 )
918 factory = UpnpFactory(requester, non_strict=True)
919
920 device = await factory.async_create_device(self.DEVICE_URL)
921
922 service = device.service("urn:schemas-upnp-org:service:Bar:1")
923 assert service.control_url == "http://192.168.1.50:1234/svc/control"
924 assert service.event_sub_url == "http://192.168.1.50:1234/svc/event"
925
926 @pytest.mark.asyncio
927 async def test_relative_urls_allowed(self) -> None:
928 """Ordinary relative service URLs resolve against the device URL and are allowed."""
929 xml = self._device_xml()
930 requester = UpnpTestRequester(
931 {
932 ("GET", self.DEVICE_URL): HttpResponse(200, {}, xml),
933 ("GET", "http://192.168.1.50:1234/svc.xml"): HttpResponse(200, {}, self.SCPD_XML),
934 }
935 )
936 factory = UpnpFactory(requester, non_strict=True)
937
938 device = await factory.async_create_device(self.DEVICE_URL)
939
940 service = device.service("urn:schemas-upnp-org:service:Bar:1")
941 assert service.control_url == "http://192.168.1.50:1234/svc/control"
942
943 @pytest.mark.asyncio
944 async def test_absolute_same_host_different_port_allowed(self) -> None:
945 """An absolute URL to the device's host on a different port is allowed.
946
947 The SSRF boundary is the host: a different port on the device's own host
948 is the device talking to itself, not a cross-host request. Some devices
949 legitimately serve control/eventing on a different port than the device
950 description, so the host-only check intentionally permits this.
951 """
952 xml = self._device_xml(
953 scpd_url="http://192.168.1.50:1234/svc.xml",
954 control_url="http://192.168.1.50:8080/svc/control",
955 event_sub_url="http://192.168.1.50:8080/svc/event",
956 )
957 requester = UpnpTestRequester(
958 {
959 ("GET", self.DEVICE_URL): HttpResponse(200, {}, xml),
960 ("GET", "http://192.168.1.50:1234/svc.xml"): HttpResponse(200, {}, self.SCPD_XML),
961 }
962 )
963 factory = UpnpFactory(requester, non_strict=True)
964
965 device = await factory.async_create_device(self.DEVICE_URL)
966
967 service = device.service("urn:schemas-upnp-org:service:Bar:1")
968 assert service.control_url == "http://192.168.1.50:8080/svc/control"
969
970 @pytest.mark.asyncio
971 async def test_ipv6_link_local_zone_id_mismatch_allowed(self) -> None:
972 """Absolute service URLs without a zone ID match a device URL that has one.
973
974 SSDP discovery adds zone IDs to link-local IPv6 device URLs, but
975 devices typically omit them from service URLs in their XML. The SSRF
976 host comparison must strip zone IDs so these are not falsely rejected.
977 """
978 device_url = "http://[fe80::218:ddff:fe0a:517d%252]:80/dms/device.xml"
979 xml = self._device_xml(
980 scpd_url="http://[fe80::218:ddff:fe0a:517d]:80/svc.xml",
981 control_url="http://[fe80::218:ddff:fe0a:517d]:80/dms/control",
982 event_sub_url="http://[fe80::218:ddff:fe0a:517d]:80/dms/event",
983 )
984 requester = UpnpTestRequester(
985 {
986 ("GET", device_url): HttpResponse(200, {}, xml),
987 (
988 "GET",
989 "http://[fe80::218:ddff:fe0a:517d]:80/svc.xml",
990 ): HttpResponse(200, {}, self.SCPD_XML),
991 }
992 )
993 factory = UpnpFactory(requester, non_strict=True)
994
995 device = await factory.async_create_device(device_url)
996
997 service = device.service("urn:schemas-upnp-org:service:Bar:1")
998 assert service.control_url == "http://[fe80::218:ddff:fe0a:517d]:80/dms/control"
999
1000 @pytest.mark.asyncio
1001 async def test_ipv6_different_zone_ids_rejected_in_strict_mode(self) -> None:
1002 """Service URLs with a different zone ID than the device URL are rejected."""
1003 device_url = "http://[fe80::1%251]:80/device.xml"
1004 xml = self._device_xml(
1005 control_url="http://[fe80::1%252]:80/svc/control",
1006 )
1007 requester = UpnpTestRequester({("GET", device_url): HttpResponse(200, {}, xml)})
1008 factory = UpnpFactory(requester)
1009
1010 with pytest.raises(UpnpError):
1011 await factory.async_create_device(device_url)
1012
1013 @pytest.mark.asyncio
1014 async def test_ipv6_service_introduces_zone_rejected(self) -> None:
1015 """A service URL that adds a zone ID absent from the device URL is rejected."""
1016 device_url = "http://[fe80::1]:80/device.xml"
1017 xml = self._device_xml(
1018 control_url="http://[fe80::1%252]:80/svc/control",
1019 )
1020 requester = UpnpTestRequester({("GET", device_url): HttpResponse(200, {}, xml)})
1021 factory = UpnpFactory(requester)
1022
1023 with pytest.raises(UpnpError):
1024 await factory.async_create_device(device_url)
1025
1026 @pytest.mark.asyncio
1027 async def test_ipv6_different_addresses_with_zones_rejected(self) -> None:
1028 """Different IPv6 addresses are rejected even when both carry zone IDs."""
1029 device_url = "http://[fe80::1%251]:80/device.xml"
1030 xml = self._device_xml(
1031 control_url="http://[fe80::2%251]:80/svc/control",
1032 )
1033 requester = UpnpTestRequester({("GET", device_url): HttpResponse(200, {}, xml)})
1034 factory = UpnpFactory(requester)
1035
1036 with pytest.raises(UpnpError):
1037 await factory.async_create_device(device_url)