1
0

test_etcd_util.py 15 KB

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