test_azureblob.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. # -*- coding: utf-8 -*-
  2. """
  3. Tests for the Azure Blob External Pillar.
  4. """
  5. # Import python libs
  6. from __future__ import absolute_import, print_function, unicode_literals
  7. import os
  8. import pickle
  9. import tempfile
  10. import time
  11. import salt.config
  12. import salt.loader
  13. # Import Salt Libs
  14. import salt.pillar.azureblob as azureblob
  15. import salt.utils.files
  16. from tests.support.mixins import LoaderModuleMockMixin
  17. from tests.support.mock import MagicMock, patch
  18. # Import Salt Testing libs
  19. from tests.support.unit import TestCase, skipIf
  20. # Import Azure libs
  21. HAS_LIBS = False
  22. try:
  23. # pylint: disable=no-name-in-module
  24. from azure.storage.blob import BlobServiceClient
  25. # pylint: enable=no-name-in-module
  26. HAS_LIBS = True
  27. except ImportError:
  28. pass
  29. class MockBlob(dict):
  30. """
  31. Creates a Mock Blob object.
  32. """
  33. name = ""
  34. def __init__(self):
  35. super(MockBlob, self).__init__(
  36. {
  37. "container": None,
  38. "name": "test.sls",
  39. "prefix": None,
  40. "delimiter": "/",
  41. "results_per_page": None,
  42. "location_mode": None,
  43. }
  44. )
  45. class MockContainerClient(object):
  46. """
  47. Creates a Mock ContainerClient.
  48. """
  49. def __init__(self):
  50. pass
  51. def walk_blobs(self, *args, **kwargs):
  52. yield MockBlob()
  53. def get_blob_client(self, *args, **kwargs):
  54. pass
  55. class MockBlobServiceClient(object):
  56. """
  57. Creates a Mock BlobServiceClient.
  58. """
  59. def __init__(self):
  60. pass
  61. def get_container_client(self, *args, **kwargs):
  62. container_client = MockContainerClient()
  63. return container_client
  64. @skipIf(HAS_LIBS is False, "The azure.storage.blob module must be installed.")
  65. class AzureBlobTestCase(TestCase, LoaderModuleMockMixin):
  66. """
  67. TestCase for salt.pillar.azureblob ext_pillar.
  68. """
  69. def setup_loader_modules(self):
  70. self.opts = salt.config.DEFAULT_MASTER_OPTS.copy()
  71. utils = salt.loader.utils(self.opts)
  72. return {
  73. azureblob: {"__opts__": self.opts, "__utils__": utils},
  74. }
  75. def test__init_expired(self):
  76. """
  77. Tests the result of _init when the cache is expired.
  78. """
  79. container = "test"
  80. multiple_env = False
  81. environment = "base"
  82. blob_cache_expire = 0 # The cache will be expired
  83. blob_client = MockBlobServiceClient()
  84. cache_file = tempfile.NamedTemporaryFile()
  85. # Patches the _get_containers_cache_filename module so that it returns the name of the new tempfile that
  86. # represents the cache file
  87. with patch.object(
  88. azureblob,
  89. "_get_containers_cache_filename",
  90. MagicMock(return_value=str(cache_file.name)),
  91. ):
  92. # Patches the from_connection_string module of the BlobServiceClient class so that a connection string does
  93. # not need to be given. Additionally it returns example blob data used by the ext_pillar.
  94. with patch.object(
  95. BlobServiceClient,
  96. "from_connection_string",
  97. MagicMock(return_value=blob_client),
  98. ):
  99. ret = azureblob._init(
  100. "", container, multiple_env, environment, blob_cache_expire
  101. )
  102. cache_file.close()
  103. self.assertEqual(
  104. ret,
  105. {
  106. "base": {
  107. "test": [
  108. {
  109. "container": None,
  110. "name": "test.sls",
  111. "prefix": None,
  112. "delimiter": "/",
  113. "results_per_page": None,
  114. "location_mode": None,
  115. }
  116. ]
  117. }
  118. },
  119. )
  120. def test__init_not_expired(self):
  121. """
  122. Tests the result of _init when the cache is not expired.
  123. """
  124. container = "test"
  125. multiple_env = False
  126. environment = "base"
  127. blob_cache_expire = (time.time()) * (
  128. time.time()
  129. ) # The cache will not be expired
  130. metadata = {
  131. "base": {
  132. "test": [
  133. {"name": "base/secret.sls", "relevant": "include.sls"},
  134. {"name": "blobtest.sls", "irrelevant": "ignore.sls"},
  135. ]
  136. }
  137. }
  138. cache_file = tempfile.NamedTemporaryFile()
  139. # Pickles the metadata and stores it in cache_file
  140. with salt.utils.files.fopen(str(cache_file), "wb") as fp_:
  141. pickle.dump(metadata, fp_)
  142. # Patches the _get_containers_cache_filename module so that it returns the name of the new tempfile that
  143. # represents the cache file
  144. with patch.object(
  145. azureblob,
  146. "_get_containers_cache_filename",
  147. MagicMock(return_value=str(cache_file.name)),
  148. ):
  149. # Patches the _read_containers_cache_file module so that it returns what it normally would if the new
  150. # tempfile representing the cache file was passed to it
  151. plugged = azureblob._read_containers_cache_file(str(cache_file))
  152. with patch.object(
  153. azureblob,
  154. "_read_containers_cache_file",
  155. MagicMock(return_value=plugged),
  156. ):
  157. ret = azureblob._init(
  158. "", container, multiple_env, environment, blob_cache_expire
  159. )
  160. fp_.close()
  161. os.remove(str(fp_.name))
  162. cache_file.close()
  163. self.assertEqual(ret, metadata)
  164. def test__get_cache_dir(self):
  165. """
  166. Tests the result of _get_cache_dir.
  167. """
  168. ret = azureblob._get_cache_dir()
  169. self.assertEqual(ret, "/var/cache/salt/master/pillar_azureblob")
  170. def test__get_cached_file_name(self):
  171. """
  172. Tests the result of _get_cached_file_name.
  173. """
  174. container = "test"
  175. saltenv = "base"
  176. path = "base/secret.sls"
  177. ret = azureblob._get_cached_file_name(container, saltenv, path)
  178. self.assertEqual(
  179. ret, "/var/cache/salt/master/pillar_azureblob/base/test/base/secret.sls"
  180. )
  181. def test__get_containers_cache_filename(self):
  182. """
  183. Tests the result of _get_containers_cache_filename.
  184. """
  185. container = "test"
  186. ret = azureblob._get_containers_cache_filename(container)
  187. self.assertEqual(
  188. ret, "/var/cache/salt/master/pillar_azureblob/test-files.cache"
  189. )
  190. def test__refresh_containers_cache_file(self):
  191. """
  192. Tests the result of _refresh_containers_cache_file to ensure that it successfully copies blob data into a
  193. cache file.
  194. """
  195. blob_client = MockBlobServiceClient()
  196. container = "test"
  197. cache_file = tempfile.NamedTemporaryFile()
  198. with patch.object(
  199. BlobServiceClient,
  200. "from_connection_string",
  201. MagicMock(return_value=blob_client),
  202. ):
  203. ret = azureblob._refresh_containers_cache_file(
  204. "", container, cache_file.name
  205. )
  206. cache_file.close()
  207. self.assertEqual(
  208. ret,
  209. {
  210. "base": {
  211. "test": [
  212. {
  213. "container": None,
  214. "name": "test.sls",
  215. "prefix": None,
  216. "delimiter": "/",
  217. "results_per_page": None,
  218. "location_mode": None,
  219. }
  220. ]
  221. }
  222. },
  223. )
  224. def test__read_containers_cache_file(self):
  225. """
  226. Tests the result of _read_containers_cache_file to make sure that it successfully loads in pickled metadata.
  227. """
  228. metadata = {
  229. "base": {
  230. "test": [
  231. {"name": "base/secret.sls", "relevant": "include.sls"},
  232. {"name": "blobtest.sls", "irrelevant": "ignore.sls"},
  233. ]
  234. }
  235. }
  236. cache_file = tempfile.NamedTemporaryFile()
  237. # Pickles the metadata and stores it in cache_file
  238. with salt.utils.files.fopen(str(cache_file), "wb") as fp_:
  239. pickle.dump(metadata, fp_)
  240. # Checks to see if _read_containers_cache_file can successfully read the pickled metadata from the cache file
  241. ret = azureblob._read_containers_cache_file(str(cache_file))
  242. fp_.close()
  243. os.remove(str(fp_.name))
  244. cache_file.close()
  245. self.assertEqual(ret, metadata)
  246. def test__find_files(self):
  247. """
  248. Tests the result of _find_files. Ensures it only finds files and not directories. Ensures it also ignore
  249. irrelevant files.
  250. """
  251. metadata = {
  252. "test": [
  253. {"name": "base/secret.sls"},
  254. {"name": "blobtest.sls", "irrelevant": "ignore.sls"},
  255. {"name": "base/"},
  256. ]
  257. }
  258. ret = azureblob._find_files(metadata)
  259. self.assertEqual(ret, {"test": ["base/secret.sls", "blobtest.sls"]})
  260. def test__find_file_meta1(self):
  261. """
  262. Tests the result of _find_file_meta when the metadata contains a blob with the specified path and a blob
  263. without the specified path.
  264. """
  265. metadata = {
  266. "base": {
  267. "test": [
  268. {"name": "base/secret.sls", "relevant": "include.sls"},
  269. {"name": "blobtest.sls", "irrelevant": "ignore.sls"},
  270. ]
  271. }
  272. }
  273. container = "test"
  274. saltenv = "base"
  275. path = "base/secret.sls"
  276. ret = azureblob._find_file_meta(metadata, container, saltenv, path)
  277. self.assertEqual(ret, {"name": "base/secret.sls", "relevant": "include.sls"})
  278. def test__find_file_meta2(self):
  279. """
  280. Tests the result of _find_file_meta when the saltenv in metadata does not match the specified saltenv.
  281. """
  282. metadata = {"wrong": {"test": [{"name": "base/secret.sls"}]}}
  283. container = "test"
  284. saltenv = "base"
  285. path = "base/secret.sls"
  286. ret = azureblob._find_file_meta(metadata, container, saltenv, path)
  287. self.assertEqual(ret, None)
  288. def test__find_file_meta3(self):
  289. """
  290. Tests the result of _find_file_meta when the container in metadata does not match the specified metadata.
  291. """
  292. metadata = {"base": {"wrong": [{"name": "base/secret.sls"}]}}
  293. container = "test"
  294. saltenv = "base"
  295. path = "base/secret.sls"
  296. ret = azureblob._find_file_meta(metadata, container, saltenv, path)
  297. self.assertEqual(ret, None)