test_traversal.py 32 KB

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