test_etcd_util.py 13 KB

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