test_data.py 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500
  1. # -*- coding: utf-8 -*-
  2. """
  3. Tests for salt.utils.data
  4. """
  5. # Import Python libs
  6. from __future__ import absolute_import, print_function, unicode_literals
  7. import logging
  8. # Import Salt libs
  9. import salt.utils.data
  10. import salt.utils.stringutils
  11. from salt.ext import six
  12. # Import 3rd party libs
  13. from salt.ext.six.moves import ( # pylint: disable=import-error,redefined-builtin
  14. builtins,
  15. )
  16. from salt.utils.odict import OrderedDict
  17. from tests.support.mock import patch
  18. from tests.support.unit import LOREM_IPSUM, TestCase
  19. log = logging.getLogger(__name__)
  20. _b = lambda x: x.encode("utf-8")
  21. _s = lambda x: salt.utils.stringutils.to_str(x, normalize=True)
  22. # Some randomized data that will not decode
  23. BYTES = b"1\x814\x10"
  24. # This is an example of a unicode string with й constructed using two separate
  25. # code points. Do not modify it.
  26. EGGS = "\u044f\u0438\u0306\u0446\u0430"
  27. class DataTestCase(TestCase):
  28. test_data = [
  29. "unicode_str",
  30. _b("питон"),
  31. 123,
  32. 456.789,
  33. True,
  34. False,
  35. None,
  36. EGGS,
  37. BYTES,
  38. [123, 456.789, _b("спам"), True, False, None, EGGS, BYTES],
  39. (987, 654.321, _b("яйца"), EGGS, None, (True, EGGS, BYTES)),
  40. {
  41. _b("str_key"): _b("str_val"),
  42. None: True,
  43. 123: 456.789,
  44. EGGS: BYTES,
  45. _b("subdict"): {
  46. "unicode_key": EGGS,
  47. _b("tuple"): (123, "hello", _b("world"), True, EGGS, BYTES),
  48. _b("list"): [456, _b("спам"), False, EGGS, BYTES],
  49. },
  50. },
  51. OrderedDict([(_b("foo"), "bar"), (123, 456), (EGGS, BYTES)]),
  52. ]
  53. def test_sorted_ignorecase(self):
  54. test_list = ["foo", "Foo", "bar", "Bar"]
  55. expected_list = ["bar", "Bar", "foo", "Foo"]
  56. self.assertEqual(salt.utils.data.sorted_ignorecase(test_list), expected_list)
  57. def test_mysql_to_dict(self):
  58. test_mysql_output = [
  59. "+----+------+-----------+------+---------+------+-------+------------------+",
  60. "| Id | User | Host | db | Command | Time | State | Info |",
  61. "+----+------+-----------+------+---------+------+-------+------------------+",
  62. "| 7 | root | localhost | NULL | Query | 0 | init | show processlist |",
  63. "+----+------+-----------+------+---------+------+-------+------------------+",
  64. ]
  65. ret = salt.utils.data.mysql_to_dict(test_mysql_output, "Info")
  66. expected_dict = {
  67. "show processlist": {
  68. "Info": "show processlist",
  69. "db": "NULL",
  70. "State": "init",
  71. "Host": "localhost",
  72. "Command": "Query",
  73. "User": "root",
  74. "Time": 0,
  75. "Id": 7,
  76. }
  77. }
  78. self.assertDictEqual(ret, expected_dict)
  79. def test_subdict_match(self):
  80. test_two_level_dict = {"foo": {"bar": "baz"}}
  81. test_two_level_comb_dict = {"foo": {"bar": "baz:woz"}}
  82. test_two_level_dict_and_list = {
  83. "abc": ["def", "ghi", {"lorem": {"ipsum": [{"dolor": "sit"}]}}],
  84. }
  85. test_three_level_dict = {"a": {"b": {"c": "v"}}}
  86. self.assertTrue(
  87. salt.utils.data.subdict_match(test_two_level_dict, "foo:bar:baz")
  88. )
  89. # In test_two_level_comb_dict, 'foo:bar' corresponds to 'baz:woz', not
  90. # 'baz'. This match should return False.
  91. self.assertFalse(
  92. salt.utils.data.subdict_match(test_two_level_comb_dict, "foo:bar:baz")
  93. )
  94. # This tests matching with the delimiter in the value part (in other
  95. # words, that the path 'foo:bar' corresponds to the string 'baz:woz').
  96. self.assertTrue(
  97. salt.utils.data.subdict_match(test_two_level_comb_dict, "foo:bar:baz:woz")
  98. )
  99. # This would match if test_two_level_comb_dict['foo']['bar'] was equal
  100. # to 'baz:woz:wiz', or if there was more deep nesting. But it does not,
  101. # so this should return False.
  102. self.assertFalse(
  103. salt.utils.data.subdict_match(
  104. test_two_level_comb_dict, "foo:bar:baz:woz:wiz"
  105. )
  106. )
  107. # This tests for cases when a key path corresponds to a list. The
  108. # value part 'ghi' should be successfully matched as it is a member of
  109. # the list corresponding to key path 'abc'. It is somewhat a
  110. # duplication of a test within test_traverse_dict_and_list, but
  111. # salt.utils.data.subdict_match() does more than just invoke
  112. # salt.utils.traverse_list_and_dict() so this particular assertion is a
  113. # sanity check.
  114. self.assertTrue(
  115. salt.utils.data.subdict_match(test_two_level_dict_and_list, "abc:ghi")
  116. )
  117. # This tests the use case of a dict embedded in a list, embedded in a
  118. # list, embedded in a dict. This is a rather absurd case, but it
  119. # confirms that match recursion works properly.
  120. self.assertTrue(
  121. salt.utils.data.subdict_match(
  122. test_two_level_dict_and_list, "abc:lorem:ipsum:dolor:sit"
  123. )
  124. )
  125. # Test four level dict match for reference
  126. self.assertTrue(salt.utils.data.subdict_match(test_three_level_dict, "a:b:c:v"))
  127. # Test regression in 2015.8 where 'a:c:v' would match 'a:b:c:v'
  128. self.assertFalse(salt.utils.data.subdict_match(test_three_level_dict, "a:c:v"))
  129. # Test wildcard match
  130. self.assertTrue(salt.utils.data.subdict_match(test_three_level_dict, "a:*:c:v"))
  131. def test_subdict_match_with_wildcards(self):
  132. """
  133. Tests subdict matching when wildcards are used in the expression
  134. """
  135. data = {"a": {"b": {"ç": "d", "é": ["eff", "gee", "8ch"], "ĩ": {"j": "k"}}}}
  136. assert salt.utils.data.subdict_match(data, "*:*:*:*")
  137. assert salt.utils.data.subdict_match(data, "a:*:*:*")
  138. assert salt.utils.data.subdict_match(data, "a:b:*:*")
  139. assert salt.utils.data.subdict_match(data, "a:b:ç:*")
  140. assert salt.utils.data.subdict_match(data, "a:b:*:d")
  141. assert salt.utils.data.subdict_match(data, "a:*:ç:d")
  142. assert salt.utils.data.subdict_match(data, "*:b:ç:d")
  143. assert salt.utils.data.subdict_match(data, "*:*:ç:d")
  144. assert salt.utils.data.subdict_match(data, "*:*:*:d")
  145. assert salt.utils.data.subdict_match(data, "a:*:*:d")
  146. assert salt.utils.data.subdict_match(data, "a:b:*:ef*")
  147. assert salt.utils.data.subdict_match(data, "a:b:*:g*")
  148. assert salt.utils.data.subdict_match(data, "a:b:*:j:*")
  149. assert salt.utils.data.subdict_match(data, "a:b:*:j:k")
  150. assert salt.utils.data.subdict_match(data, "a:b:*:*:k")
  151. assert salt.utils.data.subdict_match(data, "a:b:*:*:*")
  152. def test_traverse_dict(self):
  153. test_two_level_dict = {"foo": {"bar": "baz"}}
  154. self.assertDictEqual(
  155. {"not_found": "nope"},
  156. salt.utils.data.traverse_dict(
  157. test_two_level_dict, "foo:bar:baz", {"not_found": "nope"}
  158. ),
  159. )
  160. self.assertEqual(
  161. "baz",
  162. salt.utils.data.traverse_dict(
  163. test_two_level_dict, "foo:bar", {"not_found": "not_found"}
  164. ),
  165. )
  166. def test_traverse_dict_and_list(self):
  167. test_two_level_dict = {"foo": {"bar": "baz"}}
  168. test_two_level_dict_and_list = {
  169. "foo": ["bar", "baz", {"lorem": {"ipsum": [{"dolor": "sit"}]}}]
  170. }
  171. # Check traversing too far: salt.utils.data.traverse_dict_and_list() returns
  172. # the value corresponding to a given key path, and baz is a value
  173. # corresponding to the key path foo:bar.
  174. self.assertDictEqual(
  175. {"not_found": "nope"},
  176. salt.utils.data.traverse_dict_and_list(
  177. test_two_level_dict, "foo:bar:baz", {"not_found": "nope"}
  178. ),
  179. )
  180. # Now check to ensure that foo:bar corresponds to baz
  181. self.assertEqual(
  182. "baz",
  183. salt.utils.data.traverse_dict_and_list(
  184. test_two_level_dict, "foo:bar", {"not_found": "not_found"}
  185. ),
  186. )
  187. # Check traversing too far
  188. self.assertDictEqual(
  189. {"not_found": "nope"},
  190. salt.utils.data.traverse_dict_and_list(
  191. test_two_level_dict_and_list, "foo:bar", {"not_found": "nope"}
  192. ),
  193. )
  194. # Check index 1 (2nd element) of list corresponding to path 'foo'
  195. self.assertEqual(
  196. "baz",
  197. salt.utils.data.traverse_dict_and_list(
  198. test_two_level_dict_and_list, "foo:1", {"not_found": "not_found"}
  199. ),
  200. )
  201. # Traverse a couple times into dicts embedded in lists
  202. self.assertEqual(
  203. "sit",
  204. salt.utils.data.traverse_dict_and_list(
  205. test_two_level_dict_and_list,
  206. "foo:lorem:ipsum:dolor",
  207. {"not_found": "not_found"},
  208. ),
  209. )
  210. # Traverse and match integer key in a nested dict
  211. # https://github.com/saltstack/salt/issues/56444
  212. self.assertEqual(
  213. "it worked",
  214. salt.utils.data.traverse_dict_and_list(
  215. {"foo": {1234: "it worked"}}, "foo:1234", "it didn't work",
  216. ),
  217. )
  218. # Make sure that we properly return the default value when the initial
  219. # attempt fails and YAML-loading the target key doesn't change its
  220. # value.
  221. self.assertEqual(
  222. "default",
  223. salt.utils.data.traverse_dict_and_list(
  224. {"foo": {"baz": "didn't work"}}, "foo:bar", "default",
  225. ),
  226. )
  227. def test_compare_dicts(self):
  228. ret = salt.utils.data.compare_dicts(old={"foo": "bar"}, new={"foo": "bar"})
  229. self.assertEqual(ret, {})
  230. ret = salt.utils.data.compare_dicts(old={"foo": "bar"}, new={"foo": "woz"})
  231. expected_ret = {"foo": {"new": "woz", "old": "bar"}}
  232. self.assertDictEqual(ret, expected_ret)
  233. def test_compare_lists_no_change(self):
  234. ret = salt.utils.data.compare_lists(
  235. old=[1, 2, 3, "a", "b", "c"], new=[1, 2, 3, "a", "b", "c"]
  236. )
  237. expected = {}
  238. self.assertDictEqual(ret, expected)
  239. def test_compare_lists_changes(self):
  240. ret = salt.utils.data.compare_lists(
  241. old=[1, 2, 3, "a", "b", "c"], new=[1, 2, 4, "x", "y", "z"]
  242. )
  243. expected = {"new": [4, "x", "y", "z"], "old": [3, "a", "b", "c"]}
  244. self.assertDictEqual(ret, expected)
  245. def test_compare_lists_changes_new(self):
  246. ret = salt.utils.data.compare_lists(old=[1, 2, 3], new=[1, 2, 3, "x", "y", "z"])
  247. expected = {"new": ["x", "y", "z"]}
  248. self.assertDictEqual(ret, expected)
  249. def test_compare_lists_changes_old(self):
  250. ret = salt.utils.data.compare_lists(old=[1, 2, 3, "a", "b", "c"], new=[1, 2, 3])
  251. expected = {"old": ["a", "b", "c"]}
  252. self.assertDictEqual(ret, expected)
  253. def test_decode(self):
  254. """
  255. Companion to test_decode_to_str, they should both be kept up-to-date
  256. with one another.
  257. NOTE: This uses the lambda "_b" defined above in the global scope,
  258. which encodes a string to a bytestring, assuming utf-8.
  259. """
  260. expected = [
  261. "unicode_str",
  262. "питон",
  263. 123,
  264. 456.789,
  265. True,
  266. False,
  267. None,
  268. "яйца",
  269. BYTES,
  270. [123, 456.789, "спам", True, False, None, "яйца", BYTES],
  271. (987, 654.321, "яйца", "яйца", None, (True, "яйца", BYTES)),
  272. {
  273. "str_key": "str_val",
  274. None: True,
  275. 123: 456.789,
  276. "яйца": BYTES,
  277. "subdict": {
  278. "unicode_key": "яйца",
  279. "tuple": (123, "hello", "world", True, "яйца", BYTES),
  280. "list": [456, "спам", False, "яйца", BYTES],
  281. },
  282. },
  283. OrderedDict([("foo", "bar"), (123, 456), ("яйца", BYTES)]),
  284. ]
  285. ret = salt.utils.data.decode(
  286. self.test_data,
  287. keep=True,
  288. normalize=True,
  289. preserve_dict_class=True,
  290. preserve_tuples=True,
  291. )
  292. self.assertEqual(ret, expected)
  293. # The binary data in the data structure should fail to decode, even
  294. # using the fallback, and raise an exception.
  295. self.assertRaises(
  296. UnicodeDecodeError,
  297. salt.utils.data.decode,
  298. self.test_data,
  299. keep=False,
  300. normalize=True,
  301. preserve_dict_class=True,
  302. preserve_tuples=True,
  303. )
  304. # Now munge the expected data so that we get what we would expect if we
  305. # disable preservation of dict class and tuples
  306. expected[10] = [987, 654.321, "яйца", "яйца", None, [True, "яйца", BYTES]]
  307. expected[11]["subdict"]["tuple"] = [123, "hello", "world", True, "яйца", BYTES]
  308. expected[12] = {"foo": "bar", 123: 456, "яйца": BYTES}
  309. ret = salt.utils.data.decode(
  310. self.test_data,
  311. keep=True,
  312. normalize=True,
  313. preserve_dict_class=False,
  314. preserve_tuples=False,
  315. )
  316. self.assertEqual(ret, expected)
  317. # Now test single non-string, non-data-structure items, these should
  318. # return the same value when passed to this function
  319. for item in (123, 4.56, True, False, None):
  320. log.debug("Testing decode of %s", item)
  321. self.assertEqual(salt.utils.data.decode(item), item)
  322. # Test single strings (not in a data structure)
  323. self.assertEqual(salt.utils.data.decode("foo"), "foo")
  324. self.assertEqual(salt.utils.data.decode(_b("bar")), "bar")
  325. self.assertEqual(salt.utils.data.decode(EGGS, normalize=True), "яйца")
  326. self.assertEqual(salt.utils.data.decode(EGGS, normalize=False), EGGS)
  327. # Test binary blob
  328. self.assertEqual(salt.utils.data.decode(BYTES, keep=True), BYTES)
  329. self.assertRaises(UnicodeDecodeError, salt.utils.data.decode, BYTES, keep=False)
  330. def test_circular_refs_dicts(self):
  331. test_dict = {"key": "value", "type": "test1"}
  332. test_dict["self"] = test_dict
  333. ret = salt.utils.data._remove_circular_refs(ob=test_dict)
  334. self.assertDictEqual(ret, {"key": "value", "type": "test1", "self": None})
  335. def test_circular_refs_lists(self):
  336. test_list = {
  337. "foo": [],
  338. }
  339. test_list["foo"].append((test_list,))
  340. ret = salt.utils.data._remove_circular_refs(ob=test_list)
  341. self.assertDictEqual(ret, {"foo": [(None,)]})
  342. def test_circular_refs_tuple(self):
  343. test_dup = {"foo": "string 1", "bar": "string 1", "ham": 1, "spam": 1}
  344. ret = salt.utils.data._remove_circular_refs(ob=test_dup)
  345. self.assertDictEqual(
  346. ret, {"foo": "string 1", "bar": "string 1", "ham": 1, "spam": 1}
  347. )
  348. def test_decode_to_str(self):
  349. """
  350. Companion to test_decode, they should both be kept up-to-date with one
  351. another.
  352. NOTE: This uses the lambda "_s" defined above in the global scope,
  353. which converts the string/bytestring to a str type.
  354. """
  355. expected = [
  356. _s("unicode_str"),
  357. _s("питон"),
  358. 123,
  359. 456.789,
  360. True,
  361. False,
  362. None,
  363. _s("яйца"),
  364. BYTES,
  365. [123, 456.789, _s("спам"), True, False, None, _s("яйца"), BYTES],
  366. (987, 654.321, _s("яйца"), _s("яйца"), None, (True, _s("яйца"), BYTES)),
  367. {
  368. _s("str_key"): _s("str_val"),
  369. None: True,
  370. 123: 456.789,
  371. _s("яйца"): BYTES,
  372. _s("subdict"): {
  373. _s("unicode_key"): _s("яйца"),
  374. _s("tuple"): (
  375. 123,
  376. _s("hello"),
  377. _s("world"),
  378. True,
  379. _s("яйца"),
  380. BYTES,
  381. ),
  382. _s("list"): [456, _s("спам"), False, _s("яйца"), BYTES],
  383. },
  384. },
  385. OrderedDict([(_s("foo"), _s("bar")), (123, 456), (_s("яйца"), BYTES)]),
  386. ]
  387. ret = salt.utils.data.decode(
  388. self.test_data,
  389. keep=True,
  390. normalize=True,
  391. preserve_dict_class=True,
  392. preserve_tuples=True,
  393. to_str=True,
  394. )
  395. self.assertEqual(ret, expected)
  396. if six.PY3:
  397. # The binary data in the data structure should fail to decode, even
  398. # using the fallback, and raise an exception.
  399. self.assertRaises(
  400. UnicodeDecodeError,
  401. salt.utils.data.decode,
  402. self.test_data,
  403. keep=False,
  404. normalize=True,
  405. preserve_dict_class=True,
  406. preserve_tuples=True,
  407. to_str=True,
  408. )
  409. # Now munge the expected data so that we get what we would expect if we
  410. # disable preservation of dict class and tuples
  411. expected[10] = [
  412. 987,
  413. 654.321,
  414. _s("яйца"),
  415. _s("яйца"),
  416. None,
  417. [True, _s("яйца"), BYTES],
  418. ]
  419. expected[11][_s("subdict")][_s("tuple")] = [
  420. 123,
  421. _s("hello"),
  422. _s("world"),
  423. True,
  424. _s("яйца"),
  425. BYTES,
  426. ]
  427. expected[12] = {_s("foo"): _s("bar"), 123: 456, _s("яйца"): BYTES}
  428. ret = salt.utils.data.decode(
  429. self.test_data,
  430. keep=True,
  431. normalize=True,
  432. preserve_dict_class=False,
  433. preserve_tuples=False,
  434. to_str=True,
  435. )
  436. self.assertEqual(ret, expected)
  437. # Now test single non-string, non-data-structure items, these should
  438. # return the same value when passed to this function
  439. for item in (123, 4.56, True, False, None):
  440. log.debug("Testing decode of %s", item)
  441. self.assertEqual(salt.utils.data.decode(item, to_str=True), item)
  442. # Test single strings (not in a data structure)
  443. self.assertEqual(salt.utils.data.decode("foo", to_str=True), _s("foo"))
  444. self.assertEqual(salt.utils.data.decode(_b("bar"), to_str=True), _s("bar"))
  445. # Test binary blob
  446. self.assertEqual(salt.utils.data.decode(BYTES, keep=True, to_str=True), BYTES)
  447. if six.PY3:
  448. self.assertRaises(
  449. UnicodeDecodeError,
  450. salt.utils.data.decode,
  451. BYTES,
  452. keep=False,
  453. to_str=True,
  454. )
  455. def test_decode_fallback(self):
  456. """
  457. Test fallback to utf-8
  458. """
  459. with patch.object(builtins, "__salt_system_encoding__", "ascii"):
  460. self.assertEqual(salt.utils.data.decode(_b("яйца")), "яйца")
  461. def test_encode(self):
  462. """
  463. NOTE: This uses the lambda "_b" defined above in the global scope,
  464. which encodes a string to a bytestring, assuming utf-8.
  465. """
  466. expected = [
  467. _b("unicode_str"),
  468. _b("питон"),
  469. 123,
  470. 456.789,
  471. True,
  472. False,
  473. None,
  474. _b(EGGS),
  475. BYTES,
  476. [123, 456.789, _b("спам"), True, False, None, _b(EGGS), BYTES],
  477. (987, 654.321, _b("яйца"), _b(EGGS), None, (True, _b(EGGS), BYTES)),
  478. {
  479. _b("str_key"): _b("str_val"),
  480. None: True,
  481. 123: 456.789,
  482. _b(EGGS): BYTES,
  483. _b("subdict"): {
  484. _b("unicode_key"): _b(EGGS),
  485. _b("tuple"): (123, _b("hello"), _b("world"), True, _b(EGGS), BYTES),
  486. _b("list"): [456, _b("спам"), False, _b(EGGS), BYTES],
  487. },
  488. },
  489. OrderedDict([(_b("foo"), _b("bar")), (123, 456), (_b(EGGS), BYTES)]),
  490. ]
  491. # Both keep=True and keep=False should work because the BYTES data is
  492. # already bytes.
  493. ret = salt.utils.data.encode(
  494. self.test_data, keep=True, preserve_dict_class=True, preserve_tuples=True
  495. )
  496. self.assertEqual(ret, expected)
  497. ret = salt.utils.data.encode(
  498. self.test_data, keep=False, preserve_dict_class=True, preserve_tuples=True
  499. )
  500. self.assertEqual(ret, expected)
  501. # Now munge the expected data so that we get what we would expect if we
  502. # disable preservation of dict class and tuples
  503. expected[10] = [
  504. 987,
  505. 654.321,
  506. _b("яйца"),
  507. _b(EGGS),
  508. None,
  509. [True, _b(EGGS), BYTES],
  510. ]
  511. expected[11][_b("subdict")][_b("tuple")] = [
  512. 123,
  513. _b("hello"),
  514. _b("world"),
  515. True,
  516. _b(EGGS),
  517. BYTES,
  518. ]
  519. expected[12] = {_b("foo"): _b("bar"), 123: 456, _b(EGGS): BYTES}
  520. ret = salt.utils.data.encode(
  521. self.test_data, keep=True, preserve_dict_class=False, preserve_tuples=False
  522. )
  523. self.assertEqual(ret, expected)
  524. ret = salt.utils.data.encode(
  525. self.test_data, keep=False, preserve_dict_class=False, preserve_tuples=False
  526. )
  527. self.assertEqual(ret, expected)
  528. # Now test single non-string, non-data-structure items, these should
  529. # return the same value when passed to this function
  530. for item in (123, 4.56, True, False, None):
  531. log.debug("Testing encode of %s", item)
  532. self.assertEqual(salt.utils.data.encode(item), item)
  533. # Test single strings (not in a data structure)
  534. self.assertEqual(salt.utils.data.encode("foo"), _b("foo"))
  535. self.assertEqual(salt.utils.data.encode(_b("bar")), _b("bar"))
  536. # Test binary blob, nothing should happen even when keep=False since
  537. # the data is already bytes
  538. self.assertEqual(salt.utils.data.encode(BYTES, keep=True), BYTES)
  539. self.assertEqual(salt.utils.data.encode(BYTES, keep=False), BYTES)
  540. def test_encode_keep(self):
  541. """
  542. Whereas we tested the keep argument in test_decode, it is much easier
  543. to do a more comprehensive test of keep in its own function where we
  544. can force the encoding.
  545. """
  546. unicode_str = "питон"
  547. encoding = "ascii"
  548. # Test single string
  549. self.assertEqual(
  550. salt.utils.data.encode(unicode_str, encoding, keep=True), unicode_str
  551. )
  552. self.assertRaises(
  553. UnicodeEncodeError,
  554. salt.utils.data.encode,
  555. unicode_str,
  556. encoding,
  557. keep=False,
  558. )
  559. data = [
  560. unicode_str,
  561. [b"foo", [unicode_str], {b"key": unicode_str}, (unicode_str,)],
  562. {
  563. b"list": [b"foo", unicode_str],
  564. b"dict": {b"key": unicode_str},
  565. b"tuple": (b"foo", unicode_str),
  566. },
  567. ([b"foo", unicode_str], {b"key": unicode_str}, (unicode_str,)),
  568. ]
  569. # Since everything was a bytestring aside from the bogus data, the
  570. # return data should be identical. We don't need to test recursive
  571. # decoding, that has already been tested in test_encode.
  572. self.assertEqual(
  573. salt.utils.data.encode(data, encoding, keep=True, preserve_tuples=True),
  574. data,
  575. )
  576. self.assertRaises(
  577. UnicodeEncodeError,
  578. salt.utils.data.encode,
  579. data,
  580. encoding,
  581. keep=False,
  582. preserve_tuples=True,
  583. )
  584. for index, _ in enumerate(data):
  585. self.assertEqual(
  586. salt.utils.data.encode(
  587. data[index], encoding, keep=True, preserve_tuples=True
  588. ),
  589. data[index],
  590. )
  591. self.assertRaises(
  592. UnicodeEncodeError,
  593. salt.utils.data.encode,
  594. data[index],
  595. encoding,
  596. keep=False,
  597. preserve_tuples=True,
  598. )
  599. def test_encode_fallback(self):
  600. """
  601. Test fallback to utf-8
  602. """
  603. with patch.object(builtins, "__salt_system_encoding__", "ascii"):
  604. self.assertEqual(salt.utils.data.encode("яйца"), _b("яйца"))
  605. with patch.object(builtins, "__salt_system_encoding__", "CP1252"):
  606. self.assertEqual(salt.utils.data.encode("Ψ"), _b("Ψ"))
  607. def test_repack_dict(self):
  608. list_of_one_element_dicts = [
  609. {"dict_key_1": "dict_val_1"},
  610. {"dict_key_2": "dict_val_2"},
  611. {"dict_key_3": "dict_val_3"},
  612. ]
  613. expected_ret = {
  614. "dict_key_1": "dict_val_1",
  615. "dict_key_2": "dict_val_2",
  616. "dict_key_3": "dict_val_3",
  617. }
  618. ret = salt.utils.data.repack_dictlist(list_of_one_element_dicts)
  619. self.assertDictEqual(ret, expected_ret)
  620. # Try with yaml
  621. yaml_key_val_pair = "- key1: val1"
  622. ret = salt.utils.data.repack_dictlist(yaml_key_val_pair)
  623. self.assertDictEqual(ret, {"key1": "val1"})
  624. # Make sure we handle non-yaml junk data
  625. ret = salt.utils.data.repack_dictlist(LOREM_IPSUM)
  626. self.assertDictEqual(ret, {})
  627. def test_stringify(self):
  628. self.assertRaises(TypeError, salt.utils.data.stringify, 9)
  629. self.assertEqual(
  630. salt.utils.data.stringify(
  631. ["one", "two", str("three"), 4, 5]
  632. ), # future lint: disable=blacklisted-function
  633. ["one", "two", "three", "4", "5"],
  634. )
  635. def test_json_query(self):
  636. # Raises exception if jmespath module is not found
  637. with patch("salt.utils.data.jmespath", None):
  638. self.assertRaisesRegex(
  639. RuntimeError, "requires jmespath", salt.utils.data.json_query, {}, "@"
  640. )
  641. # Test search
  642. user_groups = {
  643. "user1": {"groups": ["group1", "group2", "group3"]},
  644. "user2": {"groups": ["group1", "group2"]},
  645. "user3": {"groups": ["group3"]},
  646. }
  647. expression = "*.groups[0]"
  648. primary_groups = ["group1", "group1", "group3"]
  649. self.assertEqual(
  650. sorted(salt.utils.data.json_query(user_groups, expression)), primary_groups
  651. )
  652. class FilterFalseyTestCase(TestCase):
  653. """
  654. Test suite for salt.utils.data.filter_falsey
  655. """
  656. def test_nop(self):
  657. """
  658. Test cases where nothing will be done.
  659. """
  660. # Test with dictionary without recursion
  661. old_dict = {
  662. "foo": "bar",
  663. "bar": {"baz": {"qux": "quux"}},
  664. "baz": ["qux", {"foo": "bar"}],
  665. }
  666. new_dict = salt.utils.data.filter_falsey(old_dict)
  667. self.assertEqual(old_dict, new_dict)
  668. # Check returned type equality
  669. self.assertIs(type(old_dict), type(new_dict))
  670. # Test dictionary with recursion
  671. new_dict = salt.utils.data.filter_falsey(old_dict, recurse_depth=3)
  672. self.assertEqual(old_dict, new_dict)
  673. # Test with list
  674. old_list = ["foo", "bar"]
  675. new_list = salt.utils.data.filter_falsey(old_list)
  676. self.assertEqual(old_list, new_list)
  677. # Check returned type equality
  678. self.assertIs(type(old_list), type(new_list))
  679. # Test with set
  680. old_set = set(["foo", "bar"])
  681. new_set = salt.utils.data.filter_falsey(old_set)
  682. self.assertEqual(old_set, new_set)
  683. # Check returned type equality
  684. self.assertIs(type(old_set), type(new_set))
  685. # Test with OrderedDict
  686. old_dict = OrderedDict(
  687. [
  688. ("foo", "bar"),
  689. ("bar", OrderedDict([("qux", "quux")])),
  690. ("baz", ["qux", OrderedDict([("foo", "bar")])]),
  691. ]
  692. )
  693. new_dict = salt.utils.data.filter_falsey(old_dict)
  694. self.assertEqual(old_dict, new_dict)
  695. self.assertIs(type(old_dict), type(new_dict))
  696. # Test excluding int
  697. old_list = [0]
  698. new_list = salt.utils.data.filter_falsey(old_list, ignore_types=[type(0)])
  699. self.assertEqual(old_list, new_list)
  700. # Test excluding str (or unicode) (or both)
  701. old_list = [""]
  702. new_list = salt.utils.data.filter_falsey(old_list, ignore_types=[type("")])
  703. self.assertEqual(old_list, new_list)
  704. # Test excluding list
  705. old_list = [[]]
  706. new_list = salt.utils.data.filter_falsey(old_list, ignore_types=[type([])])
  707. self.assertEqual(old_list, new_list)
  708. # Test excluding dict
  709. old_list = [{}]
  710. new_list = salt.utils.data.filter_falsey(old_list, ignore_types=[type({})])
  711. self.assertEqual(old_list, new_list)
  712. def test_filter_dict_no_recurse(self):
  713. """
  714. Test filtering a dictionary without recursing.
  715. This will only filter out key-values where the values are falsey.
  716. """
  717. old_dict = {
  718. "foo": None,
  719. "bar": {"baz": {"qux": None, "quux": "", "foo": []}},
  720. "baz": ["qux"],
  721. "qux": {},
  722. "quux": [],
  723. }
  724. new_dict = salt.utils.data.filter_falsey(old_dict)
  725. expect_dict = {
  726. "bar": {"baz": {"qux": None, "quux": "", "foo": []}},
  727. "baz": ["qux"],
  728. }
  729. self.assertEqual(expect_dict, new_dict)
  730. self.assertIs(type(expect_dict), type(new_dict))
  731. def test_filter_dict_recurse(self):
  732. """
  733. Test filtering a dictionary with recursing.
  734. This will filter out any key-values where the values are falsey or when
  735. the values *become* falsey after filtering their contents (in case they
  736. are lists or dicts).
  737. """
  738. old_dict = {
  739. "foo": None,
  740. "bar": {"baz": {"qux": None, "quux": "", "foo": []}},
  741. "baz": ["qux"],
  742. "qux": {},
  743. "quux": [],
  744. }
  745. new_dict = salt.utils.data.filter_falsey(old_dict, recurse_depth=3)
  746. expect_dict = {"baz": ["qux"]}
  747. self.assertEqual(expect_dict, new_dict)
  748. self.assertIs(type(expect_dict), type(new_dict))
  749. def test_filter_list_no_recurse(self):
  750. """
  751. Test filtering a list without recursing.
  752. This will only filter out items which are falsey.
  753. """
  754. old_list = ["foo", None, [], {}, 0, ""]
  755. new_list = salt.utils.data.filter_falsey(old_list)
  756. expect_list = ["foo"]
  757. self.assertEqual(expect_list, new_list)
  758. self.assertIs(type(expect_list), type(new_list))
  759. # Ensure nested values are *not* filtered out.
  760. old_list = [
  761. "foo",
  762. ["foo"],
  763. ["foo", None],
  764. {"foo": 0},
  765. {"foo": "bar", "baz": []},
  766. [{"foo": ""}],
  767. ]
  768. new_list = salt.utils.data.filter_falsey(old_list)
  769. self.assertEqual(old_list, new_list)
  770. self.assertIs(type(old_list), type(new_list))
  771. def test_filter_list_recurse(self):
  772. """
  773. Test filtering a list with recursing.
  774. This will filter out any items which are falsey, or which become falsey
  775. after filtering their contents (in case they are lists or dicts).
  776. """
  777. old_list = [
  778. "foo",
  779. ["foo"],
  780. ["foo", None],
  781. {"foo": 0},
  782. {"foo": "bar", "baz": []},
  783. [{"foo": ""}],
  784. ]
  785. new_list = salt.utils.data.filter_falsey(old_list, recurse_depth=3)
  786. expect_list = ["foo", ["foo"], ["foo"], {"foo": "bar"}]
  787. self.assertEqual(expect_list, new_list)
  788. self.assertIs(type(expect_list), type(new_list))
  789. def test_filter_set_no_recurse(self):
  790. """
  791. Test filtering a set without recursing.
  792. Note that a set cannot contain unhashable types, so recursion is not possible.
  793. """
  794. old_set = set(["foo", None, 0, ""])
  795. new_set = salt.utils.data.filter_falsey(old_set)
  796. expect_set = set(["foo"])
  797. self.assertEqual(expect_set, new_set)
  798. self.assertIs(type(expect_set), type(new_set))
  799. def test_filter_ordereddict_no_recurse(self):
  800. """
  801. Test filtering an OrderedDict without recursing.
  802. """
  803. old_dict = OrderedDict(
  804. [
  805. ("foo", None),
  806. (
  807. "bar",
  808. OrderedDict(
  809. [
  810. (
  811. "baz",
  812. OrderedDict([("qux", None), ("quux", ""), ("foo", [])]),
  813. )
  814. ]
  815. ),
  816. ),
  817. ("baz", ["qux"]),
  818. ("qux", {}),
  819. ("quux", []),
  820. ]
  821. )
  822. new_dict = salt.utils.data.filter_falsey(old_dict)
  823. expect_dict = OrderedDict(
  824. [
  825. (
  826. "bar",
  827. OrderedDict(
  828. [
  829. (
  830. "baz",
  831. OrderedDict([("qux", None), ("quux", ""), ("foo", [])]),
  832. )
  833. ]
  834. ),
  835. ),
  836. ("baz", ["qux"]),
  837. ]
  838. )
  839. self.assertEqual(expect_dict, new_dict)
  840. self.assertIs(type(expect_dict), type(new_dict))
  841. def test_filter_ordereddict_recurse(self):
  842. """
  843. Test filtering an OrderedDict with recursing.
  844. """
  845. old_dict = OrderedDict(
  846. [
  847. ("foo", None),
  848. (
  849. "bar",
  850. OrderedDict(
  851. [
  852. (
  853. "baz",
  854. OrderedDict([("qux", None), ("quux", ""), ("foo", [])]),
  855. )
  856. ]
  857. ),
  858. ),
  859. ("baz", ["qux"]),
  860. ("qux", {}),
  861. ("quux", []),
  862. ]
  863. )
  864. new_dict = salt.utils.data.filter_falsey(old_dict, recurse_depth=3)
  865. expect_dict = OrderedDict([("baz", ["qux"])])
  866. self.assertEqual(expect_dict, new_dict)
  867. self.assertIs(type(expect_dict), type(new_dict))
  868. def test_filter_list_recurse_limit(self):
  869. """
  870. Test filtering a list with recursing, but with a limited depth.
  871. Note that the top-level is always processed, so a recursion depth of 2
  872. means that two *additional* levels are processed.
  873. """
  874. old_list = [None, [None, [None, [None]]]]
  875. new_list = salt.utils.data.filter_falsey(old_list, recurse_depth=2)
  876. self.assertEqual([[[[None]]]], new_list)
  877. def test_filter_dict_recurse_limit(self):
  878. """
  879. Test filtering a dict with recursing, but with a limited depth.
  880. Note that the top-level is always processed, so a recursion depth of 2
  881. means that two *additional* levels are processed.
  882. """
  883. old_dict = {
  884. "one": None,
  885. "foo": {"two": None, "bar": {"three": None, "baz": {"four": None}}},
  886. }
  887. new_dict = salt.utils.data.filter_falsey(old_dict, recurse_depth=2)
  888. self.assertEqual({"foo": {"bar": {"baz": {"four": None}}}}, new_dict)
  889. def test_filter_exclude_types(self):
  890. """
  891. Test filtering a list recursively, but also ignoring (i.e. not filtering)
  892. out certain types that can be falsey.
  893. """
  894. # Ignore int, unicode
  895. old_list = [
  896. "foo",
  897. ["foo"],
  898. ["foo", None],
  899. {"foo": 0},
  900. {"foo": "bar", "baz": []},
  901. [{"foo": ""}],
  902. ]
  903. new_list = salt.utils.data.filter_falsey(
  904. old_list, recurse_depth=3, ignore_types=[type(0), type("")]
  905. )
  906. self.assertEqual(
  907. ["foo", ["foo"], ["foo"], {"foo": 0}, {"foo": "bar"}, [{"foo": ""}]],
  908. new_list,
  909. )
  910. # Ignore list
  911. old_list = [
  912. "foo",
  913. ["foo"],
  914. ["foo", None],
  915. {"foo": 0},
  916. {"foo": "bar", "baz": []},
  917. [{"foo": ""}],
  918. ]
  919. new_list = salt.utils.data.filter_falsey(
  920. old_list, recurse_depth=3, ignore_types=[type([])]
  921. )
  922. self.assertEqual(
  923. ["foo", ["foo"], ["foo"], {"foo": "bar", "baz": []}, []], new_list
  924. )
  925. # Ignore dict
  926. old_list = [
  927. "foo",
  928. ["foo"],
  929. ["foo", None],
  930. {"foo": 0},
  931. {"foo": "bar", "baz": []},
  932. [{"foo": ""}],
  933. ]
  934. new_list = salt.utils.data.filter_falsey(
  935. old_list, recurse_depth=3, ignore_types=[type({})]
  936. )
  937. self.assertEqual(["foo", ["foo"], ["foo"], {}, {"foo": "bar"}, [{}]], new_list)
  938. # Ignore NoneType
  939. old_list = [
  940. "foo",
  941. ["foo"],
  942. ["foo", None],
  943. {"foo": 0},
  944. {"foo": "bar", "baz": []},
  945. [{"foo": ""}],
  946. ]
  947. new_list = salt.utils.data.filter_falsey(
  948. old_list, recurse_depth=3, ignore_types=[type(None)]
  949. )
  950. self.assertEqual(["foo", ["foo"], ["foo", None], {"foo": "bar"}], new_list)
  951. class FilterRecursiveDiff(TestCase):
  952. """
  953. Test suite for salt.utils.data.recursive_diff
  954. """
  955. def test_list_equality(self):
  956. """
  957. Test cases where equal lists are compared.
  958. """
  959. test_list = [0, 1, 2]
  960. self.assertEqual({}, salt.utils.data.recursive_diff(test_list, test_list))
  961. test_list = [[0], [1], [0, 1, 2]]
  962. self.assertEqual({}, salt.utils.data.recursive_diff(test_list, test_list))
  963. def test_dict_equality(self):
  964. """
  965. Test cases where equal dicts are compared.
  966. """
  967. test_dict = {"foo": "bar", "bar": {"baz": {"qux": "quux"}}, "frop": 0}
  968. self.assertEqual({}, salt.utils.data.recursive_diff(test_dict, test_dict))
  969. def test_ordereddict_equality(self):
  970. """
  971. Test cases where equal OrderedDicts are compared.
  972. """
  973. test_dict = OrderedDict(
  974. [
  975. ("foo", "bar"),
  976. ("bar", OrderedDict([("baz", OrderedDict([("qux", "quux")]))])),
  977. ("frop", 0),
  978. ]
  979. )
  980. self.assertEqual({}, salt.utils.data.recursive_diff(test_dict, test_dict))
  981. def test_mixed_equality(self):
  982. """
  983. Test cases where mixed nested lists and dicts are compared.
  984. """
  985. test_data = {
  986. "foo": "bar",
  987. "baz": [0, 1, 2],
  988. "bar": {"baz": [{"qux": "quux"}, {"froop", 0}]},
  989. }
  990. self.assertEqual({}, salt.utils.data.recursive_diff(test_data, test_data))
  991. def test_set_equality(self):
  992. """
  993. Test cases where equal sets are compared.
  994. """
  995. test_set = set([0, 1, 2, 3, "foo"])
  996. self.assertEqual({}, salt.utils.data.recursive_diff(test_set, test_set))
  997. # This is a bit of an oddity, as python seems to sort the sets in memory
  998. # so both sets end up with the same ordering (0..3).
  999. set_one = set([0, 1, 2, 3])
  1000. set_two = set([3, 2, 1, 0])
  1001. self.assertEqual({}, salt.utils.data.recursive_diff(set_one, set_two))
  1002. def test_tuple_equality(self):
  1003. """
  1004. Test cases where equal tuples are compared.
  1005. """
  1006. test_tuple = (0, 1, 2, 3, "foo")
  1007. self.assertEqual({}, salt.utils.data.recursive_diff(test_tuple, test_tuple))
  1008. def test_list_inequality(self):
  1009. """
  1010. Test cases where two inequal lists are compared.
  1011. """
  1012. list_one = [0, 1, 2]
  1013. list_two = ["foo", "bar", "baz"]
  1014. expected_result = {"old": list_one, "new": list_two}
  1015. self.assertEqual(
  1016. expected_result, salt.utils.data.recursive_diff(list_one, list_two)
  1017. )
  1018. expected_result = {"new": list_one, "old": list_two}
  1019. self.assertEqual(
  1020. expected_result, salt.utils.data.recursive_diff(list_two, list_one)
  1021. )
  1022. list_one = [0, "foo", 1, "bar"]
  1023. list_two = [1, "foo", 1, "qux"]
  1024. expected_result = {"old": [0, "bar"], "new": [1, "qux"]}
  1025. self.assertEqual(
  1026. expected_result, salt.utils.data.recursive_diff(list_one, list_two)
  1027. )
  1028. expected_result = {"new": [0, "bar"], "old": [1, "qux"]}
  1029. self.assertEqual(
  1030. expected_result, salt.utils.data.recursive_diff(list_two, list_one)
  1031. )
  1032. list_one = [0, 1, [2, 3]]
  1033. list_two = [0, 1, ["foo", "bar"]]
  1034. expected_result = {"old": [[2, 3]], "new": [["foo", "bar"]]}
  1035. self.assertEqual(
  1036. expected_result, salt.utils.data.recursive_diff(list_one, list_two)
  1037. )
  1038. expected_result = {"new": [[2, 3]], "old": [["foo", "bar"]]}
  1039. self.assertEqual(
  1040. expected_result, salt.utils.data.recursive_diff(list_two, list_one)
  1041. )
  1042. def test_dict_inequality(self):
  1043. """
  1044. Test cases where two inequal dicts are compared.
  1045. """
  1046. dict_one = {"foo": 1, "bar": 2, "baz": 3}
  1047. dict_two = {"foo": 2, 1: "bar", "baz": 3}
  1048. expected_result = {"old": {"foo": 1, "bar": 2}, "new": {"foo": 2, 1: "bar"}}
  1049. self.assertEqual(
  1050. expected_result, salt.utils.data.recursive_diff(dict_one, dict_two)
  1051. )
  1052. expected_result = {"new": {"foo": 1, "bar": 2}, "old": {"foo": 2, 1: "bar"}}
  1053. self.assertEqual(
  1054. expected_result, salt.utils.data.recursive_diff(dict_two, dict_one)
  1055. )
  1056. dict_one = {"foo": {"bar": {"baz": 1}}}
  1057. dict_two = {"foo": {"qux": {"baz": 1}}}
  1058. expected_result = {"old": dict_one, "new": dict_two}
  1059. self.assertEqual(
  1060. expected_result, salt.utils.data.recursive_diff(dict_one, dict_two)
  1061. )
  1062. expected_result = {"new": dict_one, "old": dict_two}
  1063. self.assertEqual(
  1064. expected_result, salt.utils.data.recursive_diff(dict_two, dict_one)
  1065. )
  1066. def test_ordereddict_inequality(self):
  1067. """
  1068. Test cases where two inequal OrderedDicts are compared.
  1069. """
  1070. odict_one = OrderedDict([("foo", "bar"), ("bar", "baz")])
  1071. odict_two = OrderedDict([("bar", "baz"), ("foo", "bar")])
  1072. expected_result = {"old": odict_one, "new": odict_two}
  1073. self.assertEqual(
  1074. expected_result, salt.utils.data.recursive_diff(odict_one, odict_two)
  1075. )
  1076. def test_set_inequality(self):
  1077. """
  1078. Test cases where two inequal sets are compared.
  1079. Tricky as the sets are compared zipped, so shuffled sets of equal values
  1080. are considered different.
  1081. """
  1082. set_one = set([0, 1, 2, 4])
  1083. set_two = set([0, 1, 3, 4])
  1084. expected_result = {"old": set([2]), "new": set([3])}
  1085. self.assertEqual(
  1086. expected_result, salt.utils.data.recursive_diff(set_one, set_two)
  1087. )
  1088. expected_result = {"new": set([2]), "old": set([3])}
  1089. self.assertEqual(
  1090. expected_result, salt.utils.data.recursive_diff(set_two, set_one)
  1091. )
  1092. # It is unknown how different python versions will store sets in memory.
  1093. # Python 2.7 seems to sort it (i.e. set_one below becomes {0, 1, 'foo', 'bar'}
  1094. # However Python 3.6.8 stores it differently each run.
  1095. # So just test for "not equal" here.
  1096. set_one = set([0, "foo", 1, "bar"])
  1097. set_two = set(["foo", 1, "bar", 2])
  1098. expected_result = {}
  1099. self.assertNotEqual(
  1100. expected_result, salt.utils.data.recursive_diff(set_one, set_two)
  1101. )
  1102. def test_mixed_inequality(self):
  1103. """
  1104. Test cases where two mixed dicts/iterables that are different are compared.
  1105. """
  1106. dict_one = {"foo": [1, 2, 3]}
  1107. dict_two = {"foo": [3, 2, 1]}
  1108. expected_result = {"old": {"foo": [1, 3]}, "new": {"foo": [3, 1]}}
  1109. self.assertEqual(
  1110. expected_result, salt.utils.data.recursive_diff(dict_one, dict_two)
  1111. )
  1112. expected_result = {"new": {"foo": [1, 3]}, "old": {"foo": [3, 1]}}
  1113. self.assertEqual(
  1114. expected_result, salt.utils.data.recursive_diff(dict_two, dict_one)
  1115. )
  1116. list_one = [1, 2, {"foo": ["bar", {"foo": 1, "bar": 2}]}]
  1117. list_two = [3, 4, {"foo": ["qux", {"foo": 1, "bar": 2}]}]
  1118. expected_result = {
  1119. "old": [1, 2, {"foo": ["bar"]}],
  1120. "new": [3, 4, {"foo": ["qux"]}],
  1121. }
  1122. self.assertEqual(
  1123. expected_result, salt.utils.data.recursive_diff(list_one, list_two)
  1124. )
  1125. expected_result = {
  1126. "new": [1, 2, {"foo": ["bar"]}],
  1127. "old": [3, 4, {"foo": ["qux"]}],
  1128. }
  1129. self.assertEqual(
  1130. expected_result, salt.utils.data.recursive_diff(list_two, list_one)
  1131. )
  1132. mixed_one = {"foo": set([0, 1, 2]), "bar": [0, 1, 2]}
  1133. mixed_two = {"foo": set([1, 2, 3]), "bar": [1, 2, 3]}
  1134. expected_result = {
  1135. "old": {"foo": set([0]), "bar": [0, 1, 2]},
  1136. "new": {"foo": set([3]), "bar": [1, 2, 3]},
  1137. }
  1138. self.assertEqual(
  1139. expected_result, salt.utils.data.recursive_diff(mixed_one, mixed_two)
  1140. )
  1141. expected_result = {
  1142. "new": {"foo": set([0]), "bar": [0, 1, 2]},
  1143. "old": {"foo": set([3]), "bar": [1, 2, 3]},
  1144. }
  1145. self.assertEqual(
  1146. expected_result, salt.utils.data.recursive_diff(mixed_two, mixed_one)
  1147. )
  1148. def test_tuple_inequality(self):
  1149. """
  1150. Test cases where two tuples that are different are compared.
  1151. """
  1152. tuple_one = (1, 2, 3)
  1153. tuple_two = (3, 2, 1)
  1154. expected_result = {"old": (1, 3), "new": (3, 1)}
  1155. self.assertEqual(
  1156. expected_result, salt.utils.data.recursive_diff(tuple_one, tuple_two)
  1157. )
  1158. def test_list_vs_set(self):
  1159. """
  1160. Test case comparing a list with a set, will be compared unordered.
  1161. """
  1162. mixed_one = [1, 2, 3]
  1163. mixed_two = set([3, 2, 1])
  1164. expected_result = {}
  1165. self.assertEqual(
  1166. expected_result, salt.utils.data.recursive_diff(mixed_one, mixed_two)
  1167. )
  1168. self.assertEqual(
  1169. expected_result, salt.utils.data.recursive_diff(mixed_two, mixed_one)
  1170. )
  1171. def test_dict_vs_ordereddict(self):
  1172. """
  1173. Test case comparing a dict with an ordereddict, will be compared unordered.
  1174. """
  1175. test_dict = {"foo": "bar", "bar": "baz"}
  1176. test_odict = OrderedDict([("foo", "bar"), ("bar", "baz")])
  1177. self.assertEqual({}, salt.utils.data.recursive_diff(test_dict, test_odict))
  1178. self.assertEqual({}, salt.utils.data.recursive_diff(test_odict, test_dict))
  1179. test_odict2 = OrderedDict([("bar", "baz"), ("foo", "bar")])
  1180. self.assertEqual({}, salt.utils.data.recursive_diff(test_dict, test_odict2))
  1181. self.assertEqual({}, salt.utils.data.recursive_diff(test_odict2, test_dict))
  1182. def test_list_ignore_ignored(self):
  1183. """
  1184. Test case comparing two lists with ignore-list supplied (which is not used
  1185. when comparing lists).
  1186. """
  1187. list_one = [1, 2, 3]
  1188. list_two = [3, 2, 1]
  1189. expected_result = {"old": [1, 3], "new": [3, 1]}
  1190. self.assertEqual(
  1191. expected_result,
  1192. salt.utils.data.recursive_diff(list_one, list_two, ignore_keys=[1, 3]),
  1193. )
  1194. def test_dict_ignore(self):
  1195. """
  1196. Test case comparing two dicts with ignore-list supplied.
  1197. """
  1198. dict_one = {"foo": 1, "bar": 2, "baz": 3}
  1199. dict_two = {"foo": 3, "bar": 2, "baz": 1}
  1200. expected_result = {"old": {"baz": 3}, "new": {"baz": 1}}
  1201. self.assertEqual(
  1202. expected_result,
  1203. salt.utils.data.recursive_diff(dict_one, dict_two, ignore_keys=["foo"]),
  1204. )
  1205. def test_ordereddict_ignore(self):
  1206. """
  1207. Test case comparing two OrderedDicts with ignore-list supplied.
  1208. """
  1209. odict_one = OrderedDict([("foo", 1), ("bar", 2), ("baz", 3)])
  1210. odict_two = OrderedDict([("baz", 1), ("bar", 2), ("foo", 3)])
  1211. # The key 'foo' will be ignored, which means the key from the other OrderedDict
  1212. # will always be considered "different" since OrderedDicts are compared ordered.
  1213. expected_result = {
  1214. "old": OrderedDict([("baz", 3)]),
  1215. "new": OrderedDict([("baz", 1)]),
  1216. }
  1217. self.assertEqual(
  1218. expected_result,
  1219. salt.utils.data.recursive_diff(odict_one, odict_two, ignore_keys=["foo"]),
  1220. )
  1221. def test_dict_vs_ordereddict_ignore(self):
  1222. """
  1223. Test case comparing a dict with an OrderedDict with ignore-list supplied.
  1224. """
  1225. dict_one = {"foo": 1, "bar": 2, "baz": 3}
  1226. odict_two = OrderedDict([("foo", 3), ("bar", 2), ("baz", 1)])
  1227. expected_result = {"old": {"baz": 3}, "new": OrderedDict([("baz", 1)])}
  1228. self.assertEqual(
  1229. expected_result,
  1230. salt.utils.data.recursive_diff(dict_one, odict_two, ignore_keys=["foo"]),
  1231. )
  1232. def test_mixed_nested_ignore(self):
  1233. """
  1234. Test case comparing mixed, nested items with ignore-list supplied.
  1235. """
  1236. dict_one = {"foo": [1], "bar": {"foo": 1, "bar": 2}, "baz": 3}
  1237. dict_two = {"foo": [2], "bar": {"foo": 3, "bar": 2}, "baz": 1}
  1238. expected_result = {"old": {"baz": 3}, "new": {"baz": 1}}
  1239. self.assertEqual(
  1240. expected_result,
  1241. salt.utils.data.recursive_diff(dict_one, dict_two, ignore_keys=["foo"]),
  1242. )
  1243. def test_ordered_dict_unequal_length(self):
  1244. """
  1245. Test case comparing two OrderedDicts of unequal length.
  1246. """
  1247. odict_one = OrderedDict([("foo", 1), ("bar", 2), ("baz", 3)])
  1248. odict_two = OrderedDict([("foo", 1), ("bar", 2)])
  1249. expected_result = {"old": OrderedDict([("baz", 3)]), "new": {}}
  1250. self.assertEqual(
  1251. expected_result, salt.utils.data.recursive_diff(odict_one, odict_two)
  1252. )
  1253. def test_list_unequal_length(self):
  1254. """
  1255. Test case comparing two lists of unequal length.
  1256. """
  1257. list_one = [1, 2, 3]
  1258. list_two = [1, 2, 3, 4]
  1259. expected_result = {"old": [], "new": [4]}
  1260. self.assertEqual(
  1261. expected_result, salt.utils.data.recursive_diff(list_one, list_two)
  1262. )
  1263. def test_set_unequal_length(self):
  1264. """
  1265. Test case comparing two sets of unequal length.
  1266. This does not do anything special, as it is unordered.
  1267. """
  1268. set_one = set([1, 2, 3])
  1269. set_two = set([4, 3, 2, 1])
  1270. expected_result = {"old": set([]), "new": set([4])}
  1271. self.assertEqual(
  1272. expected_result, salt.utils.data.recursive_diff(set_one, set_two)
  1273. )
  1274. def test_tuple_unequal_length(self):
  1275. """
  1276. Test case comparing two tuples of unequal length.
  1277. This should be the same as comparing two ordered lists.
  1278. """
  1279. tuple_one = (1, 2, 3)
  1280. tuple_two = (1, 2, 3, 4)
  1281. expected_result = {"old": (), "new": (4,)}
  1282. self.assertEqual(
  1283. expected_result, salt.utils.data.recursive_diff(tuple_one, tuple_two)
  1284. )
  1285. def test_list_unordered(self):
  1286. """
  1287. Test case comparing two lists unordered.
  1288. """
  1289. list_one = [1, 2, 3, 4]
  1290. list_two = [4, 3, 2]
  1291. expected_result = {"old": [1], "new": []}
  1292. self.assertEqual(
  1293. expected_result,
  1294. salt.utils.data.recursive_diff(list_one, list_two, ignore_order=True),
  1295. )
  1296. def test_mixed_nested_unordered(self):
  1297. """
  1298. Test case comparing nested dicts/lists unordered.
  1299. """
  1300. dict_one = {"foo": {"bar": [1, 2, 3]}, "bar": [{"foo": 4}, 0]}
  1301. dict_two = {"foo": {"bar": [3, 2, 1]}, "bar": [0, {"foo": 4}]}
  1302. expected_result = {}
  1303. self.assertEqual(
  1304. expected_result,
  1305. salt.utils.data.recursive_diff(dict_one, dict_two, ignore_order=True),
  1306. )
  1307. expected_result = {
  1308. "old": {"foo": {"bar": [1, 3]}, "bar": [{"foo": 4}, 0]},
  1309. "new": {"foo": {"bar": [3, 1]}, "bar": [0, {"foo": 4}]},
  1310. }
  1311. self.assertEqual(
  1312. expected_result, salt.utils.data.recursive_diff(dict_one, dict_two)
  1313. )
  1314. def test_ordered_dict_unordered(self):
  1315. """
  1316. Test case comparing OrderedDicts unordered.
  1317. """
  1318. odict_one = OrderedDict([("foo", 1), ("bar", 2), ("baz", 3)])
  1319. odict_two = OrderedDict([("baz", 3), ("bar", 2), ("foo", 1)])
  1320. expected_result = {}
  1321. self.assertEqual(
  1322. expected_result,
  1323. salt.utils.data.recursive_diff(odict_one, odict_two, ignore_order=True),
  1324. )
  1325. def test_ignore_missing_keys_dict(self):
  1326. """
  1327. Test case ignoring missing keys on a comparison of dicts.
  1328. """
  1329. dict_one = {"foo": 1, "bar": 2, "baz": 3}
  1330. dict_two = {"bar": 3}
  1331. expected_result = {"old": {"bar": 2}, "new": {"bar": 3}}
  1332. self.assertEqual(
  1333. expected_result,
  1334. salt.utils.data.recursive_diff(
  1335. dict_one, dict_two, ignore_missing_keys=True
  1336. ),
  1337. )
  1338. def test_ignore_missing_keys_ordered_dict(self):
  1339. """
  1340. Test case not ignoring missing keys on a comparison of OrderedDicts.
  1341. """
  1342. odict_one = OrderedDict([("foo", 1), ("bar", 2), ("baz", 3)])
  1343. odict_two = OrderedDict([("bar", 3)])
  1344. expected_result = {"old": odict_one, "new": odict_two}
  1345. self.assertEqual(
  1346. expected_result,
  1347. salt.utils.data.recursive_diff(
  1348. odict_one, odict_two, ignore_missing_keys=True
  1349. ),
  1350. )
  1351. def test_ignore_missing_keys_recursive(self):
  1352. """
  1353. Test case ignoring missing keys on a comparison of nested dicts.
  1354. """
  1355. dict_one = {"foo": {"bar": 2, "baz": 3}}
  1356. dict_two = {"foo": {"baz": 3}}
  1357. expected_result = {}
  1358. self.assertEqual(
  1359. expected_result,
  1360. salt.utils.data.recursive_diff(
  1361. dict_one, dict_two, ignore_missing_keys=True
  1362. ),
  1363. )
  1364. # Compare from dict-in-dict
  1365. dict_two = {}
  1366. self.assertEqual(
  1367. expected_result,
  1368. salt.utils.data.recursive_diff(
  1369. dict_one, dict_two, ignore_missing_keys=True
  1370. ),
  1371. )
  1372. # Compare from dict-in-list
  1373. dict_one = {"foo": ["bar", {"baz": 3}]}
  1374. dict_two = {"foo": ["bar", {}]}
  1375. self.assertEqual(
  1376. expected_result,
  1377. salt.utils.data.recursive_diff(
  1378. dict_one, dict_two, ignore_missing_keys=True
  1379. ),
  1380. )