test_etcd_util.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  1. # -*- coding: utf-8 -*-
  2. """
  3. :codeauthor: Jayesh Kariya <jayeshk@saltstack.com>
  4. """
  5. # Import Python Libs
  6. from __future__ import absolute_import, print_function, unicode_literals
  7. # Import Salt Libs
  8. import salt.utils.etcd_util as etcd_util
  9. from tests.support.mock import MagicMock, patch
  10. # Import Salt Testing Libs
  11. from tests.support.unit import TestCase, skipIf
  12. try:
  13. from urllib3.exceptions import ReadTimeoutError, MaxRetryError
  14. HAS_URLLIB3 = True
  15. except ImportError:
  16. HAS_URLLIB3 = False
  17. try:
  18. import etcd
  19. HAS_ETCD = True
  20. except ImportError:
  21. HAS_ETCD = False
  22. @skipIf(HAS_URLLIB3 is False, "urllib3 module must be installed.")
  23. @skipIf(HAS_ETCD is False, "python-etcd module must be installed.")
  24. class EtcdUtilTestCase(TestCase):
  25. """
  26. Test cases for salt.utils.etcd_util
  27. """
  28. # 'get_' function tests: 1
  29. def test_read(self):
  30. """
  31. Test to make sure we interact with etcd correctly
  32. """
  33. with patch("etcd.Client", autospec=True) as mock:
  34. etcd_client = mock.return_value
  35. etcd_return = MagicMock(value="salt")
  36. etcd_client.read.return_value = etcd_return
  37. client = etcd_util.EtcdClient({})
  38. self.assertEqual(client.read("/salt"), etcd_return)
  39. etcd_client.read.assert_called_with(
  40. "/salt", recursive=False, wait=False, timeout=None
  41. )
  42. client.read("salt", True, True, 10, 5)
  43. etcd_client.read.assert_called_with(
  44. "salt", recursive=True, wait=True, timeout=10, waitIndex=5
  45. )
  46. etcd_client.read.side_effect = etcd.EtcdKeyNotFound
  47. self.assertRaises(etcd.EtcdKeyNotFound, client.read, "salt")
  48. etcd_client.read.side_effect = etcd.EtcdConnectionFailed
  49. self.assertRaises(etcd.EtcdConnectionFailed, client.read, "salt")
  50. etcd_client.read.side_effect = etcd.EtcdValueError
  51. self.assertRaises(etcd.EtcdValueError, client.read, "salt")
  52. etcd_client.read.side_effect = ValueError
  53. self.assertRaises(ValueError, client.read, "salt")
  54. etcd_client.read.side_effect = ReadTimeoutError(None, None, None)
  55. self.assertRaises(etcd.EtcdConnectionFailed, client.read, "salt")
  56. etcd_client.read.side_effect = MaxRetryError(None, None)
  57. self.assertRaises(etcd.EtcdConnectionFailed, client.read, "salt")
  58. def test_get(self):
  59. """
  60. Test if it get a value from etcd, by direct path
  61. """
  62. with patch("etcd.Client") as mock:
  63. client = etcd_util.EtcdClient({})
  64. with patch.object(client, "read", autospec=True) as mock:
  65. mock.return_value = MagicMock(value="stack")
  66. self.assertEqual(client.get("salt"), "stack")
  67. mock.assert_called_with("salt", recursive=False)
  68. self.assertEqual(client.get("salt", recurse=True), "stack")
  69. mock.assert_called_with("salt", recursive=True)
  70. # iter(list(Exception)) works correctly with both mock<1.1 and mock>=1.1
  71. mock.side_effect = iter([etcd.EtcdKeyNotFound()])
  72. self.assertEqual(client.get("not-found"), None)
  73. mock.side_effect = iter([etcd.EtcdConnectionFailed()])
  74. self.assertEqual(client.get("watching"), None)
  75. # python 2.6 test
  76. mock.side_effect = ValueError
  77. self.assertEqual(client.get("not-found"), None)
  78. mock.side_effect = Exception
  79. self.assertRaises(Exception, client.get, "some-error")
  80. def test_tree(self):
  81. """
  82. Test recursive gets
  83. """
  84. with patch("etcd.Client") as mock:
  85. client = etcd_util.EtcdClient({})
  86. with patch.object(client, "read", autospec=True) as mock:
  87. c1, c2 = MagicMock(), MagicMock()
  88. c1.__iter__.return_value = [
  89. MagicMock(key="/x/a", value="1"),
  90. MagicMock(key="/x/b", value="2"),
  91. MagicMock(key="/x/c", dir=True),
  92. ]
  93. c2.__iter__.return_value = [MagicMock(key="/x/c/d", value="3")]
  94. mock.side_effect = iter(
  95. [MagicMock(children=c1), MagicMock(children=c2)]
  96. )
  97. self.assertDictEqual(
  98. client.tree("/x"), {"a": "1", "b": "2", "c": {"d": "3"}}
  99. )
  100. mock.assert_any_call("/x")
  101. mock.assert_any_call("/x/c")
  102. # iter(list(Exception)) works correctly with both mock<1.1 and mock>=1.1
  103. mock.side_effect = iter([etcd.EtcdKeyNotFound()])
  104. self.assertEqual(client.tree("not-found"), None)
  105. mock.side_effect = ValueError
  106. self.assertEqual(client.tree("/x"), None)
  107. mock.side_effect = Exception
  108. self.assertRaises(Exception, client.tree, "some-error")
  109. def test_ls(self):
  110. with patch("etcd.Client") as mock:
  111. client = etcd_util.EtcdClient({})
  112. with patch.object(client, "read", autospec=True) as mock:
  113. c1 = MagicMock()
  114. c1.__iter__.return_value = [
  115. MagicMock(key="/x/a", value="1"),
  116. MagicMock(key="/x/b", value="2"),
  117. MagicMock(key="/x/c", dir=True),
  118. ]
  119. mock.return_value = MagicMock(children=c1)
  120. self.assertEqual(
  121. client.ls("/x"), {"/x": {"/x/a": "1", "/x/b": "2", "/x/c/": {}}}
  122. )
  123. mock.assert_called_with("/x")
  124. # iter(list(Exception)) works correctly with both mock<1.1 and mock>=1.1
  125. mock.side_effect = iter([etcd.EtcdKeyNotFound()])
  126. self.assertEqual(client.ls("/not-found"), {})
  127. mock.side_effect = Exception
  128. self.assertRaises(Exception, client.tree, "some-error")
  129. def test_write(self):
  130. with patch("etcd.Client", autospec=True) as mock:
  131. client = etcd_util.EtcdClient({})
  132. etcd_client = mock.return_value
  133. etcd_client.write.return_value = MagicMock(value="salt")
  134. self.assertEqual(client.write("/some-key", "salt"), "salt")
  135. etcd_client.write.assert_called_with(
  136. "/some-key", "salt", ttl=None, dir=False
  137. )
  138. self.assertEqual(client.write("/some-key", "salt", ttl=5), "salt")
  139. etcd_client.write.assert_called_with("/some-key", "salt", ttl=5, dir=False)
  140. etcd_client.write.return_value = MagicMock(dir=True)
  141. self.assertEqual(
  142. client.write("/some-dir", "salt", ttl=0, directory=True), True
  143. )
  144. etcd_client.write.assert_called_with("/some-dir", None, ttl=0, dir=True)
  145. # Check when a file is attempted to be written to a read-only root
  146. etcd_client.write.side_effect = etcd.EtcdRootReadOnly()
  147. self.assertEqual(client.write("/", "some-val", directory=False), None)
  148. # Check when a directory is attempted to be written to a read-only root
  149. etcd_client.write.side_effect = etcd.EtcdRootReadOnly()
  150. self.assertEqual(client.write("/", None, directory=True), None)
  151. # Check when a file is attempted to be written when unable to connect to the service
  152. etcd_client.write.side_effect = MaxRetryError(None, None)
  153. self.assertEqual(
  154. client.write("/some-key", "some-val", directory=False), None
  155. )
  156. # Check when a directory is attempted to be written when unable to connect to the service
  157. etcd_client.write.side_effect = MaxRetryError(None, None)
  158. self.assertEqual(client.write("/some-dir", None, directory=True), None)
  159. # Check when a file is attempted to be written to a directory that already exists (name-collision)
  160. etcd_client.write.side_effect = etcd.EtcdNotFile()
  161. self.assertEqual(
  162. client.write("/some-dir", "some-val", directory=False), None
  163. )
  164. # Check when a directory is attempted to be written to a file that already exists (name-collision)
  165. etcd_client.write.side_effect = etcd.EtcdNotDir()
  166. self.assertEqual(client.write("/some-key", None, directory=True), None)
  167. # Check when a directory is attempted to be written to a directory that already exists (update-ttl)
  168. etcd_client.write.side_effect = etcd.EtcdNotFile()
  169. self.assertEqual(client.write("/some-dir", None, directory=True), True)
  170. etcd_client.write.side_effect = ValueError
  171. self.assertEqual(client.write("/some-key", "some-val"), None)
  172. etcd_client.write.side_effect = Exception
  173. self.assertRaises(Exception, client.set, "some-key", "some-val")
  174. def test_flatten(self):
  175. with patch("etcd.Client", autospec=True) as mock:
  176. client = etcd_util.EtcdClient({})
  177. some_data = {
  178. "/x/y/a": "1",
  179. "x": {"y": {"b": "2"}},
  180. "m/j/": "3",
  181. "z": "4",
  182. "d": {},
  183. }
  184. result_path = {
  185. "/test/x/y/a": "1",
  186. "/test/x/y/b": "2",
  187. "/test/m/j": "3",
  188. "/test/z": "4",
  189. "/test/d": {},
  190. }
  191. result_nopath = {
  192. "/x/y/a": "1",
  193. "/x/y/b": "2",
  194. "/m/j": "3",
  195. "/z": "4",
  196. "/d": {},
  197. }
  198. result_root = {
  199. "/x/y/a": "1",
  200. "/x/y/b": "2",
  201. "/m/j": "3",
  202. "/z": "4",
  203. "/d": {},
  204. }
  205. self.assertEqual(client._flatten(some_data, path="/test"), result_path)
  206. self.assertEqual(client._flatten(some_data, path="/"), result_root)
  207. self.assertEqual(client._flatten(some_data), result_nopath)
  208. def test_update(self):
  209. with patch("etcd.Client", autospec=True) as mock:
  210. client = etcd_util.EtcdClient({})
  211. some_data = {
  212. "/x/y/a": "1",
  213. "x": {"y": {"b": "3"}},
  214. "m/j/": "3",
  215. "z": "4",
  216. "d": {},
  217. }
  218. result = {
  219. "/test/x/y/a": "1",
  220. "/test/x/y/b": "2",
  221. "/test/m/j": "3",
  222. "/test/z": "4",
  223. "/test/d": True,
  224. }
  225. flatten_result = {
  226. "/test/x/y/a": "1",
  227. "/test/x/y/b": "2",
  228. "/test/m/j": "3",
  229. "/test/z": "4",
  230. "/test/d": {},
  231. }
  232. client._flatten = MagicMock(return_value=flatten_result)
  233. self.assertEqual(client.update("/some/key", path="/blah"), None)
  234. with patch.object(client, "write", autospec=True) as write_mock:
  235. def write_return(key, val, ttl=None, directory=None):
  236. return result.get(key, None)
  237. write_mock.side_effect = write_return
  238. self.assertDictEqual(client.update(some_data, path="/test"), result)
  239. client._flatten.assert_called_with(some_data, "/test")
  240. self.assertEqual(write_mock.call_count, 5)
  241. def test_rm(self):
  242. with patch("etcd.Client", autospec=True) as mock:
  243. etcd_client = mock.return_value
  244. client = etcd_util.EtcdClient({})
  245. etcd_client.delete.return_value = True
  246. self.assertEqual(client.rm("/some-key"), True)
  247. etcd_client.delete.assert_called_with("/some-key", recursive=False)
  248. self.assertEqual(client.rm("/some-dir", recurse=True), True)
  249. etcd_client.delete.assert_called_with("/some-dir", recursive=True)
  250. etcd_client.delete.side_effect = etcd.EtcdNotFile()
  251. self.assertEqual(client.rm("/some-dir"), None)
  252. etcd_client.delete.side_effect = etcd.EtcdDirNotEmpty()
  253. self.assertEqual(client.rm("/some-key"), None)
  254. etcd_client.delete.side_effect = etcd.EtcdRootReadOnly()
  255. self.assertEqual(client.rm("/"), None)
  256. etcd_client.delete.side_effect = ValueError
  257. self.assertEqual(client.rm("/some-dir"), None)
  258. etcd_client.delete.side_effect = Exception
  259. self.assertRaises(Exception, client.rm, "some-dir")
  260. def test_watch(self):
  261. with patch("etcd.Client", autospec=True) as client_mock:
  262. client = etcd_util.EtcdClient({})
  263. with patch.object(client, "read", autospec=True) as mock:
  264. mock.return_value = MagicMock(
  265. value="stack", key="/some-key", modifiedIndex=1, dir=False
  266. )
  267. self.assertDictEqual(
  268. client.watch("/some-key"),
  269. {
  270. "value": "stack",
  271. "key": "/some-key",
  272. "mIndex": 1,
  273. "changed": True,
  274. "dir": False,
  275. },
  276. )
  277. mock.assert_called_with(
  278. "/some-key", wait=True, recursive=False, timeout=0, waitIndex=None
  279. )
  280. mock.side_effect = iter(
  281. [etcd_util.EtcdUtilWatchTimeout, mock.return_value]
  282. )
  283. self.assertDictEqual(
  284. client.watch("/some-key"),
  285. {
  286. "value": "stack",
  287. "changed": False,
  288. "mIndex": 1,
  289. "key": "/some-key",
  290. "dir": False,
  291. },
  292. )
  293. mock.side_effect = iter(
  294. [etcd_util.EtcdUtilWatchTimeout, etcd.EtcdKeyNotFound]
  295. )
  296. self.assertEqual(
  297. client.watch("/some-key"),
  298. {
  299. "value": None,
  300. "changed": False,
  301. "mIndex": 0,
  302. "key": "/some-key",
  303. "dir": False,
  304. },
  305. )
  306. mock.side_effect = iter([etcd_util.EtcdUtilWatchTimeout, ValueError])
  307. self.assertEqual(client.watch("/some-key"), {})
  308. mock.side_effect = None
  309. mock.return_value = MagicMock(
  310. value="stack", key="/some-key", modifiedIndex=1, dir=True
  311. )
  312. self.assertDictEqual(
  313. client.watch("/some-dir", recurse=True, timeout=5, index=10),
  314. {
  315. "value": "stack",
  316. "key": "/some-key",
  317. "mIndex": 1,
  318. "changed": True,
  319. "dir": True,
  320. },
  321. )
  322. mock.assert_called_with(
  323. "/some-dir", wait=True, recursive=True, timeout=5, waitIndex=10
  324. )
  325. # iter(list(Exception)) works correctly with both mock<1.1 and mock>=1.1
  326. mock.side_effect = iter([MaxRetryError(None, None)])
  327. self.assertEqual(client.watch("/some-key"), {})
  328. mock.side_effect = iter([etcd.EtcdConnectionFailed()])
  329. self.assertEqual(client.watch("/some-key"), {})
  330. mock.side_effect = None
  331. mock.return_value = None
  332. self.assertEqual(client.watch("/some-key"), {})