test_traversal.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  1. import http.cookies
  2. import re
  3. import xml.etree.ElementTree
  4. import pytest
  5. from yt_dlp.utils import dict_get, int_or_none, str_or_none
  6. from yt_dlp.utils.traversal import traverse_obj
  7. _TEST_DATA = {
  8. 100: 100,
  9. 1.2: 1.2,
  10. 'str': 'str',
  11. 'None': None,
  12. '...': ...,
  13. 'urls': [
  14. {'index': 0, 'url': 'https://www.example.com/0'},
  15. {'index': 1, 'url': 'https://www.example.com/1'},
  16. ],
  17. 'data': (
  18. {'index': 2},
  19. {'index': 3},
  20. ),
  21. 'dict': {},
  22. }
  23. class TestTraversal:
  24. def test_traversal_base(self):
  25. assert traverse_obj(_TEST_DATA, ('str',)) == 'str', \
  26. 'allow tuple path'
  27. assert traverse_obj(_TEST_DATA, ['str']) == 'str', \
  28. 'allow list path'
  29. assert traverse_obj(_TEST_DATA, (value for value in ('str',))) == 'str', \
  30. 'allow iterable path'
  31. assert traverse_obj(_TEST_DATA, 'str') == 'str', \
  32. 'single items should be treated as a path'
  33. assert traverse_obj(_TEST_DATA, 100) == 100, \
  34. 'allow int path'
  35. assert traverse_obj(_TEST_DATA, 1.2) == 1.2, \
  36. 'allow float path'
  37. assert traverse_obj(_TEST_DATA, None) == _TEST_DATA, \
  38. '`None` should not perform any modification'
  39. def test_traversal_ellipsis(self):
  40. assert traverse_obj(_TEST_DATA, ...) == [x for x in _TEST_DATA.values() if x not in (None, {})], \
  41. '`...` should give all non discarded values'
  42. assert traverse_obj(_TEST_DATA, ('urls', 0, ...)) == list(_TEST_DATA['urls'][0].values()), \
  43. '`...` selection for dicts should select all values'
  44. assert traverse_obj(_TEST_DATA, (..., ..., 'url')) == ['https://www.example.com/0', 'https://www.example.com/1'], \
  45. 'nested `...` queries should work'
  46. assert traverse_obj(_TEST_DATA, (..., ..., 'index')) == list(range(4)), \
  47. '`...` query result should be flattened'
  48. assert traverse_obj(iter(range(4)), ...) == list(range(4)), \
  49. '`...` should accept iterables'
  50. def test_traversal_function(self):
  51. filter_func = lambda x, y: x == 'urls' and isinstance(y, list)
  52. assert traverse_obj(_TEST_DATA, filter_func) == [_TEST_DATA['urls']], \
  53. 'function as query key should perform a filter based on (key, value)'
  54. assert traverse_obj(_TEST_DATA, lambda _, x: isinstance(x[0], str)) == ['str'], \
  55. 'exceptions in the query function should be catched'
  56. assert traverse_obj(iter(range(4)), lambda _, x: x % 2 == 0) == [0, 2], \
  57. 'function key should accept iterables'
  58. # Wrong function signature should raise (debug mode)
  59. with pytest.raises(Exception):
  60. traverse_obj(_TEST_DATA, lambda a: ...)
  61. with pytest.raises(Exception):
  62. traverse_obj(_TEST_DATA, lambda a, b, c: ...)
  63. def test_traversal_set(self):
  64. # transformation/type, like `expected_type`
  65. assert traverse_obj(_TEST_DATA, (..., {str.upper})) == ['STR'], \
  66. 'Function in set should be a transformation'
  67. assert traverse_obj(_TEST_DATA, (..., {str})) == ['str'], \
  68. 'Type in set should be a type filter'
  69. assert traverse_obj(_TEST_DATA, (..., {str, int})) == [100, 'str'], \
  70. 'Multiple types in set should be a type filter'
  71. assert traverse_obj(_TEST_DATA, {dict}) == _TEST_DATA, \
  72. 'A single set should be wrapped into a path'
  73. assert traverse_obj(_TEST_DATA, (..., {str.upper})) == ['STR'], \
  74. 'Transformation function should not raise'
  75. expected = [x for x in map(str_or_none, _TEST_DATA.values()) if x is not None]
  76. assert traverse_obj(_TEST_DATA, (..., {str_or_none})) == expected, \
  77. 'Function in set should be a transformation'
  78. assert traverse_obj(_TEST_DATA, ('fail', {lambda _: 'const'})) == 'const', \
  79. 'Function in set should always be called'
  80. # Sets with length < 1 or > 1 not including only types should raise
  81. with pytest.raises(Exception):
  82. traverse_obj(_TEST_DATA, set())
  83. with pytest.raises(Exception):
  84. traverse_obj(_TEST_DATA, {str.upper, str})
  85. def test_traversal_slice(self):
  86. _SLICE_DATA = [0, 1, 2, 3, 4]
  87. assert traverse_obj(_TEST_DATA, ('dict', slice(1))) is None, \
  88. 'slice on a dictionary should not throw'
  89. assert traverse_obj(_SLICE_DATA, slice(1)) == _SLICE_DATA[:1], \
  90. 'slice key should apply slice to sequence'
  91. assert traverse_obj(_SLICE_DATA, slice(1, 2)) == _SLICE_DATA[1:2], \
  92. 'slice key should apply slice to sequence'
  93. assert traverse_obj(_SLICE_DATA, slice(1, 4, 2)) == _SLICE_DATA[1:4:2], \
  94. 'slice key should apply slice to sequence'
  95. def test_traversal_alternatives(self):
  96. assert traverse_obj(_TEST_DATA, 'fail', 'str') == 'str', \
  97. 'multiple `paths` should be treated as alternative paths'
  98. assert traverse_obj(_TEST_DATA, 'str', 100) == 'str', \
  99. 'alternatives should exit early'
  100. assert traverse_obj(_TEST_DATA, 'fail', 'fail') is None, \
  101. 'alternatives should return `default` if exhausted'
  102. assert traverse_obj(_TEST_DATA, (..., 'fail'), 100) == 100, \
  103. 'alternatives should track their own branching return'
  104. assert traverse_obj(_TEST_DATA, ('dict', ...), ('data', ...)) == list(_TEST_DATA['data']), \
  105. 'alternatives on empty objects should search further'
  106. def test_traversal_branching_nesting(self):
  107. assert traverse_obj(_TEST_DATA, ('urls', (3, 0), 'url')) == ['https://www.example.com/0'], \
  108. 'tuple as key should be treated as branches'
  109. assert traverse_obj(_TEST_DATA, ('urls', [3, 0], 'url')) == ['https://www.example.com/0'], \
  110. 'list as key should be treated as branches'
  111. assert traverse_obj(_TEST_DATA, ('urls', ((1, 'fail'), (0, 'url')))) == ['https://www.example.com/0'], \
  112. 'double nesting in path should be treated as paths'
  113. assert traverse_obj(['0', [1, 2]], [(0, 1), 0]) == [1], \
  114. 'do not fail early on branching'
  115. expected = ['https://www.example.com/0', 'https://www.example.com/1']
  116. assert traverse_obj(_TEST_DATA, ('urls', ((0, ('fail', 'url')), (1, 'url')))) == expected, \
  117. 'tripple nesting in path should be treated as branches'
  118. assert traverse_obj(_TEST_DATA, ('urls', ('fail', (..., 'url')))) == expected, \
  119. 'ellipsis as branch path start gets flattened'
  120. def test_traversal_dict(self):
  121. assert traverse_obj(_TEST_DATA, {0: 100, 1: 1.2}) == {0: 100, 1: 1.2}, \
  122. 'dict key should result in a dict with the same keys'
  123. expected = {0: 'https://www.example.com/0'}
  124. assert traverse_obj(_TEST_DATA, {0: ('urls', 0, 'url')}) == expected, \
  125. 'dict key should allow paths'
  126. expected = {0: ['https://www.example.com/0']}
  127. assert traverse_obj(_TEST_DATA, {0: ('urls', (3, 0), 'url')}) == expected, \
  128. 'tuple in dict path should be treated as branches'
  129. assert traverse_obj(_TEST_DATA, {0: ('urls', ((1, 'fail'), (0, 'url')))}) == expected, \
  130. 'double nesting in dict path should be treated as paths'
  131. expected = {0: ['https://www.example.com/1', 'https://www.example.com/0']}
  132. assert traverse_obj(_TEST_DATA, {0: ('urls', ((1, ('fail', 'url')), (0, 'url')))}) == expected, \
  133. 'tripple nesting in dict path should be treated as branches'
  134. assert traverse_obj(_TEST_DATA, {0: 'fail'}) == {}, \
  135. 'remove `None` values when top level dict key fails'
  136. assert traverse_obj(_TEST_DATA, {0: 'fail'}, default=...) == {0: ...}, \
  137. 'use `default` if key fails and `default`'
  138. assert traverse_obj(_TEST_DATA, {0: 'dict'}) == {}, \
  139. 'remove empty values when dict key'
  140. assert traverse_obj(_TEST_DATA, {0: 'dict'}, default=...) == {0: ...}, \
  141. 'use `default` when dict key and `default`'
  142. assert traverse_obj(_TEST_DATA, {0: {0: 'fail'}}) == {}, \
  143. 'remove empty values when nested dict key fails'
  144. assert traverse_obj(None, {0: 'fail'}) == {}, \
  145. 'default to dict if pruned'
  146. assert traverse_obj(None, {0: 'fail'}, default=...) == {0: ...}, \
  147. 'default to dict if pruned and default is given'
  148. assert traverse_obj(_TEST_DATA, {0: {0: 'fail'}}, default=...) == {0: {0: ...}}, \
  149. 'use nested `default` when nested dict key fails and `default`'
  150. assert traverse_obj(_TEST_DATA, {0: ('dict', ...)}) == {}, \
  151. 'remove key if branch in dict key not successful'
  152. def test_traversal_default(self):
  153. _DEFAULT_DATA = {'None': None, 'int': 0, 'list': []}
  154. assert traverse_obj(_DEFAULT_DATA, 'fail') is None, \
  155. 'default value should be `None`'
  156. assert traverse_obj(_DEFAULT_DATA, 'fail', 'fail', default=...) == ..., \
  157. 'chained fails should result in default'
  158. assert traverse_obj(_DEFAULT_DATA, 'None', 'int') == 0, \
  159. 'should not short cirquit on `None`'
  160. assert traverse_obj(_DEFAULT_DATA, 'fail', default=1) == 1, \
  161. 'invalid dict key should result in `default`'
  162. assert traverse_obj(_DEFAULT_DATA, 'None', default=1) == 1, \
  163. '`None` is a deliberate sentinel and should become `default`'
  164. assert traverse_obj(_DEFAULT_DATA, ('list', 10)) is None, \
  165. '`IndexError` should result in `default`'
  166. assert traverse_obj(_DEFAULT_DATA, (..., 'fail'), default=1) == 1, \
  167. 'if branched but not successful return `default` if defined, not `[]`'
  168. assert traverse_obj(_DEFAULT_DATA, (..., 'fail'), default=None) is None, \
  169. 'if branched but not successful return `default` even if `default` is `None`'
  170. assert traverse_obj(_DEFAULT_DATA, (..., 'fail')) == [], \
  171. 'if branched but not successful return `[]`, not `default`'
  172. assert traverse_obj(_DEFAULT_DATA, ('list', ...)) == [], \
  173. 'if branched but object is empty return `[]`, not `default`'
  174. assert traverse_obj(None, ...) == [], \
  175. 'if branched but object is `None` return `[]`, not `default`'
  176. assert traverse_obj({0: None}, (0, ...)) == [], \
  177. 'if branched but state is `None` return `[]`, not `default`'
  178. @pytest.mark.parametrize('path', [
  179. ('fail', ...),
  180. (..., 'fail'),
  181. 100 * ('fail',) + (...,),
  182. (...,) + 100 * ('fail',),
  183. ])
  184. def test_traversal_branching(self, path):
  185. assert traverse_obj({}, path) == [], \
  186. 'if branched but state is `None`, return `[]` (not `default`)'
  187. assert traverse_obj({}, 'fail', path) == [], \
  188. 'if branching in last alternative and previous did not match, return `[]` (not `default`)'
  189. assert traverse_obj({0: 'x'}, 0, path) == 'x', \
  190. 'if branching in last alternative and previous did match, return single value'
  191. assert traverse_obj({0: 'x'}, path, 0) == 'x', \
  192. 'if branching in first alternative and non-branching path does match, return single value'
  193. assert traverse_obj({}, path, 'fail') is None, \
  194. 'if branching in first alternative and non-branching path does not match, return `default`'
  195. def test_traversal_expected_type(self):
  196. _EXPECTED_TYPE_DATA = {'str': 'str', 'int': 0}
  197. assert traverse_obj(_EXPECTED_TYPE_DATA, 'str', expected_type=str) == 'str', \
  198. 'accept matching `expected_type` type'
  199. assert traverse_obj(_EXPECTED_TYPE_DATA, 'str', expected_type=int) is None, \
  200. 'reject non matching `expected_type` type'
  201. assert traverse_obj(_EXPECTED_TYPE_DATA, 'int', expected_type=lambda x: str(x)) == '0', \
  202. 'transform type using type function'
  203. assert traverse_obj(_EXPECTED_TYPE_DATA, 'str', expected_type=lambda _: 1 / 0) is None, \
  204. 'wrap expected_type fuction in try_call'
  205. assert traverse_obj(_EXPECTED_TYPE_DATA, ..., expected_type=str) == ['str'], \
  206. 'eliminate items that expected_type fails on'
  207. assert traverse_obj(_TEST_DATA, {0: 100, 1: 1.2}, expected_type=int) == {0: 100}, \
  208. 'type as expected_type should filter dict values'
  209. assert traverse_obj(_TEST_DATA, {0: 100, 1: 1.2, 2: 'None'}, expected_type=str_or_none) == {0: '100', 1: '1.2'}, \
  210. 'function as expected_type should transform dict values'
  211. assert traverse_obj(_TEST_DATA, ({0: 1.2}, 0, {int_or_none}), expected_type=int) == 1, \
  212. 'expected_type should not filter non final dict values'
  213. assert traverse_obj(_TEST_DATA, {0: {0: 100, 1: 'str'}}, expected_type=int) == {0: {0: 100}}, \
  214. 'expected_type should transform deep dict values'
  215. assert traverse_obj(_TEST_DATA, [({0: '...'}, {0: '...'})], expected_type=type(...)) == [{0: ...}, {0: ...}], \
  216. 'expected_type should transform branched dict values'
  217. assert traverse_obj({1: {3: 4}}, [(1, 2), 3], expected_type=int) == [4], \
  218. 'expected_type regression for type matching in tuple branching'
  219. assert traverse_obj(_TEST_DATA, ['data', ...], expected_type=int) == [], \
  220. 'expected_type regression for type matching in dict result'
  221. def test_traversal_get_all(self):
  222. _GET_ALL_DATA = {'key': [0, 1, 2]}
  223. assert traverse_obj(_GET_ALL_DATA, ('key', ...), get_all=False) == 0, \
  224. 'if not `get_all`, return only first matching value'
  225. assert traverse_obj(_GET_ALL_DATA, ..., get_all=False) == [0, 1, 2], \
  226. 'do not overflatten if not `get_all`'
  227. def test_traversal_casesense(self):
  228. _CASESENSE_DATA = {
  229. 'KeY': 'value0',
  230. 0: {
  231. 'KeY': 'value1',
  232. 0: {'KeY': 'value2'},
  233. },
  234. }
  235. assert traverse_obj(_CASESENSE_DATA, 'key') is None, \
  236. 'dict keys should be case sensitive unless `casesense`'
  237. assert traverse_obj(_CASESENSE_DATA, 'keY', casesense=False) == 'value0', \
  238. 'allow non matching key case if `casesense`'
  239. assert traverse_obj(_CASESENSE_DATA, [0, ('keY',)], casesense=False) == ['value1'], \
  240. 'allow non matching key case in branch if `casesense`'
  241. assert traverse_obj(_CASESENSE_DATA, [0, ([0, 'keY'],)], casesense=False) == ['value2'], \
  242. 'allow non matching key case in branch path if `casesense`'
  243. def test_traversal_traverse_string(self):
  244. _TRAVERSE_STRING_DATA = {'str': 'str', 1.2: 1.2}
  245. assert traverse_obj(_TRAVERSE_STRING_DATA, ('str', 0)) is None, \
  246. 'do not traverse into string if not `traverse_string`'
  247. assert traverse_obj(_TRAVERSE_STRING_DATA, ('str', 0), traverse_string=True) == 's', \
  248. 'traverse into string if `traverse_string`'
  249. assert traverse_obj(_TRAVERSE_STRING_DATA, (1.2, 1), traverse_string=True) == '.', \
  250. 'traverse into converted data if `traverse_string`'
  251. assert traverse_obj(_TRAVERSE_STRING_DATA, ('str', ...), traverse_string=True) == 'str', \
  252. '`...` should result in string (same value) if `traverse_string`'
  253. assert traverse_obj(_TRAVERSE_STRING_DATA, ('str', slice(0, None, 2)), traverse_string=True) == 'sr', \
  254. '`slice` should result in string if `traverse_string`'
  255. assert traverse_obj(_TRAVERSE_STRING_DATA, ('str', lambda i, v: i or v == 's'), traverse_string=True) == 'str', \
  256. 'function should result in string if `traverse_string`'
  257. assert traverse_obj(_TRAVERSE_STRING_DATA, ('str', (0, 2)), traverse_string=True) == ['s', 'r'], \
  258. 'branching should result in list if `traverse_string`'
  259. assert traverse_obj({}, (0, ...), traverse_string=True) == [], \
  260. 'branching should result in list if `traverse_string`'
  261. assert traverse_obj({}, (0, lambda x, y: True), traverse_string=True) == [], \
  262. 'branching should result in list if `traverse_string`'
  263. assert traverse_obj({}, (0, slice(1)), traverse_string=True) == [], \
  264. 'branching should result in list if `traverse_string`'
  265. def test_traversal_re(self):
  266. mobj = re.fullmatch(r'0(12)(?P<group>3)(4)?', '0123')
  267. assert traverse_obj(mobj, ...) == [x for x in mobj.groups() if x is not None], \
  268. '`...` on a `re.Match` should give its `groups()`'
  269. assert traverse_obj(mobj, lambda k, _: k in (0, 2)) == ['0123', '3'], \
  270. 'function on a `re.Match` should give groupno, value starting at 0'
  271. assert traverse_obj(mobj, 'group') == '3', \
  272. 'str key on a `re.Match` should give group with that name'
  273. assert traverse_obj(mobj, 2) == '3', \
  274. 'int key on a `re.Match` should give group with that name'
  275. assert traverse_obj(mobj, 'gRoUp', casesense=False) == '3', \
  276. 'str key on a `re.Match` should respect casesense'
  277. assert traverse_obj(mobj, 'fail') is None, \
  278. 'failing str key on a `re.Match` should return `default`'
  279. assert traverse_obj(mobj, 'gRoUpS', casesense=False) is None, \
  280. 'failing str key on a `re.Match` should return `default`'
  281. assert traverse_obj(mobj, 8) is None, \
  282. 'failing int key on a `re.Match` should return `default`'
  283. assert traverse_obj(mobj, lambda k, _: k in (0, 'group')) == ['0123', '3'], \
  284. 'function on a `re.Match` should give group name as well'
  285. def test_traversal_xml_etree(self):
  286. etree = xml.etree.ElementTree.fromstring('''<?xml version="1.0"?>
  287. <data>
  288. <country name="Liechtenstein">
  289. <rank>1</rank>
  290. <year>2008</year>
  291. <gdppc>141100</gdppc>
  292. <neighbor name="Austria" direction="E"/>
  293. <neighbor name="Switzerland" direction="W"/>
  294. </country>
  295. <country name="Singapore">
  296. <rank>4</rank>
  297. <year>2011</year>
  298. <gdppc>59900</gdppc>
  299. <neighbor name="Malaysia" direction="N"/>
  300. </country>
  301. <country name="Panama">
  302. <rank>68</rank>
  303. <year>2011</year>
  304. <gdppc>13600</gdppc>
  305. <neighbor name="Costa Rica" direction="W"/>
  306. <neighbor name="Colombia" direction="E"/>
  307. </country>
  308. </data>''')
  309. assert traverse_obj(etree, '') == etree, \
  310. 'empty str key should return the element itself'
  311. assert traverse_obj(etree, 'country') == list(etree), \
  312. 'str key should lead all children with that tag name'
  313. assert traverse_obj(etree, ...) == list(etree), \
  314. '`...` as key should return all children'
  315. assert traverse_obj(etree, lambda _, x: x[0].text == '4') == [etree[1]], \
  316. 'function as key should get element as value'
  317. assert traverse_obj(etree, lambda i, _: i == 1) == [etree[1]], \
  318. 'function as key should get index as key'
  319. assert traverse_obj(etree, 0) == etree[0], \
  320. 'int key should return the nth child'
  321. expected = ['Austria', 'Switzerland', 'Malaysia', 'Costa Rica', 'Colombia']
  322. assert traverse_obj(etree, './/neighbor/@name') == expected, \
  323. '`@<attribute>` at end of path should give that attribute'
  324. assert traverse_obj(etree, '//neighbor/@fail') == [None, None, None, None, None], \
  325. '`@<nonexistant>` at end of path should give `None`'
  326. assert traverse_obj(etree, ('//neighbor/@', 2)) == {'name': 'Malaysia', 'direction': 'N'}, \
  327. '`@` should give the full attribute dict'
  328. assert traverse_obj(etree, '//year/text()') == ['2008', '2011', '2011'], \
  329. '`text()` at end of path should give the inner text'
  330. assert traverse_obj(etree, '//*[@direction]/@direction') == ['E', 'W', 'N', 'W', 'E'], \
  331. 'full Python xpath features should be supported'
  332. assert traverse_obj(etree, (0, '@name')) == 'Liechtenstein', \
  333. 'special transformations should act on current element'
  334. assert traverse_obj(etree, ('country', 0, ..., 'text()', {int_or_none})) == [1, 2008, 141100], \
  335. 'special transformations should act on current element'
  336. def test_traversal_unbranching(self):
  337. assert traverse_obj(_TEST_DATA, [(100, 1.2), all]) == [100, 1.2], \
  338. '`all` should give all results as list'
  339. assert traverse_obj(_TEST_DATA, [(100, 1.2), any]) == 100, \
  340. '`any` should give the first result'
  341. assert traverse_obj(_TEST_DATA, [100, all]) == [100], \
  342. '`all` should give list if non branching'
  343. assert traverse_obj(_TEST_DATA, [100, any]) == 100, \
  344. '`any` should give single item if non branching'
  345. assert traverse_obj(_TEST_DATA, [('dict', 'None', 100), all]) == [100], \
  346. '`all` should filter `None` and empty dict'
  347. assert traverse_obj(_TEST_DATA, [('dict', 'None', 100), any]) == 100, \
  348. '`any` should filter `None` and empty dict'
  349. assert traverse_obj(_TEST_DATA, [{
  350. 'all': [('dict', 'None', 100, 1.2), all],
  351. 'any': [('dict', 'None', 100, 1.2), any],
  352. }]) == {'all': [100, 1.2], 'any': 100}, \
  353. '`all`/`any` should apply to each dict path separately'
  354. assert traverse_obj(_TEST_DATA, [{
  355. 'all': [('dict', 'None', 100, 1.2), all],
  356. 'any': [('dict', 'None', 100, 1.2), any],
  357. }], get_all=False) == {'all': [100, 1.2], 'any': 100}, \
  358. '`all`/`any` should apply to dict regardless of `get_all`'
  359. assert traverse_obj(_TEST_DATA, [('dict', 'None', 100, 1.2), all, {float}]) is None, \
  360. '`all` should reset branching status'
  361. assert traverse_obj(_TEST_DATA, [('dict', 'None', 100, 1.2), any, {float}]) is None, \
  362. '`any` should reset branching status'
  363. assert traverse_obj(_TEST_DATA, [('dict', 'None', 100, 1.2), all, ..., {float}]) == [1.2], \
  364. '`all` should allow further branching'
  365. assert traverse_obj(_TEST_DATA, [('dict', 'None', 'urls', 'data'), any, ..., 'index']) == [0, 1], \
  366. '`any` should allow further branching'
  367. def test_traversal_morsel(self):
  368. values = {
  369. 'expires': 'a',
  370. 'path': 'b',
  371. 'comment': 'c',
  372. 'domain': 'd',
  373. 'max-age': 'e',
  374. 'secure': 'f',
  375. 'httponly': 'g',
  376. 'version': 'h',
  377. 'samesite': 'i',
  378. }
  379. morsel = http.cookies.Morsel()
  380. morsel.set('item_key', 'item_value', 'coded_value')
  381. morsel.update(values)
  382. values['key'] = 'item_key'
  383. values['value'] = 'item_value'
  384. for key, value in values.items():
  385. assert traverse_obj(morsel, key) == value, \
  386. 'Morsel should provide access to all values'
  387. assert traverse_obj(morsel, ...) == list(values.values()), \
  388. '`...` should yield all values'
  389. assert traverse_obj(morsel, lambda k, v: True) == list(values.values()), \
  390. 'function key should yield all values'
  391. assert traverse_obj(morsel, [(None,), any]) == morsel, \
  392. 'Morsel should not be implicitly changed to dict on usage'
  393. class TestDictGet:
  394. def test_dict_get(self):
  395. FALSE_VALUES = {
  396. 'none': None,
  397. 'false': False,
  398. 'zero': 0,
  399. 'empty_string': '',
  400. 'empty_list': [],
  401. }
  402. d = {**FALSE_VALUES, 'a': 42}
  403. assert dict_get(d, 'a') == 42
  404. assert dict_get(d, 'b') is None
  405. assert dict_get(d, 'b', 42) == 42
  406. assert dict_get(d, ('a',)) == 42
  407. assert dict_get(d, ('b', 'a')) == 42
  408. assert dict_get(d, ('b', 'c', 'a', 'd')) == 42
  409. assert dict_get(d, ('b', 'c')) is None
  410. assert dict_get(d, ('b', 'c'), 42) == 42
  411. for key, false_value in FALSE_VALUES.items():
  412. assert dict_get(d, ('b', 'c', key)) is None
  413. assert dict_get(d, ('b', 'c', key), skip_false_values=False) == false_value