test_localfs.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. # -*- coding: utf-8 -*-
  2. '''
  3. unit tests for the localfs cache
  4. '''
  5. # Import Python libs
  6. from __future__ import absolute_import, print_function, unicode_literals
  7. import errno
  8. import shutil
  9. import tempfile
  10. # Import Salt Testing libs
  11. from tests.support.runtests import RUNTIME_VARS
  12. from tests.support.mixins import LoaderModuleMockMixin
  13. from tests.support.unit import TestCase
  14. from tests.support.mock import (
  15. MagicMock,
  16. patch
  17. )
  18. # Import Salt libs
  19. import salt.payload
  20. import salt.utils.files
  21. import salt.cache.localfs as localfs
  22. from salt.exceptions import SaltCacheError
  23. class LocalFSTest(TestCase, LoaderModuleMockMixin):
  24. '''
  25. Validate the functions in the localfs cache
  26. '''
  27. def setup_loader_modules(self):
  28. return {localfs: {}}
  29. def _create_tmp_cache_file(self, tmp_dir, serializer):
  30. '''
  31. Helper function that creates a temporary cache file using localfs.store. This
  32. is to used to create DRY unit tests for the localfs cache.
  33. '''
  34. self.addCleanup(shutil.rmtree, tmp_dir)
  35. with patch.dict(localfs.__opts__, {'cachedir': tmp_dir}):
  36. with patch.dict(localfs.__context__, {'serial': serializer}):
  37. localfs.store(bank='bank', key='key', data='payload data', cachedir=tmp_dir)
  38. # 'store' function tests: 5
  39. def test_handled_exception_cache_dir(self):
  40. '''
  41. Tests that a SaltCacheError is raised when the base directory doesn't exist and
  42. cannot be created.
  43. '''
  44. with patch('os.makedirs', MagicMock(side_effect=OSError(errno.EEXIST, ''))):
  45. with patch('tempfile.mkstemp', MagicMock(side_effect=Exception)):
  46. self.assertRaises(Exception, localfs.store, bank='', key='', data='', cachedir='')
  47. def test_unhandled_exception_cache_dir(self):
  48. '''
  49. Tests that a SaltCacheError is raised when the base directory doesn't exist and
  50. cannot be created.
  51. '''
  52. with patch('os.makedirs', MagicMock(side_effect=OSError(1, ''))):
  53. self.assertRaises(SaltCacheError, localfs.store, bank='', key='', data='', cachedir='')
  54. def test_store_close_mkstemp_file_handle(self):
  55. '''
  56. Tests that the file descriptor that is opened by os.open during the mkstemp call
  57. in localfs.store is closed before calling salt.utils.files.fopen on the filename.
  58. This test mocks the call to mkstemp, but forces an OSError to be raised when the
  59. close() function is called on a file descriptor that doesn't exist.
  60. '''
  61. with patch('os.makedirs', MagicMock(side_effect=OSError(errno.EEXIST, ''))):
  62. with patch('tempfile.mkstemp', MagicMock(return_value=(12345, 'foo'))):
  63. self.assertRaises(OSError, localfs.store, bank='', key='', data='', cachedir='')
  64. def test_store_error_writing_cache(self):
  65. '''
  66. Tests that a SaltCacheError is raised when there is a problem writing to the
  67. cache file.
  68. '''
  69. with patch('os.makedirs', MagicMock(side_effect=OSError(errno.EEXIST, ''))):
  70. with patch('tempfile.mkstemp', MagicMock(return_value=('one', 'two'))):
  71. with patch('os.close', MagicMock(return_value=None)):
  72. with patch('salt.utils.files.fopen', MagicMock(side_effect=IOError)):
  73. self.assertRaises(SaltCacheError, localfs.store, bank='', key='', data='', cachedir='')
  74. def test_store_success(self):
  75. '''
  76. Tests that the store function writes the data to the serializer for storage.
  77. '''
  78. # Create a temporary cache dir
  79. tmp_dir = tempfile.mkdtemp(dir=RUNTIME_VARS.TMP)
  80. # Use the helper function to create the cache file using localfs.store()
  81. self._create_tmp_cache_file(tmp_dir, salt.payload.Serial(self))
  82. # Read in the contents of the key.p file and assert "payload data" was written
  83. with salt.utils.files.fopen(tmp_dir + '/bank/key.p', 'rb') as fh_:
  84. for line in fh_:
  85. self.assertIn(b'payload data', line)
  86. # 'fetch' function tests: 3
  87. def test_fetch_return_when_cache_file_does_not_exist(self):
  88. '''
  89. Tests that the fetch function returns an empty dic when the cache key file
  90. doesn't exist.
  91. '''
  92. with patch('os.path.isfile', MagicMock(return_value=False)):
  93. self.assertEqual(localfs.fetch(bank='', key='', cachedir=''), {})
  94. def test_fetch_error_reading_cache(self):
  95. '''
  96. Tests that a SaltCacheError is raised when there is a problem reading the cache
  97. file.
  98. '''
  99. with patch('os.path.isfile', MagicMock(return_value=True)):
  100. with patch('salt.utils.files.fopen', MagicMock(side_effect=IOError)):
  101. self.assertRaises(SaltCacheError, localfs.fetch, bank='', key='', cachedir='')
  102. def test_fetch_success(self):
  103. '''
  104. Tests that the fetch function is able to read the cache file and return its data.
  105. '''
  106. # Create a temporary cache dir
  107. tmp_dir = tempfile.mkdtemp(dir=RUNTIME_VARS.TMP)
  108. # Create a new serializer object to use in function patches
  109. serializer = salt.payload.Serial(self)
  110. # Use the helper function to create the cache file using localfs.store()
  111. self._create_tmp_cache_file(tmp_dir, serializer)
  112. # Now fetch the data from the new cache key file
  113. with patch.dict(localfs.__opts__, {'cachedir': tmp_dir}):
  114. with patch.dict(localfs.__context__, {'serial': serializer}):
  115. self.assertIn('payload data', localfs.fetch(bank='bank', key='key', cachedir=tmp_dir))
  116. # 'updated' function tests: 3
  117. def test_updated_return_when_cache_file_does_not_exist(self):
  118. '''
  119. Tests that the updated function returns None when the cache key file doesn't
  120. exist.
  121. '''
  122. with patch('os.path.isfile', MagicMock(return_value=False)):
  123. self.assertIsNone(localfs.updated(bank='', key='', cachedir=''))
  124. def test_updated_error_when_reading_mtime(self):
  125. '''
  126. Tests that a SaltCacheError is raised when there is a problem reading the mtime
  127. of the cache file.
  128. '''
  129. with patch('os.path.isfile', MagicMock(return_value=True)):
  130. with patch('os.path.getmtime', MagicMock(side_effect=IOError)):
  131. self.assertRaises(SaltCacheError, localfs.updated, bank='', key='', cachedir='')
  132. def test_updated_success(self):
  133. '''
  134. Test that the updated function returns the modification time of the cache file
  135. '''
  136. # Create a temporary cache dir
  137. tmp_dir = tempfile.mkdtemp(dir=RUNTIME_VARS.TMP)
  138. # Use the helper function to create the cache file using localfs.store()
  139. self._create_tmp_cache_file(tmp_dir, salt.payload.Serial(self))
  140. with patch('os.path.join', MagicMock(return_value=tmp_dir + '/bank/key.p')):
  141. self.assertIsInstance(localfs.updated(bank='bank', key='key', cachedir=tmp_dir), int)
  142. # 'flush' function tests: 4
  143. def test_flush_key_is_none_and_no_target_dir(self):
  144. '''
  145. Tests that the flush function returns False when no key is passed in and the
  146. target directory doesn't exist.
  147. '''
  148. with patch('os.path.isdir', MagicMock(return_value=False)):
  149. self.assertFalse(localfs.flush(bank='', key=None, cachedir=''))
  150. def test_flush_key_provided_and_no_key_file_false(self):
  151. '''
  152. Tests that the flush function returns False when a key file is provided but
  153. the target key file doesn't exist in the cache bank.
  154. '''
  155. with patch('os.path.isfile', MagicMock(return_value=False)):
  156. self.assertFalse(localfs.flush(bank='', key='key', cachedir=''))
  157. def test_flush_success(self):
  158. '''
  159. Tests that the flush function returns True when a key file is provided and
  160. the target key exists in the cache bank.
  161. '''
  162. with patch('os.path.isfile', MagicMock(return_value=True)):
  163. # Create a temporary cache dir
  164. tmp_dir = tempfile.mkdtemp(dir=RUNTIME_VARS.TMP)
  165. # Use the helper function to create the cache file using localfs.store()
  166. self._create_tmp_cache_file(tmp_dir, salt.payload.Serial(self))
  167. # Now test the return of the flush function
  168. with patch.dict(localfs.__opts__, {'cachedir': tmp_dir}):
  169. self.assertTrue(localfs.flush(bank='bank', key='key', cachedir=tmp_dir))
  170. def test_flush_error_raised(self):
  171. '''
  172. Tests that a SaltCacheError is raised when there is a problem removing the
  173. key file from the cache bank
  174. '''
  175. with patch('os.path.isfile', MagicMock(return_value=True)):
  176. with patch('os.remove', MagicMock(side_effect=OSError)):
  177. self.assertRaises(SaltCacheError, localfs.flush, bank='', key='key', cachedir='/var/cache/salt')
  178. # 'list' function tests: 3
  179. def test_list_no_base_dir(self):
  180. '''
  181. Tests that the ls function returns an empty list if the bank directory
  182. doesn't exist.
  183. '''
  184. with patch('os.path.isdir', MagicMock(return_value=False)):
  185. self.assertEqual(localfs.list_(bank='', cachedir=''), [])
  186. def test_list_error_raised_no_bank_directory_access(self):
  187. '''
  188. Tests that a SaltCacheError is raised when there is a problem accessing the
  189. cache bank directory.
  190. '''
  191. with patch('os.path.isdir', MagicMock(return_value=True)):
  192. with patch('os.listdir', MagicMock(side_effect=OSError)):
  193. self.assertRaises(SaltCacheError, localfs.list_, bank='', cachedir='')
  194. def test_list_success(self):
  195. '''
  196. Tests the return of the ls function containing bank entries.
  197. '''
  198. # Create a temporary cache dir
  199. tmp_dir = tempfile.mkdtemp(dir=RUNTIME_VARS.TMP)
  200. # Use the helper function to create the cache file using localfs.store()
  201. self._create_tmp_cache_file(tmp_dir, salt.payload.Serial(self))
  202. # Now test the return of the ls function
  203. with patch.dict(localfs.__opts__, {'cachedir': tmp_dir}):
  204. self.assertEqual(localfs.list_(bank='bank', cachedir=tmp_dir), ['key'])
  205. # 'contains' function tests: 1
  206. def test_contains(self):
  207. '''
  208. Test the return of the contains function when key=None and when a key
  209. is provided.
  210. '''
  211. # Create a temporary cache dir
  212. tmp_dir = tempfile.mkdtemp(dir=RUNTIME_VARS.TMP)
  213. # Use the helper function to create the cache file using localfs.store()
  214. self._create_tmp_cache_file(tmp_dir, salt.payload.Serial(self))
  215. # Now test the return of the contains function when key=None
  216. with patch.dict(localfs.__opts__, {'cachedir': tmp_dir}):
  217. self.assertTrue(localfs.contains(bank='bank', key=None, cachedir=tmp_dir))
  218. # Now test the return of the contains function when key='key'
  219. with patch.dict(localfs.__opts__, {'cachedir': tmp_dir}):
  220. self.assertTrue(localfs.contains(bank='bank', key='key', cachedir=tmp_dir))