test_localfs.py 11 KB

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