1
0

test_localfs.py 12 KB

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