3 import xml
.etree
.ElementTree
7 from yt_dlp
.utils
import (
15 from yt_dlp
.utils
.traversal
import (
32 {'index': 0, 'url': 'https://www.example.com/0'},
33 {'index': 1, 'url': 'https://www.example.com/1'},
42 _TEST_HTML
= '''<html><body>
43 <div class="a">1</div>
44 <div class="a" id="x" custom="z">2</div>
45 <div class="b" data-id="y" custom="z">3</div>
47 <p id="d" custom="e">5</p>
52 def test_traversal_base(self
):
53 assert traverse_obj(_TEST_DATA
, ('str',)) == 'str', \
55 assert traverse_obj(_TEST_DATA
, ['str']) == 'str', \
57 assert traverse_obj(_TEST_DATA
, (value
for value
in ('str',))) == 'str', \
59 assert traverse_obj(_TEST_DATA
, 'str') == 'str', \
60 'single items should be treated as a path'
61 assert traverse_obj(_TEST_DATA
, 100) == 100, \
63 assert traverse_obj(_TEST_DATA
, 1.2) == 1.2, \
65 assert traverse_obj(_TEST_DATA
, None) == _TEST_DATA
, \
66 '`None` should not perform any modification'
68 def test_traversal_ellipsis(self
):
69 assert traverse_obj(_TEST_DATA
, ...) == [x
for x
in _TEST_DATA
.values() if x
not in (None, {})], \
70 '`...` should give all non discarded values'
71 assert traverse_obj(_TEST_DATA
, ('urls', 0, ...)) == list(_TEST_DATA
['urls'][0].values()), \
72 '`...` selection for dicts should select all values'
73 assert traverse_obj(_TEST_DATA
, (..., ..., 'url')) == ['https://www.example.com/0', 'https://www.example.com/1'], \
74 'nested `...` queries should work'
75 assert traverse_obj(_TEST_DATA
, (..., ..., 'index')) == list(range(4)), \
76 '`...` query result should be flattened'
77 assert traverse_obj(iter(range(4)), ...) == list(range(4)), \
78 '`...` should accept iterables'
80 def test_traversal_function(self
):
81 filter_func
= lambda x
, y
: x
== 'urls' and isinstance(y
, list)
82 assert traverse_obj(_TEST_DATA
, filter_func
) == [_TEST_DATA
['urls']], \
83 'function as query key should perform a filter based on (key, value)'
84 assert traverse_obj(_TEST_DATA
, lambda _
, x
: isinstance(x
[0], str)) == ['str'], \
85 'exceptions in the query function should be catched'
86 assert traverse_obj(iter(range(4)), lambda _
, x
: x
% 2 == 0) == [0, 2], \
87 'function key should accept iterables'
88 # Wrong function signature should raise (debug mode)
89 with pytest
.raises(Exception):
90 traverse_obj(_TEST_DATA
, lambda a
: ...)
91 with pytest
.raises(Exception):
92 traverse_obj(_TEST_DATA
, lambda a
, b
, c
: ...)
94 def test_traversal_set(self
):
95 # transformation/type, like `expected_type`
96 assert traverse_obj(_TEST_DATA
, (..., {str.upper
})) == ['STR'], \
97 'Function in set should be a transformation'
98 assert traverse_obj(_TEST_DATA
, (..., {str}
)) == ['str'], \
99 'Type in set should be a type filter'
100 assert traverse_obj(_TEST_DATA
, (..., {str, int})) == [100, 'str'], \
101 'Multiple types in set should be a type filter'
102 assert traverse_obj(_TEST_DATA
, {dict}
) == _TEST_DATA
, \
103 'A single set should be wrapped into a path'
104 assert traverse_obj(_TEST_DATA
, (..., {str.upper
})) == ['STR'], \
105 'Transformation function should not raise'
106 expected
= [x
for x
in map(str_or_none
, _TEST_DATA
.values()) if x
is not None]
107 assert traverse_obj(_TEST_DATA
, (..., {str_or_none}
)) == expected
, \
108 'Function in set should be a transformation'
109 assert traverse_obj(_TEST_DATA
, ('fail', {lambda _
: 'const'})) == 'const', \
110 'Function in set should always be called'
111 # Sets with length < 1 or > 1 not including only types should raise
112 with pytest
.raises(Exception):
113 traverse_obj(_TEST_DATA
, set())
114 with pytest
.raises(Exception):
115 traverse_obj(_TEST_DATA
, {str.upper
, str})
117 def test_traversal_slice(self
):
118 _SLICE_DATA
= [0, 1, 2, 3, 4]
120 assert traverse_obj(_TEST_DATA
, ('dict', slice(1))) is None, \
121 'slice on a dictionary should not throw'
122 assert traverse_obj(_SLICE_DATA
, slice(1)) == _SLICE_DATA
[:1], \
123 'slice key should apply slice to sequence'
124 assert traverse_obj(_SLICE_DATA
, slice(1, 2)) == _SLICE_DATA
[1:2], \
125 'slice key should apply slice to sequence'
126 assert traverse_obj(_SLICE_DATA
, slice(1, 4, 2)) == _SLICE_DATA
[1:4:2], \
127 'slice key should apply slice to sequence'
129 def test_traversal_alternatives(self
):
130 assert traverse_obj(_TEST_DATA
, 'fail', 'str') == 'str', \
131 'multiple `paths` should be treated as alternative paths'
132 assert traverse_obj(_TEST_DATA
, 'str', 100) == 'str', \
133 'alternatives should exit early'
134 assert traverse_obj(_TEST_DATA
, 'fail', 'fail') is None, \
135 'alternatives should return `default` if exhausted'
136 assert traverse_obj(_TEST_DATA
, (..., 'fail'), 100) == 100, \
137 'alternatives should track their own branching return'
138 assert traverse_obj(_TEST_DATA
, ('dict', ...), ('data', ...)) == list(_TEST_DATA
['data']), \
139 'alternatives on empty objects should search further'
141 def test_traversal_branching_nesting(self
):
142 assert traverse_obj(_TEST_DATA
, ('urls', (3, 0), 'url')) == ['https://www.example.com/0'], \
143 'tuple as key should be treated as branches'
144 assert traverse_obj(_TEST_DATA
, ('urls', [3, 0], 'url')) == ['https://www.example.com/0'], \
145 'list as key should be treated as branches'
146 assert traverse_obj(_TEST_DATA
, ('urls', ((1, 'fail'), (0, 'url')))) == ['https://www.example.com/0'], \
147 'double nesting in path should be treated as paths'
148 assert traverse_obj(['0', [1, 2]], [(0, 1), 0]) == [1], \
149 'do not fail early on branching'
150 expected
= ['https://www.example.com/0', 'https://www.example.com/1']
151 assert traverse_obj(_TEST_DATA
, ('urls', ((0, ('fail', 'url')), (1, 'url')))) == expected
, \
152 'tripple nesting in path should be treated as branches'
153 assert traverse_obj(_TEST_DATA
, ('urls', ('fail', (..., 'url')))) == expected
, \
154 'ellipsis as branch path start gets flattened'
156 def test_traversal_dict(self
):
157 assert traverse_obj(_TEST_DATA
, {0: 100, 1: 1.2}) == {0: 100, 1: 1.2}, \
158 'dict key should result in a dict with the same keys'
159 expected
= {0: 'https://www.example.com/0'}
160 assert traverse_obj(_TEST_DATA
, {0: ('urls', 0, 'url')}) == expected
, \
161 'dict key should allow paths'
162 expected
= {0: ['https://www.example.com/0']}
163 assert traverse_obj(_TEST_DATA
, {0: ('urls', (3, 0), 'url')}) == expected
, \
164 'tuple in dict path should be treated as branches'
165 assert traverse_obj(_TEST_DATA
, {0: ('urls', ((1, 'fail'), (0, 'url')))}) == expected
, \
166 'double nesting in dict path should be treated as paths'
167 expected
= {0: ['https://www.example.com/1', 'https://www.example.com/0']}
168 assert traverse_obj(_TEST_DATA
, {0: ('urls', ((1, ('fail', 'url')), (0, 'url')))}) == expected
, \
169 'tripple nesting in dict path should be treated as branches'
170 assert traverse_obj(_TEST_DATA
, {0: 'fail'}) == {}, \
171 'remove `None` values when top level dict key fails'
172 assert traverse_obj(_TEST_DATA
, {0: 'fail'}, default
=...) == {0: ...}, \
173 'use `default` if key fails and `default`'
174 assert traverse_obj(_TEST_DATA
, {0: 'dict'}) == {}, \
175 'remove empty values when dict key'
176 assert traverse_obj(_TEST_DATA
, {0: 'dict'}, default
=...) == {0: ...}, \
177 'use `default` when dict key and `default`'
178 assert traverse_obj(_TEST_DATA
, {0: {0: 'fail'}}) == {}, \
179 'remove empty values when nested dict key fails'
180 assert traverse_obj(None, {0: 'fail'}) == {}, \
181 'default to dict if pruned'
182 assert traverse_obj(None, {0: 'fail'}, default
=...) == {0: ...}, \
183 'default to dict if pruned and default is given'
184 assert traverse_obj(_TEST_DATA
, {0: {0: 'fail'}}, default
=...) == {0: {0: ...}}, \
185 'use nested `default` when nested dict key fails and `default`'
186 assert traverse_obj(_TEST_DATA
, {0: ('dict', ...)}) == {}, \
187 'remove key if branch in dict key not successful'
189 def test_traversal_default(self
):
190 _DEFAULT_DATA
= {'None': None, 'int': 0, 'list': []}
192 assert traverse_obj(_DEFAULT_DATA
, 'fail') is None, \
193 'default value should be `None`'
194 assert traverse_obj(_DEFAULT_DATA
, 'fail', 'fail', default
=...) == ..., \
195 'chained fails should result in default'
196 assert traverse_obj(_DEFAULT_DATA
, 'None', 'int') == 0, \
197 'should not short cirquit on `None`'
198 assert traverse_obj(_DEFAULT_DATA
, 'fail', default
=1) == 1, \
199 'invalid dict key should result in `default`'
200 assert traverse_obj(_DEFAULT_DATA
, 'None', default
=1) == 1, \
201 '`None` is a deliberate sentinel and should become `default`'
202 assert traverse_obj(_DEFAULT_DATA
, ('list', 10)) is None, \
203 '`IndexError` should result in `default`'
204 assert traverse_obj(_DEFAULT_DATA
, (..., 'fail'), default
=1) == 1, \
205 'if branched but not successful return `default` if defined, not `[]`'
206 assert traverse_obj(_DEFAULT_DATA
, (..., 'fail'), default
=None) is None, \
207 'if branched but not successful return `default` even if `default` is `None`'
208 assert traverse_obj(_DEFAULT_DATA
, (..., 'fail')) == [], \
209 'if branched but not successful return `[]`, not `default`'
210 assert traverse_obj(_DEFAULT_DATA
, ('list', ...)) == [], \
211 'if branched but object is empty return `[]`, not `default`'
212 assert traverse_obj(None, ...) == [], \
213 'if branched but object is `None` return `[]`, not `default`'
214 assert traverse_obj({0: None}, (0, ...)) == [], \
215 'if branched but state is `None` return `[]`, not `default`'
217 @pytest.mark
.parametrize('path', [
220 100 * ('fail',) + (...,),
221 (...,) + 100 * ('fail',),
223 def test_traversal_branching(self
, path
):
224 assert traverse_obj({}, path
) == [], \
225 'if branched but state is `None`, return `[]` (not `default`)'
226 assert traverse_obj({}, 'fail', path
) == [], \
227 'if branching in last alternative and previous did not match, return `[]` (not `default`)'
228 assert traverse_obj({0: 'x'}, 0, path
) == 'x', \
229 'if branching in last alternative and previous did match, return single value'
230 assert traverse_obj({0: 'x'}, path
, 0) == 'x', \
231 'if branching in first alternative and non-branching path does match, return single value'
232 assert traverse_obj({}, path
, 'fail') is None, \
233 'if branching in first alternative and non-branching path does not match, return `default`'
235 def test_traversal_expected_type(self
):
236 _EXPECTED_TYPE_DATA
= {'str': 'str', 'int': 0}
238 assert traverse_obj(_EXPECTED_TYPE_DATA
, 'str', expected_type
=str) == 'str', \
239 'accept matching `expected_type` type'
240 assert traverse_obj(_EXPECTED_TYPE_DATA
, 'str', expected_type
=int) is None, \
241 'reject non matching `expected_type` type'
242 assert traverse_obj(_EXPECTED_TYPE_DATA
, 'int', expected_type
=lambda x
: str(x
)) == '0', \
243 'transform type using type function'
244 assert traverse_obj(_EXPECTED_TYPE_DATA
, 'str', expected_type
=lambda _
: 1 / 0) is None, \
245 'wrap expected_type fuction in try_call'
246 assert traverse_obj(_EXPECTED_TYPE_DATA
, ..., expected_type
=str) == ['str'], \
247 'eliminate items that expected_type fails on'
248 assert traverse_obj(_TEST_DATA
, {0: 100, 1: 1.2}, expected_type
=int) == {0: 100}, \
249 'type as expected_type should filter dict values'
250 assert traverse_obj(_TEST_DATA
, {0: 100, 1: 1.2, 2: 'None'}, expected_type
=str_or_none
) == {0: '100', 1: '1.2'}, \
251 'function as expected_type should transform dict values'
252 assert traverse_obj(_TEST_DATA
, ({0: 1.2}, 0, {int_or_none}
), expected_type
=int) == 1, \
253 'expected_type should not filter non final dict values'
254 assert traverse_obj(_TEST_DATA
, {0: {0: 100, 1: 'str'}}, expected_type
=int) == {0: {0: 100}}, \
255 'expected_type should transform deep dict values'
256 assert traverse_obj(_TEST_DATA
, [({0: '...'}, {0: '...'})], expected_type
=type(...)) == [{0: ...}, {0: ...}], \
257 'expected_type should transform branched dict values'
258 assert traverse_obj({1: {3: 4}}, [(1, 2), 3], expected_type
=int) == [4], \
259 'expected_type regression for type matching in tuple branching'
260 assert traverse_obj(_TEST_DATA
, ['data', ...], expected_type
=int) == [], \
261 'expected_type regression for type matching in dict result'
263 def test_traversal_get_all(self
):
264 _GET_ALL_DATA
= {'key': [0, 1, 2]}
266 assert traverse_obj(_GET_ALL_DATA
, ('key', ...), get_all
=False) == 0, \
267 'if not `get_all`, return only first matching value'
268 assert traverse_obj(_GET_ALL_DATA
, ..., get_all
=False) == [0, 1, 2], \
269 'do not overflatten if not `get_all`'
271 def test_traversal_casesense(self
):
276 0: {'KeY': 'value2'},
280 assert traverse_obj(_CASESENSE_DATA
, 'key') is None, \
281 'dict keys should be case sensitive unless `casesense`'
282 assert traverse_obj(_CASESENSE_DATA
, 'keY', casesense
=False) == 'value0', \
283 'allow non matching key case if `casesense`'
284 assert traverse_obj(_CASESENSE_DATA
, [0, ('keY',)], casesense
=False) == ['value1'], \
285 'allow non matching key case in branch if `casesense`'
286 assert traverse_obj(_CASESENSE_DATA
, [0, ([0, 'keY'],)], casesense
=False) == ['value2'], \
287 'allow non matching key case in branch path if `casesense`'
289 def test_traversal_traverse_string(self
):
290 _TRAVERSE_STRING_DATA
= {'str': 'str', 1.2: 1.2}
292 assert traverse_obj(_TRAVERSE_STRING_DATA
, ('str', 0)) is None, \
293 'do not traverse into string if not `traverse_string`'
294 assert traverse_obj(_TRAVERSE_STRING_DATA
, ('str', 0), traverse_string
=True) == 's', \
295 'traverse into string if `traverse_string`'
296 assert traverse_obj(_TRAVERSE_STRING_DATA
, (1.2, 1), traverse_string
=True) == '.', \
297 'traverse into converted data if `traverse_string`'
298 assert traverse_obj(_TRAVERSE_STRING_DATA
, ('str', ...), traverse_string
=True) == 'str', \
299 '`...` should result in string (same value) if `traverse_string`'
300 assert traverse_obj(_TRAVERSE_STRING_DATA
, ('str', slice(0, None, 2)), traverse_string
=True) == 'sr', \
301 '`slice` should result in string if `traverse_string`'
302 assert traverse_obj(_TRAVERSE_STRING_DATA
, ('str', lambda i
, v
: i
or v
== 's'), traverse_string
=True) == 'str', \
303 'function should result in string if `traverse_string`'
304 assert traverse_obj(_TRAVERSE_STRING_DATA
, ('str', (0, 2)), traverse_string
=True) == ['s', 'r'], \
305 'branching should result in list if `traverse_string`'
306 assert traverse_obj({}, (0, ...), traverse_string
=True) == [], \
307 'branching should result in list if `traverse_string`'
308 assert traverse_obj({}, (0, lambda x
, y
: True), traverse_string
=True) == [], \
309 'branching should result in list if `traverse_string`'
310 assert traverse_obj({}, (0, slice(1)), traverse_string
=True) == [], \
311 'branching should result in list if `traverse_string`'
313 def test_traversal_re(self
):
314 mobj
= re
.fullmatch(r
'0(12)(?P<group>3)(4)?', '0123')
315 assert traverse_obj(mobj
, ...) == [x
for x
in mobj
.groups() if x
is not None], \
316 '`...` on a `re.Match` should give its `groups()`'
317 assert traverse_obj(mobj
, lambda k
, _
: k
in (0, 2)) == ['0123', '3'], \
318 'function on a `re.Match` should give groupno, value starting at 0'
319 assert traverse_obj(mobj
, 'group') == '3', \
320 'str key on a `re.Match` should give group with that name'
321 assert traverse_obj(mobj
, 2) == '3', \
322 'int key on a `re.Match` should give group with that name'
323 assert traverse_obj(mobj
, 'gRoUp', casesense
=False) == '3', \
324 'str key on a `re.Match` should respect casesense'
325 assert traverse_obj(mobj
, 'fail') is None, \
326 'failing str key on a `re.Match` should return `default`'
327 assert traverse_obj(mobj
, 'gRoUpS', casesense
=False) is None, \
328 'failing str key on a `re.Match` should return `default`'
329 assert traverse_obj(mobj
, 8) is None, \
330 'failing int key on a `re.Match` should return `default`'
331 assert traverse_obj(mobj
, lambda k
, _
: k
in (0, 'group')) == ['0123', '3'], \
332 'function on a `re.Match` should give group name as well'
334 def test_traversal_xml_etree(self
):
335 etree
= xml
.etree
.ElementTree
.fromstring('''<?xml version="1.0"?>
337 <country name="Liechtenstein">
340 <gdppc>141100</gdppc>
341 <neighbor name="Austria" direction="E"/>
342 <neighbor name="Switzerland" direction="W"/>
344 <country name="Singapore">
348 <neighbor name="Malaysia" direction="N"/>
350 <country name="Panama">
354 <neighbor name="Costa Rica" direction="W"/>
355 <neighbor name="Colombia" direction="E"/>
358 assert traverse_obj(etree
, '') == etree
, \
359 'empty str key should return the element itself'
360 assert traverse_obj(etree
, 'country') == list(etree
), \
361 'str key should lead all children with that tag name'
362 assert traverse_obj(etree
, ...) == list(etree
), \
363 '`...` as key should return all children'
364 assert traverse_obj(etree
, lambda _
, x
: x
[0].text
== '4') == [etree
[1]], \
365 'function as key should get element as value'
366 assert traverse_obj(etree
, lambda i
, _
: i
== 1) == [etree
[1]], \
367 'function as key should get index as key'
368 assert traverse_obj(etree
, 0) == etree
[0], \
369 'int key should return the nth child'
370 expected
= ['Austria', 'Switzerland', 'Malaysia', 'Costa Rica', 'Colombia']
371 assert traverse_obj(etree
, './/neighbor/@name') == expected
, \
372 '`@<attribute>` at end of path should give that attribute'
373 assert traverse_obj(etree
, '//neighbor/@fail') == [None, None, None, None, None], \
374 '`@<nonexistant>` at end of path should give `None`'
375 assert traverse_obj(etree
, ('//neighbor/@', 2)) == {'name': 'Malaysia', 'direction': 'N'}, \
376 '`@` should give the full attribute dict'
377 assert traverse_obj(etree
, '//year/text()') == ['2008', '2011', '2011'], \
378 '`text()` at end of path should give the inner text'
379 assert traverse_obj(etree
, '//*[@direction]/@direction') == ['E', 'W', 'N', 'W', 'E'], \
380 'full Python xpath features should be supported'
381 assert traverse_obj(etree
, (0, '@name')) == 'Liechtenstein', \
382 'special transformations should act on current element'
383 assert traverse_obj(etree
, ('country', 0, ..., 'text()', {int_or_none}
)) == [1, 2008, 141100], \
384 'special transformations should act on current element'
386 def test_traversal_unbranching(self
):
387 assert traverse_obj(_TEST_DATA
, [(100, 1.2), all
]) == [100, 1.2], \
388 '`all` should give all results as list'
389 assert traverse_obj(_TEST_DATA
, [(100, 1.2), any
]) == 100, \
390 '`any` should give the first result'
391 assert traverse_obj(_TEST_DATA
, [100, all
]) == [100], \
392 '`all` should give list if non branching'
393 assert traverse_obj(_TEST_DATA
, [100, any
]) == 100, \
394 '`any` should give single item if non branching'
395 assert traverse_obj(_TEST_DATA
, [('dict', 'None', 100), all
]) == [100], \
396 '`all` should filter `None` and empty dict'
397 assert traverse_obj(_TEST_DATA
, [('dict', 'None', 100), any
]) == 100, \
398 '`any` should filter `None` and empty dict'
399 assert traverse_obj(_TEST_DATA
, [{
400 'all': [('dict', 'None', 100, 1.2), all
],
401 'any': [('dict', 'None', 100, 1.2), any
],
402 }]) == {'all': [100, 1.2], 'any': 100}, \
403 '`all`/`any` should apply to each dict path separately'
404 assert traverse_obj(_TEST_DATA
, [{
405 'all': [('dict', 'None', 100, 1.2), all
],
406 'any': [('dict', 'None', 100, 1.2), any
],
407 }], get_all
=False) == {'all': [100, 1.2], 'any': 100}, \
408 '`all`/`any` should apply to dict regardless of `get_all`'
409 assert traverse_obj(_TEST_DATA
, [('dict', 'None', 100, 1.2), all
, {float}
]) is None, \
410 '`all` should reset branching status'
411 assert traverse_obj(_TEST_DATA
, [('dict', 'None', 100, 1.2), any
, {float}
]) is None, \
412 '`any` should reset branching status'
413 assert traverse_obj(_TEST_DATA
, [('dict', 'None', 100, 1.2), all
, ..., {float}
]) == [1.2], \
414 '`all` should allow further branching'
415 assert traverse_obj(_TEST_DATA
, [('dict', 'None', 'urls', 'data'), any
, ..., 'index']) == [0, 1], \
416 '`any` should allow further branching'
418 def test_traversal_morsel(self
):
430 morsel
= http
.cookies
.Morsel()
431 morsel
.set('item_key', 'item_value', 'coded_value')
432 morsel
.update(values
)
433 values
['key'] = 'item_key'
434 values
['value'] = 'item_value'
436 for key
, value
in values
.items():
437 assert traverse_obj(morsel
, key
) == value
, \
438 'Morsel should provide access to all values'
439 assert traverse_obj(morsel
, ...) == list(values
.values()), \
440 '`...` should yield all values'
441 assert traverse_obj(morsel
, lambda k
, v
: True) == list(values
.values()), \
442 'function key should yield all values'
443 assert traverse_obj(morsel
, [(None,), any
]) == morsel
, \
444 'Morsel should not be implicitly changed to dict on usage'
446 def test_traversal_filter(self
):
447 data
= [None, False, True, 0, 1, 0.0, 1.1, '', 'str', {}, {0: 0}, [], [1]]
449 assert traverse_obj(data
, [..., filter]) == [True, 1, 1.1, 'str', {0: 0}, [1]], \
450 '`filter` should filter falsy values'
453 class TestTraversalHelpers
:
454 def test_traversal_require(self
):
455 with pytest
.raises(ExtractorError
):
456 traverse_obj(_TEST_DATA
, ['None', {require('value')}])
457 assert traverse_obj(_TEST_DATA
, ['str', {require('value')}]) == 'str', \
458 '`require` should pass through non `None` values'
460 def test_subs_list_to_dict(self
):
461 assert traverse_obj([
462 {'name': 'de', 'url': 'https://example.com/subs/de.vtt'},
463 {'name': 'en', 'url': 'https://example.com/subs/en1.ass'},
464 {'name': 'en', 'url': 'https://example.com/subs/en2.ass'},
468 }, all
, {subs_list_to_dict}
]) == {
469 'de': [{'url': 'https://example.com/subs/de.vtt'}],
471 {'url': 'https://example.com/subs/en1.ass'},
472 {'url': 'https://example.com/subs/en2.ass'},
474 }, 'function should build subtitle dict from list of subtitles'
475 assert traverse_obj([
476 {'name': 'de', 'url': 'https://example.com/subs/de.ass'},
478 {'name': 'en', 'content': 'content'},
479 {'url': 'https://example.com/subs/en'},
484 }, all
, {subs_list_to_dict(lang
=None)}]) == {
485 'de': [{'url': 'https://example.com/subs/de.ass'}],
486 'en': [{'data': 'content'}],
487 }, 'subs with mandatory items missing should be filtered'
488 assert traverse_obj([
489 {'url': 'https://example.com/subs/de.ass', 'name': 'de'},
490 {'url': 'https://example.com/subs/en', 'name': 'en'},
493 'ext': ['url', {determine_ext(default_ext
=None)}],
495 }, all
, {subs_list_to_dict(ext
='ext')}]) == {
496 'de': [{'url': 'https://example.com/subs/de.ass', 'ext': 'ass'}],
497 'en': [{'url': 'https://example.com/subs/en', 'ext': 'ext'}],
498 }, '`ext` should set default ext but leave existing value untouched'
499 assert traverse_obj([
500 {'name': 'en', 'url': 'https://example.com/subs/en2', 'prio': True},
501 {'name': 'en', 'url': 'https://example.com/subs/en1', 'prio': False},
504 'quality': ['prio', {int}
],
506 }, all
, {subs_list_to_dict(ext
='ext')}]) == {'en': [
507 {'url': 'https://example.com/subs/en1', 'ext': 'ext'},
508 {'url': 'https://example.com/subs/en2', 'ext': 'ext'},
509 ]}, '`quality` key should sort subtitle list accordingly'
510 assert traverse_obj([
511 {'name': 'de', 'url': 'https://example.com/subs/de.ass'},
513 {'name': 'en', 'content': 'content'},
514 {'url': 'https://example.com/subs/en'},
519 }, all
, {subs_list_to_dict(lang
='en')}]) == {
520 'de': [{'url': 'https://example.com/subs/de.ass'}],
523 {'url': 'https://example.com/subs/en'},
525 }, 'optionally provided lang should be used if no id available'
526 assert traverse_obj([
527 {'name': 1, 'url': 'https://example.com/subs/de1'},
528 {'name': {}, 'url': 'https://example.com/subs/de2'},
529 {'name': 'de', 'ext': 1, 'url': 'https://example.com/subs/de3'},
530 {'name': 'de', 'ext': {}, 'url': 'https://example.com/subs/de4'},
535 }, all
, {subs_list_to_dict(lang
=None)}]) == {
537 {'url': 'https://example.com/subs/de3'},
538 {'url': 'https://example.com/subs/de4'},
540 }, 'non str types should be ignored for id and ext'
541 assert traverse_obj([
542 {'name': 1, 'url': 'https://example.com/subs/de1'},
543 {'name': {}, 'url': 'https://example.com/subs/de2'},
544 {'name': 'de', 'ext': 1, 'url': 'https://example.com/subs/de3'},
545 {'name': 'de', 'ext': {}, 'url': 'https://example.com/subs/de4'},
550 }, all
, {subs_list_to_dict(lang
='de')}]) == {
552 {'url': 'https://example.com/subs/de1'},
553 {'url': 'https://example.com/subs/de2'},
554 {'url': 'https://example.com/subs/de3'},
555 {'url': 'https://example.com/subs/de4'},
557 }, 'non str types should be replaced by default id'
559 def test_trim_str(self
):
560 with pytest
.raises(TypeError):
561 trim_str('positional')
563 assert callable(trim_str(start
='a'))
564 assert trim_str(start
='ab')('abc') == 'c'
565 assert trim_str(end
='bc')('abc') == 'a'
566 assert trim_str(start
='a', end
='c')('abc') == 'b'
567 assert trim_str(start
='ab', end
='c')('abc') == ''
568 assert trim_str(start
='a', end
='bc')('abc') == ''
569 assert trim_str(start
='ab', end
='bc')('abc') == ''
570 assert trim_str(start
='abc', end
='abc')('abc') == ''
571 assert trim_str(start
='', end
='')('abc') == 'abc'
573 def test_unpack(self
):
574 assert unpack(lambda *x
: ''.join(map(str, x
)))([1, 2, 3]) == '123'
575 assert unpack(join_nonempty
)([1, 2, 3]) == '1-2-3'
576 assert unpack(join_nonempty
, delim
=' ')([1, 2, 3]) == '1 2 3'
577 with pytest
.raises(TypeError):
578 unpack(join_nonempty
)()
579 with pytest
.raises(TypeError):
582 def test_find_element(self
):
583 for improper_kwargs
in [
584 dict(attr
='data-id'),
586 dict(attr
='data-id', value
='y', cls
='a'),
587 dict(attr
='data-id', value
='y', id='x'),
588 dict(cls
='a', id='x'),
589 dict(cls
='a', tag
='p'),
590 dict(cls
='[ab]', regex
=True),
592 with pytest
.raises(AssertionError):
593 find_element(**improper_kwargs
)(_TEST_HTML
)
595 assert find_element(cls
='a')(_TEST_HTML
) == '1'
596 assert find_element(cls
='a', html
=True)(_TEST_HTML
) == '<div class="a">1</div>'
597 assert find_element(id='x')(_TEST_HTML
) == '2'
598 assert find_element(id='[ex]')(_TEST_HTML
) is None
599 assert find_element(id='[ex]', regex
=True)(_TEST_HTML
) == '2'
600 assert find_element(id='x', html
=True)(_TEST_HTML
) == '<div class="a" id="x" custom="z">2</div>'
601 assert find_element(attr
='data-id', value
='y')(_TEST_HTML
) == '3'
602 assert find_element(attr
='data-id', value
='y(?:es)?')(_TEST_HTML
) is None
603 assert find_element(attr
='data-id', value
='y(?:es)?', regex
=True)(_TEST_HTML
) == '3'
605 attr
='data-id', value
='y', html
=True)(_TEST_HTML
) == '<div class="b" data-id="y" custom="z">3</div>'
607 def test_find_elements(self
):
608 for improper_kwargs
in [
610 dict(attr
='data-id'),
612 dict(attr
='data-id', value
='y', cls
='a'),
613 dict(cls
='a', tag
='div'),
614 dict(cls
='[ab]', regex
=True),
616 with pytest
.raises(AssertionError):
617 find_elements(**improper_kwargs
)(_TEST_HTML
)
619 assert find_elements(cls
='a')(_TEST_HTML
) == ['1', '2', '4']
620 assert find_elements(cls
='a', html
=True)(_TEST_HTML
) == [
621 '<div class="a">1</div>', '<div class="a" id="x" custom="z">2</div>', '<p class="a">4</p>']
622 assert find_elements(attr
='custom', value
='z')(_TEST_HTML
) == ['2', '3']
623 assert find_elements(attr
='custom', value
='[ez]')(_TEST_HTML
) == []
624 assert find_elements(attr
='custom', value
='[ez]', regex
=True)(_TEST_HTML
) == ['2', '3', '5']
628 def test_dict_get(self
):
636 d
= {**FALSE_VALUES
, 'a': 42}
637 assert dict_get(d
, 'a') == 42
638 assert dict_get(d
, 'b') is None
639 assert dict_get(d
, 'b', 42) == 42
640 assert dict_get(d
, ('a',)) == 42
641 assert dict_get(d
, ('b', 'a')) == 42
642 assert dict_get(d
, ('b', 'c', 'a', 'd')) == 42
643 assert dict_get(d
, ('b', 'c')) is None
644 assert dict_get(d
, ('b', 'c'), 42) == 42
645 for key
, false_value
in FALSE_VALUES
.items():
646 assert dict_get(d
, ('b', 'c', key
)) is None
647 assert dict_get(d
, ('b', 'c', key
), skip_false_values
=False) == false_value