test_traversal.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  1. #!/usr/bin/env python
  2. # coding: utf-8
  3. from __future__ import unicode_literals
  4. # Allow direct execution
  5. import os
  6. import sys
  7. import unittest
  8. sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
  9. import re
  10. from youtube_dl.traversal import (
  11. dict_get,
  12. get_first,
  13. T,
  14. traverse_obj,
  15. )
  16. from youtube_dl.compat import (
  17. compat_etree_fromstring,
  18. compat_http_cookies,
  19. compat_str,
  20. )
  21. from youtube_dl.utils import (
  22. int_or_none,
  23. str_or_none,
  24. )
  25. _TEST_DATA = {
  26. 100: 100,
  27. 1.2: 1.2,
  28. 'str': 'str',
  29. 'None': None,
  30. '...': Ellipsis,
  31. 'urls': [
  32. {'index': 0, 'url': 'https://www.example.com/0'},
  33. {'index': 1, 'url': 'https://www.example.com/1'},
  34. ],
  35. 'data': (
  36. {'index': 2},
  37. {'index': 3},
  38. ),
  39. 'dict': {},
  40. }
  41. if sys.version_info < (3, 0):
  42. class _TestCase(unittest.TestCase):
  43. def assertCountEqual(self, *args, **kwargs):
  44. return self.assertItemsEqual(*args, **kwargs)
  45. else:
  46. _TestCase = unittest.TestCase
  47. class TestTraversal(_TestCase):
  48. def assertMaybeCountEqual(self, *args, **kwargs):
  49. if sys.version_info < (3, 7):
  50. # random dict order
  51. return self.assertCountEqual(*args, **kwargs)
  52. else:
  53. return self.assertEqual(*args, **kwargs)
  54. def test_traverse_obj(self):
  55. # instant compat
  56. str = compat_str
  57. # define a pukka Iterable
  58. def iter_range(stop):
  59. for from_ in range(stop):
  60. yield from_
  61. # Test base functionality
  62. self.assertEqual(traverse_obj(_TEST_DATA, ('str',)), 'str',
  63. msg='allow tuple path')
  64. self.assertEqual(traverse_obj(_TEST_DATA, ['str']), 'str',
  65. msg='allow list path')
  66. self.assertEqual(traverse_obj(_TEST_DATA, (value for value in ("str",))), 'str',
  67. msg='allow iterable path')
  68. self.assertEqual(traverse_obj(_TEST_DATA, 'str'), 'str',
  69. msg='single items should be treated as a path')
  70. self.assertEqual(traverse_obj(_TEST_DATA, None), _TEST_DATA)
  71. self.assertEqual(traverse_obj(_TEST_DATA, 100), 100)
  72. self.assertEqual(traverse_obj(_TEST_DATA, 1.2), 1.2)
  73. # Test Ellipsis behavior
  74. self.assertCountEqual(traverse_obj(_TEST_DATA, Ellipsis),
  75. (item for item in _TEST_DATA.values() if item not in (None, {})),
  76. msg='`...` should give all non-discarded values')
  77. self.assertCountEqual(traverse_obj(_TEST_DATA, ('urls', 0, Ellipsis)), _TEST_DATA['urls'][0].values(),
  78. msg='`...` selection for dicts should select all values')
  79. self.assertEqual(traverse_obj(_TEST_DATA, (Ellipsis, Ellipsis, 'url')),
  80. ['https://www.example.com/0', 'https://www.example.com/1'],
  81. msg='nested `...` queries should work')
  82. self.assertCountEqual(traverse_obj(_TEST_DATA, (Ellipsis, Ellipsis, 'index')), iter_range(4),
  83. msg='`...` query result should be flattened')
  84. self.assertEqual(traverse_obj(iter(range(4)), Ellipsis), list(range(4)),
  85. msg='`...` should accept iterables')
  86. # Test function as key
  87. self.assertEqual(traverse_obj(_TEST_DATA, lambda x, y: x == 'urls' and isinstance(y, list)),
  88. [_TEST_DATA['urls']],
  89. msg='function as query key should perform a filter based on (key, value)')
  90. self.assertCountEqual(traverse_obj(_TEST_DATA, lambda _, x: isinstance(x[0], str)), set(('str',)),
  91. msg='exceptions in the query function should be caught')
  92. self.assertEqual(traverse_obj(iter(range(4)), lambda _, x: x % 2 == 0), [0, 2],
  93. msg='function key should accept iterables')
  94. if __debug__:
  95. with self.assertRaises(Exception, msg='Wrong function signature should raise in debug'):
  96. traverse_obj(_TEST_DATA, lambda a: Ellipsis)
  97. with self.assertRaises(Exception, msg='Wrong function signature should raise in debug'):
  98. traverse_obj(_TEST_DATA, lambda a, b, c: Ellipsis)
  99. # Test set as key (transformation/type, like `expected_type`)
  100. self.assertEqual(traverse_obj(_TEST_DATA, (Ellipsis, T(str.upper), )), ['STR'],
  101. msg='Function in set should be a transformation')
  102. self.assertEqual(traverse_obj(_TEST_DATA, ('fail', T(lambda _: 'const'))), 'const',
  103. msg='Function in set should always be called')
  104. self.assertEqual(traverse_obj(_TEST_DATA, (Ellipsis, T(str))), ['str'],
  105. msg='Type in set should be a type filter')
  106. self.assertMaybeCountEqual(traverse_obj(_TEST_DATA, (Ellipsis, T(str, int))), [100, 'str'],
  107. msg='Multiple types in set should be a type filter')
  108. self.assertEqual(traverse_obj(_TEST_DATA, T(dict)), _TEST_DATA,
  109. msg='A single set should be wrapped into a path')
  110. self.assertEqual(traverse_obj(_TEST_DATA, (Ellipsis, T(str.upper))), ['STR'],
  111. msg='Transformation function should not raise')
  112. self.assertMaybeCountEqual(traverse_obj(_TEST_DATA, (Ellipsis, T(str_or_none))),
  113. [item for item in map(str_or_none, _TEST_DATA.values()) if item is not None],
  114. msg='Function in set should be a transformation')
  115. if __debug__:
  116. with self.assertRaises(Exception, msg='Sets with length != 1 should raise in debug'):
  117. traverse_obj(_TEST_DATA, set())
  118. with self.assertRaises(Exception, msg='Sets with length != 1 should raise in debug'):
  119. traverse_obj(_TEST_DATA, set((str.upper, str)))
  120. # Test `slice` as a key
  121. _SLICE_DATA = [0, 1, 2, 3, 4]
  122. self.assertEqual(traverse_obj(_TEST_DATA, ('dict', slice(1))), None,
  123. msg='slice on a dictionary should not throw')
  124. self.assertEqual(traverse_obj(_SLICE_DATA, slice(1)), _SLICE_DATA[:1],
  125. msg='slice key should apply slice to sequence')
  126. self.assertEqual(traverse_obj(_SLICE_DATA, slice(1, 2)), _SLICE_DATA[1:2],
  127. msg='slice key should apply slice to sequence')
  128. self.assertEqual(traverse_obj(_SLICE_DATA, slice(1, 4, 2)), _SLICE_DATA[1:4:2],
  129. msg='slice key should apply slice to sequence')
  130. # Test alternative paths
  131. self.assertEqual(traverse_obj(_TEST_DATA, 'fail', 'str'), 'str',
  132. msg='multiple `paths` should be treated as alternative paths')
  133. self.assertEqual(traverse_obj(_TEST_DATA, 'str', 100), 'str',
  134. msg='alternatives should exit early')
  135. self.assertEqual(traverse_obj(_TEST_DATA, 'fail', 'fail'), None,
  136. msg='alternatives should return `default` if exhausted')
  137. self.assertEqual(traverse_obj(_TEST_DATA, (Ellipsis, 'fail'), 100), 100,
  138. msg='alternatives should track their own branching return')
  139. self.assertEqual(traverse_obj(_TEST_DATA, ('dict', Ellipsis), ('data', Ellipsis)), list(_TEST_DATA['data']),
  140. msg='alternatives on empty objects should search further')
  141. # Test branch and path nesting
  142. self.assertEqual(traverse_obj(_TEST_DATA, ('urls', (3, 0), 'url')), ['https://www.example.com/0'],
  143. msg='tuple as key should be treated as branches')
  144. self.assertEqual(traverse_obj(_TEST_DATA, ('urls', [3, 0], 'url')), ['https://www.example.com/0'],
  145. msg='list as key should be treated as branches')
  146. self.assertEqual(traverse_obj(_TEST_DATA, ('urls', ((1, 'fail'), (0, 'url')))), ['https://www.example.com/0'],
  147. msg='double nesting in path should be treated as paths')
  148. self.assertEqual(traverse_obj(['0', [1, 2]], [(0, 1), 0]), [1],
  149. msg='do not fail early on branching')
  150. self.assertCountEqual(traverse_obj(_TEST_DATA, ('urls', ((1, ('fail', 'url')), (0, 'url')))),
  151. ['https://www.example.com/0', 'https://www.example.com/1'],
  152. msg='triple nesting in path should be treated as branches')
  153. self.assertEqual(traverse_obj(_TEST_DATA, ('urls', ('fail', (Ellipsis, 'url')))),
  154. ['https://www.example.com/0', 'https://www.example.com/1'],
  155. msg='ellipsis as branch path start gets flattened')
  156. # Test dictionary as key
  157. self.assertEqual(traverse_obj(_TEST_DATA, {0: 100, 1: 1.2}), {0: 100, 1: 1.2},
  158. msg='dict key should result in a dict with the same keys')
  159. self.assertEqual(traverse_obj(_TEST_DATA, {0: ('urls', 0, 'url')}),
  160. {0: 'https://www.example.com/0'},
  161. msg='dict key should allow paths')
  162. self.assertEqual(traverse_obj(_TEST_DATA, {0: ('urls', (3, 0), 'url')}),
  163. {0: ['https://www.example.com/0']},
  164. msg='tuple in dict path should be treated as branches')
  165. self.assertEqual(traverse_obj(_TEST_DATA, {0: ('urls', ((1, 'fail'), (0, 'url')))}),
  166. {0: ['https://www.example.com/0']},
  167. msg='double nesting in dict path should be treated as paths')
  168. self.assertEqual(traverse_obj(_TEST_DATA, {0: ('urls', ((1, ('fail', 'url')), (0, 'url')))}),
  169. {0: ['https://www.example.com/1', 'https://www.example.com/0']},
  170. msg='triple nesting in dict path should be treated as branches')
  171. self.assertEqual(traverse_obj(_TEST_DATA, {0: 'fail'}), {},
  172. msg='remove `None` values when top level dict key fails')
  173. self.assertEqual(traverse_obj(_TEST_DATA, {0: 'fail'}, default=Ellipsis), {0: Ellipsis},
  174. msg='use `default` if key fails and `default`')
  175. self.assertEqual(traverse_obj(_TEST_DATA, {0: 'dict'}), {},
  176. msg='remove empty values when dict key')
  177. self.assertEqual(traverse_obj(_TEST_DATA, {0: 'dict'}, default=Ellipsis), {0: Ellipsis},
  178. msg='use `default` when dict key and a default')
  179. self.assertEqual(traverse_obj(_TEST_DATA, {0: {0: 'fail'}}), {},
  180. msg='remove empty values when nested dict key fails')
  181. self.assertEqual(traverse_obj(None, {0: 'fail'}), {},
  182. msg='default to dict if pruned')
  183. self.assertEqual(traverse_obj(None, {0: 'fail'}, default=Ellipsis), {0: Ellipsis},
  184. msg='default to dict if pruned and default is given')
  185. self.assertEqual(traverse_obj(_TEST_DATA, {0: {0: 'fail'}}, default=Ellipsis), {0: {0: Ellipsis}},
  186. msg='use nested `default` when nested dict key fails and `default`')
  187. self.assertEqual(traverse_obj(_TEST_DATA, {0: ('dict', Ellipsis)}), {},
  188. msg='remove key if branch in dict key not successful')
  189. # Testing default parameter behavior
  190. _DEFAULT_DATA = {'None': None, 'int': 0, 'list': []}
  191. self.assertEqual(traverse_obj(_DEFAULT_DATA, 'fail'), None,
  192. msg='default value should be `None`')
  193. self.assertEqual(traverse_obj(_DEFAULT_DATA, 'fail', 'fail', default=Ellipsis), Ellipsis,
  194. msg='chained fails should result in default')
  195. self.assertEqual(traverse_obj(_DEFAULT_DATA, 'None', 'int'), 0,
  196. msg='should not short cirquit on `None`')
  197. self.assertEqual(traverse_obj(_DEFAULT_DATA, 'fail', default=1), 1,
  198. msg='invalid dict key should result in `default`')
  199. self.assertEqual(traverse_obj(_DEFAULT_DATA, 'None', default=1), 1,
  200. msg='`None` is a deliberate sentinel and should become `default`')
  201. self.assertEqual(traverse_obj(_DEFAULT_DATA, ('list', 10)), None,
  202. msg='`IndexError` should result in `default`')
  203. self.assertEqual(traverse_obj(_DEFAULT_DATA, (Ellipsis, 'fail'), default=1), 1,
  204. msg='if branched but not successful return `default` if defined, not `[]`')
  205. self.assertEqual(traverse_obj(_DEFAULT_DATA, (Ellipsis, 'fail'), default=None), None,
  206. msg='if branched but not successful return `default` even if `default` is `None`')
  207. self.assertEqual(traverse_obj(_DEFAULT_DATA, (Ellipsis, 'fail')), [],
  208. msg='if branched but not successful return `[]`, not `default`')
  209. self.assertEqual(traverse_obj(_DEFAULT_DATA, ('list', Ellipsis)), [],
  210. msg='if branched but object is empty return `[]`, not `default`')
  211. self.assertEqual(traverse_obj(None, Ellipsis), [],
  212. msg='if branched but object is `None` return `[]`, not `default`')
  213. self.assertEqual(traverse_obj({0: None}, (0, Ellipsis)), [],
  214. msg='if branched but state is `None` return `[]`, not `default`')
  215. branching_paths = [
  216. ('fail', Ellipsis),
  217. (Ellipsis, 'fail'),
  218. 100 * ('fail',) + (Ellipsis,),
  219. (Ellipsis,) + 100 * ('fail',),
  220. ]
  221. for branching_path in branching_paths:
  222. self.assertEqual(traverse_obj({}, branching_path), [],
  223. msg='if branched but state is `None`, return `[]` (not `default`)')
  224. self.assertEqual(traverse_obj({}, 'fail', branching_path), [],
  225. msg='if branching in last alternative and previous did not match, return `[]` (not `default`)')
  226. self.assertEqual(traverse_obj({0: 'x'}, 0, branching_path), 'x',
  227. msg='if branching in last alternative and previous did match, return single value')
  228. self.assertEqual(traverse_obj({0: 'x'}, branching_path, 0), 'x',
  229. msg='if branching in first alternative and non-branching path does match, return single value')
  230. self.assertEqual(traverse_obj({}, branching_path, 'fail'), None,
  231. msg='if branching in first alternative and non-branching path does not match, return `default`')
  232. # Testing expected_type behavior
  233. _EXPECTED_TYPE_DATA = {'str': 'str', 'int': 0}
  234. self.assertEqual(traverse_obj(_EXPECTED_TYPE_DATA, 'str', expected_type=str),
  235. 'str', msg='accept matching `expected_type` type')
  236. self.assertEqual(traverse_obj(_EXPECTED_TYPE_DATA, 'str', expected_type=int),
  237. None, msg='reject non-matching `expected_type` type')
  238. self.assertEqual(traverse_obj(_EXPECTED_TYPE_DATA, 'int', expected_type=lambda x: str(x)),
  239. '0', msg='transform type using type function')
  240. self.assertEqual(traverse_obj(_EXPECTED_TYPE_DATA, 'str', expected_type=lambda _: 1 / 0),
  241. None, msg='wrap expected_type function in try_call')
  242. self.assertEqual(traverse_obj(_EXPECTED_TYPE_DATA, Ellipsis, expected_type=str),
  243. ['str'], msg='eliminate items that expected_type fails on')
  244. self.assertEqual(traverse_obj(_TEST_DATA, {0: 100, 1: 1.2}, expected_type=int),
  245. {0: 100}, msg='type as expected_type should filter dict values')
  246. self.assertEqual(traverse_obj(_TEST_DATA, {0: 100, 1: 1.2, 2: 'None'}, expected_type=str_or_none),
  247. {0: '100', 1: '1.2'}, msg='function as expected_type should transform dict values')
  248. self.assertEqual(traverse_obj(_TEST_DATA, ({0: 1.2}, 0, set((int_or_none,))), expected_type=int),
  249. 1, msg='expected_type should not filter non-final dict values')
  250. self.assertEqual(traverse_obj(_TEST_DATA, {0: {0: 100, 1: 'str'}}, expected_type=int),
  251. {0: {0: 100}}, msg='expected_type should transform deep dict values')
  252. self.assertEqual(traverse_obj(_TEST_DATA, [({0: '...'}, {0: '...'})], expected_type=type(Ellipsis)),
  253. [{0: Ellipsis}, {0: Ellipsis}], msg='expected_type should transform branched dict values')
  254. self.assertEqual(traverse_obj({1: {3: 4}}, [(1, 2), 3], expected_type=int),
  255. [4], msg='expected_type regression for type matching in tuple branching')
  256. self.assertEqual(traverse_obj(_TEST_DATA, ['data', Ellipsis], expected_type=int),
  257. [], msg='expected_type regression for type matching in dict result')
  258. # Test get_all behavior
  259. _GET_ALL_DATA = {'key': [0, 1, 2]}
  260. self.assertEqual(traverse_obj(_GET_ALL_DATA, ('key', Ellipsis), get_all=False), 0,
  261. msg='if not `get_all`, return only first matching value')
  262. self.assertEqual(traverse_obj(_GET_ALL_DATA, Ellipsis, get_all=False), [0, 1, 2],
  263. msg='do not overflatten if not `get_all`')
  264. # Test casesense behavior
  265. _CASESENSE_DATA = {
  266. 'KeY': 'value0',
  267. 0: {
  268. 'KeY': 'value1',
  269. 0: {'KeY': 'value2'},
  270. },
  271. # FULLWIDTH LATIN CAPITAL LETTER K
  272. '\uff2bey': 'value3',
  273. }
  274. self.assertEqual(traverse_obj(_CASESENSE_DATA, 'key'), None,
  275. msg='dict keys should be case sensitive unless `casesense`')
  276. self.assertEqual(traverse_obj(_CASESENSE_DATA, 'keY',
  277. casesense=False), 'value0',
  278. msg='allow non matching key case if `casesense`')
  279. self.assertEqual(traverse_obj(_CASESENSE_DATA, '\uff4bey', # FULLWIDTH LATIN SMALL LETTER K
  280. casesense=False), 'value3',
  281. msg='allow non matching Unicode key case if `casesense`')
  282. self.assertEqual(traverse_obj(_CASESENSE_DATA, (0, ('keY',)),
  283. casesense=False), ['value1'],
  284. msg='allow non matching key case in branch if `casesense`')
  285. self.assertEqual(traverse_obj(_CASESENSE_DATA, (0, ((0, 'keY'),)),
  286. casesense=False), ['value2'],
  287. msg='allow non matching key case in branch path if `casesense`')
  288. # Test traverse_string behavior
  289. _TRAVERSE_STRING_DATA = {'str': 'str', 1.2: 1.2}
  290. self.assertEqual(traverse_obj(_TRAVERSE_STRING_DATA, ('str', 0)), None,
  291. msg='do not traverse into string if not `traverse_string`')
  292. self.assertEqual(traverse_obj(_TRAVERSE_STRING_DATA, ('str', 0),
  293. _traverse_string=True), 's',
  294. msg='traverse into string if `traverse_string`')
  295. self.assertEqual(traverse_obj(_TRAVERSE_STRING_DATA, (1.2, 1),
  296. _traverse_string=True), '.',
  297. msg='traverse into converted data if `traverse_string`')
  298. self.assertEqual(traverse_obj(_TRAVERSE_STRING_DATA, ('str', Ellipsis),
  299. _traverse_string=True), 'str',
  300. msg='`...` should result in string (same value) if `traverse_string`')
  301. self.assertEqual(traverse_obj(_TRAVERSE_STRING_DATA, ('str', slice(0, None, 2)),
  302. _traverse_string=True), 'sr',
  303. msg='`slice` should result in string if `traverse_string`')
  304. self.assertEqual(traverse_obj(_TRAVERSE_STRING_DATA, ('str', lambda i, v: i or v == 's'),
  305. _traverse_string=True), 'str',
  306. msg='function should result in string if `traverse_string`')
  307. self.assertEqual(traverse_obj(_TRAVERSE_STRING_DATA, ('str', (0, 2)),
  308. _traverse_string=True), ['s', 'r'],
  309. msg='branching should result in list if `traverse_string`')
  310. self.assertEqual(traverse_obj({}, (0, Ellipsis), _traverse_string=True), [],
  311. msg='branching should result in list if `traverse_string`')
  312. self.assertEqual(traverse_obj({}, (0, lambda x, y: True), _traverse_string=True), [],
  313. msg='branching should result in list if `traverse_string`')
  314. self.assertEqual(traverse_obj({}, (0, slice(1)), _traverse_string=True), [],
  315. msg='branching should result in list if `traverse_string`')
  316. # Test re.Match as input obj
  317. mobj = re.match(r'^0(12)(?P<group>3)(4)?$', '0123')
  318. self.assertEqual(traverse_obj(mobj, Ellipsis), [x for x in mobj.groups() if x is not None],
  319. msg='`...` on a `re.Match` should give its `groups()`')
  320. self.assertEqual(traverse_obj(mobj, lambda k, _: k in (0, 2)), ['0123', '3'],
  321. msg='function on a `re.Match` should give groupno, value starting at 0')
  322. self.assertEqual(traverse_obj(mobj, 'group'), '3',
  323. msg='str key on a `re.Match` should give group with that name')
  324. self.assertEqual(traverse_obj(mobj, 2), '3',
  325. msg='int key on a `re.Match` should give group with that name')
  326. self.assertEqual(traverse_obj(mobj, 'gRoUp', casesense=False), '3',
  327. msg='str key on a `re.Match` should respect casesense')
  328. self.assertEqual(traverse_obj(mobj, 'fail'), None,
  329. msg='failing str key on a `re.Match` should return `default`')
  330. self.assertEqual(traverse_obj(mobj, 'gRoUpS', casesense=False), None,
  331. msg='failing str key on a `re.Match` should return `default`')
  332. self.assertEqual(traverse_obj(mobj, 8), None,
  333. msg='failing int key on a `re.Match` should return `default`')
  334. self.assertEqual(traverse_obj(mobj, lambda k, _: k in (0, 'group')), ['0123', '3'],
  335. msg='function on a `re.Match` should give group name as well')
  336. # Test xml.etree.ElementTree.Element as input obj
  337. etree = compat_etree_fromstring('''<?xml version="1.0"?>
  338. <data>
  339. <country name="Liechtenstein">
  340. <rank>1</rank>
  341. <year>2008</year>
  342. <gdppc>141100</gdppc>
  343. <neighbor name="Austria" direction="E"/>
  344. <neighbor name="Switzerland" direction="W"/>
  345. </country>
  346. <country name="Singapore">
  347. <rank>4</rank>
  348. <year>2011</year>
  349. <gdppc>59900</gdppc>
  350. <neighbor name="Malaysia" direction="N"/>
  351. </country>
  352. <country name="Panama">
  353. <rank>68</rank>
  354. <year>2011</year>
  355. <gdppc>13600</gdppc>
  356. <neighbor name="Costa Rica" direction="W"/>
  357. <neighbor name="Colombia" direction="E"/>
  358. </country>
  359. </data>''')
  360. self.assertEqual(traverse_obj(etree, ''), etree,
  361. msg='empty str key should return the element itself')
  362. self.assertEqual(traverse_obj(etree, 'country'), list(etree),
  363. msg='str key should return all children with that tag name')
  364. self.assertEqual(traverse_obj(etree, Ellipsis), list(etree),
  365. msg='`...` as key should return all children')
  366. self.assertEqual(traverse_obj(etree, lambda _, x: x[0].text == '4'), [etree[1]],
  367. msg='function as key should get element as value')
  368. self.assertEqual(traverse_obj(etree, lambda i, _: i == 1), [etree[1]],
  369. msg='function as key should get index as key')
  370. self.assertEqual(traverse_obj(etree, 0), etree[0],
  371. msg='int key should return the nth child')
  372. self.assertEqual(traverse_obj(etree, './/neighbor/@name'),
  373. ['Austria', 'Switzerland', 'Malaysia', 'Costa Rica', 'Colombia'],
  374. msg='`@<attribute>` at end of path should give that attribute')
  375. self.assertEqual(traverse_obj(etree, '//neighbor/@fail'), [None, None, None, None, None],
  376. msg='`@<nonexistent>` at end of path should give `None`')
  377. self.assertEqual(traverse_obj(etree, ('//neighbor/@', 2)), {'name': 'Malaysia', 'direction': 'N'},
  378. msg='`@` should give the full attribute dict')
  379. self.assertEqual(traverse_obj(etree, '//year/text()'), ['2008', '2011', '2011'],
  380. msg='`text()` at end of path should give the inner text')
  381. self.assertEqual(traverse_obj(etree, '//*[@direction]/@direction'), ['E', 'W', 'N', 'W', 'E'],
  382. msg='full python xpath features should be supported')
  383. self.assertEqual(traverse_obj(etree, (0, '@name')), 'Liechtenstein',
  384. msg='special transformations should act on current element')
  385. self.assertEqual(traverse_obj(etree, ('country', 0, Ellipsis, 'text()', T(int_or_none))), [1, 2008, 141100],
  386. msg='special transformations should act on current element')
  387. def test_traversal_unbranching(self):
  388. self.assertEqual(traverse_obj(_TEST_DATA, [(100, 1.2), all]), [100, 1.2],
  389. msg='`all` should give all results as list')
  390. self.assertEqual(traverse_obj(_TEST_DATA, [(100, 1.2), any]), 100,
  391. msg='`any` should give the first result')
  392. self.assertEqual(traverse_obj(_TEST_DATA, [100, all]), [100],
  393. msg='`all` should give list if non branching')
  394. self.assertEqual(traverse_obj(_TEST_DATA, [100, any]), 100,
  395. msg='`any` should give single item if non branching')
  396. self.assertEqual(traverse_obj(_TEST_DATA, [('dict', 'None', 100), all]), [100],
  397. msg='`all` should filter `None` and empty dict')
  398. self.assertEqual(traverse_obj(_TEST_DATA, [('dict', 'None', 100), any]), 100,
  399. msg='`any` should filter `None` and empty dict')
  400. self.assertEqual(traverse_obj(_TEST_DATA, [{
  401. 'all': [('dict', 'None', 100, 1.2), all],
  402. 'any': [('dict', 'None', 100, 1.2), any],
  403. }]), {'all': [100, 1.2], 'any': 100},
  404. msg='`all`/`any` should apply to each dict path separately')
  405. self.assertEqual(traverse_obj(_TEST_DATA, [{
  406. 'all': [('dict', 'None', 100, 1.2), all],
  407. 'any': [('dict', 'None', 100, 1.2), any],
  408. }], get_all=False), {'all': [100, 1.2], 'any': 100},
  409. msg='`all`/`any` should apply to dict regardless of `get_all`')
  410. self.assertIs(traverse_obj(_TEST_DATA, [('dict', 'None', 100, 1.2), all, T(float)]), None,
  411. msg='`all` should reset branching status')
  412. self.assertIs(traverse_obj(_TEST_DATA, [('dict', 'None', 100, 1.2), any, T(float)]), None,
  413. msg='`any` should reset branching status')
  414. self.assertEqual(traverse_obj(_TEST_DATA, [('dict', 'None', 100, 1.2), all, Ellipsis, T(float)]), [1.2],
  415. msg='`all` should allow further branching')
  416. self.assertEqual(traverse_obj(_TEST_DATA, [('dict', 'None', 'urls', 'data'), any, Ellipsis, 'index']), [0, 1],
  417. msg='`any` should allow further branching')
  418. def test_traversal_morsel(self):
  419. values = {
  420. 'expires': 'a',
  421. 'path': 'b',
  422. 'comment': 'c',
  423. 'domain': 'd',
  424. 'max-age': 'e',
  425. 'secure': 'f',
  426. 'httponly': 'g',
  427. 'version': 'h',
  428. 'samesite': 'i',
  429. }
  430. # SameSite added in Py3.8, breaks .update for 3.5-3.7
  431. if sys.version_info < (3, 8):
  432. del values['samesite']
  433. morsel = compat_http_cookies.Morsel()
  434. morsel.set(str('item_key'), 'item_value', 'coded_value')
  435. morsel.update(values)
  436. values['key'] = str('item_key')
  437. values['value'] = 'item_value'
  438. values = dict((str(k), v) for k, v in values.items())
  439. # make test pass even without ordered dict
  440. value_set = set(values.values())
  441. for key, value in values.items():
  442. self.assertEqual(traverse_obj(morsel, key), value,
  443. msg='Morsel should provide access to all values')
  444. self.assertEqual(set(traverse_obj(morsel, Ellipsis)), value_set,
  445. msg='`...` should yield all values')
  446. self.assertEqual(set(traverse_obj(morsel, lambda k, v: True)), value_set,
  447. msg='function key should yield all values')
  448. self.assertIs(traverse_obj(morsel, [(None,), any]), morsel,
  449. msg='Morsel should not be implicitly changed to dict on usage')
  450. def test_get_first(self):
  451. self.assertEqual(get_first([{'a': None}, {'a': 'spam'}], 'a'), 'spam')
  452. def test_dict_get(self):
  453. FALSE_VALUES = {
  454. 'none': None,
  455. 'false': False,
  456. 'zero': 0,
  457. 'empty_string': '',
  458. 'empty_list': [],
  459. }
  460. d = FALSE_VALUES.copy()
  461. d['a'] = 42
  462. self.assertEqual(dict_get(d, 'a'), 42)
  463. self.assertEqual(dict_get(d, 'b'), None)
  464. self.assertEqual(dict_get(d, 'b', 42), 42)
  465. self.assertEqual(dict_get(d, ('a', )), 42)
  466. self.assertEqual(dict_get(d, ('b', 'a', )), 42)
  467. self.assertEqual(dict_get(d, ('b', 'c', 'a', 'd', )), 42)
  468. self.assertEqual(dict_get(d, ('b', 'c', )), None)
  469. self.assertEqual(dict_get(d, ('b', 'c', ), 42), 42)
  470. for key, false_value in FALSE_VALUES.items():
  471. self.assertEqual(dict_get(d, ('b', 'c', key, )), None)
  472. self.assertEqual(dict_get(d, ('b', 'c', key, ), skip_false_values=False), false_value)
  473. if __name__ == '__main__':
  474. unittest.main()