1
0

test_fileclient.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  1. # -*- coding: utf-8 -*-
  2. '''
  3. Tests for the salt fileclient
  4. '''
  5. # Import Python libs
  6. from __future__ import absolute_import
  7. import errno
  8. import logging
  9. import os
  10. import shutil
  11. # Import Salt Testing libs
  12. from tests.support.mixins import AdaptedConfigurationTestCaseMixin, LoaderModuleMockMixin
  13. from tests.support.mock import patch, Mock, MagicMock
  14. from tests.support.unit import TestCase
  15. from tests.support.runtests import RUNTIME_VARS
  16. # Import Salt libs
  17. import salt.utils.files
  18. from salt.ext.six.moves import range
  19. from salt import fileclient
  20. from salt.ext import six
  21. log = logging.getLogger(__name__)
  22. class FileclientTestCase(TestCase):
  23. '''
  24. Fileclient test
  25. '''
  26. opts = {
  27. 'extension_modules': '',
  28. 'cachedir': '/__test__',
  29. }
  30. def _fake_makedir(self, num=errno.EEXIST):
  31. def _side_effect(*args, **kwargs):
  32. raise OSError(num, 'Errno {0}'.format(num))
  33. return Mock(side_effect=_side_effect)
  34. def test_cache_skips_makedirs_on_race_condition(self):
  35. '''
  36. If cache contains already a directory, do not raise an exception.
  37. '''
  38. with patch('os.path.isfile', lambda prm: False):
  39. for exists in range(2):
  40. with patch('os.makedirs', self._fake_makedir()):
  41. with fileclient.Client(self.opts)._cache_loc('testfile') as c_ref_itr:
  42. assert c_ref_itr == os.sep + os.sep.join(['__test__', 'files', 'base', 'testfile'])
  43. def test_cache_raises_exception_on_non_eexist_ioerror(self):
  44. '''
  45. If makedirs raises other than EEXIST errno, an exception should be raised.
  46. '''
  47. with patch('os.path.isfile', lambda prm: False):
  48. with patch('os.makedirs', self._fake_makedir(num=errno.EROFS)):
  49. with self.assertRaises(OSError):
  50. with fileclient.Client(self.opts)._cache_loc('testfile') as c_ref_itr:
  51. assert c_ref_itr == '/__test__/files/base/testfile'
  52. def test_extrn_path_with_long_filename(self):
  53. safe_file_name = os.path.split(fileclient.Client(self.opts)._extrn_path('https://test.com/' + ('A' * 254), 'base'))[-1]
  54. assert safe_file_name == 'A' * 254
  55. oversized_file_name = os.path.split(fileclient.Client(self.opts)._extrn_path('https://test.com/' + ('A' * 255), 'base'))[-1]
  56. assert len(oversized_file_name) < 256
  57. assert oversized_file_name != 'A' * 255
  58. oversized_file_with_query_params = os.path.split(fileclient.Client(self.opts)._extrn_path('https://test.com/file?' + ('A' * 255), 'base'))[-1]
  59. assert len(oversized_file_with_query_params) < 256
  60. SALTENVS = ('base', 'dev')
  61. SUBDIR = 'subdir'
  62. SUBDIR_FILES = ('foo.txt', 'bar.txt', 'baz.txt')
  63. def _get_file_roots(fs_root):
  64. return dict(
  65. [(x, [os.path.join(fs_root, x)]) for x in SALTENVS]
  66. )
  67. class FileClientTest(TestCase, AdaptedConfigurationTestCaseMixin, LoaderModuleMockMixin):
  68. def setup_loader_modules(self):
  69. FS_ROOT = os.path.join(RUNTIME_VARS.TMP, 'fileclient_fs_root')
  70. CACHE_ROOT = os.path.join(RUNTIME_VARS.TMP, 'fileclient_cache_root')
  71. MOCKED_OPTS = {
  72. 'file_roots': _get_file_roots(FS_ROOT),
  73. 'fileserver_backend': ['roots'],
  74. 'cachedir': CACHE_ROOT,
  75. 'file_client': 'local',
  76. }
  77. self.addCleanup(shutil.rmtree, FS_ROOT, ignore_errors=True)
  78. self.addCleanup(shutil.rmtree, CACHE_ROOT, ignore_errors=True)
  79. return {fileclient: {'__opts__': MOCKED_OPTS}}
  80. def setUp(self):
  81. self.file_client = fileclient.Client(self.master_opts)
  82. def tearDown(self):
  83. del self.file_client
  84. def test_file_list_emptydirs(self):
  85. '''
  86. Ensure that the fileclient class won't allow a direct call to file_list_emptydirs()
  87. '''
  88. with self.assertRaises(NotImplementedError):
  89. self.file_client.file_list_emptydirs()
  90. def test_get_file(self):
  91. '''
  92. Ensure that the fileclient class won't allow a direct call to get_file()
  93. '''
  94. with self.assertRaises(NotImplementedError):
  95. self.file_client.get_file(None)
  96. def test_get_file_client(self):
  97. minion_opts = self.get_temp_config('minion')
  98. minion_opts['file_client'] = 'remote'
  99. with patch('salt.fileclient.RemoteClient', MagicMock(return_value='remote_client')):
  100. ret = fileclient.get_file_client(minion_opts)
  101. self.assertEqual('remote_client', ret)
  102. class FileclientCacheTest(TestCase, AdaptedConfigurationTestCaseMixin, LoaderModuleMockMixin):
  103. '''
  104. Tests for the fileclient caching. The LocalClient is the only thing we can
  105. test as it is the only way we can mock the fileclient (the tests run from
  106. the minion process, so the master cannot be mocked from test code).
  107. '''
  108. def setup_loader_modules(self):
  109. self.FS_ROOT = os.path.join(RUNTIME_VARS.TMP, 'fileclient_fs_root')
  110. self.CACHE_ROOT = os.path.join(RUNTIME_VARS.TMP, 'fileclient_cache_root')
  111. self.MOCKED_OPTS = {
  112. 'file_roots': _get_file_roots(self.FS_ROOT),
  113. 'fileserver_backend': ['roots'],
  114. 'cachedir': self.CACHE_ROOT,
  115. 'file_client': 'local',
  116. }
  117. self.addCleanup(shutil.rmtree, self.FS_ROOT, ignore_errors=True)
  118. self.addCleanup(shutil.rmtree, self.CACHE_ROOT, ignore_errors=True)
  119. return {fileclient: {'__opts__': self.MOCKED_OPTS}}
  120. def setUp(self):
  121. '''
  122. No need to add a dummy foo.txt to muddy up the github repo, just make
  123. our own fileserver root on-the-fly.
  124. '''
  125. def _new_dir(path):
  126. '''
  127. Add a new dir at ``path`` using os.makedirs. If the directory
  128. already exists, remove it recursively and then try to create it
  129. again.
  130. '''
  131. try:
  132. os.makedirs(path)
  133. except OSError as exc:
  134. if exc.errno == errno.EEXIST:
  135. # Just in case a previous test was interrupted, remove the
  136. # directory and try adding it again.
  137. shutil.rmtree(path)
  138. os.makedirs(path)
  139. else:
  140. raise
  141. # Crete the FS_ROOT
  142. for saltenv in SALTENVS:
  143. saltenv_root = os.path.join(self.FS_ROOT, saltenv)
  144. # Make sure we have a fresh root dir for this saltenv
  145. _new_dir(saltenv_root)
  146. path = os.path.join(saltenv_root, 'foo.txt')
  147. with salt.utils.files.fopen(path, 'w') as fp_:
  148. fp_.write(
  149. 'This is a test file in the \'{0}\' saltenv.\n'
  150. .format(saltenv)
  151. )
  152. subdir_abspath = os.path.join(saltenv_root, SUBDIR)
  153. os.makedirs(subdir_abspath)
  154. for subdir_file in SUBDIR_FILES:
  155. path = os.path.join(subdir_abspath, subdir_file)
  156. with salt.utils.files.fopen(path, 'w') as fp_:
  157. fp_.write(
  158. 'This is file \'{0}\' in subdir \'{1} from saltenv '
  159. '\'{2}\''.format(subdir_file, SUBDIR, saltenv)
  160. )
  161. # Create the CACHE_ROOT
  162. _new_dir(self.CACHE_ROOT)
  163. def test_cache_dir(self):
  164. '''
  165. Ensure entire directory is cached to correct location
  166. '''
  167. patched_opts = dict((x, y) for x, y in six.iteritems(self.minion_opts))
  168. patched_opts.update(self.MOCKED_OPTS)
  169. with patch.dict(fileclient.__opts__, patched_opts):
  170. client = fileclient.get_file_client(fileclient.__opts__, pillar=False)
  171. for saltenv in SALTENVS:
  172. self.assertTrue(
  173. client.cache_dir(
  174. 'salt://{0}'.format(SUBDIR),
  175. saltenv,
  176. cachedir=None
  177. )
  178. )
  179. for subdir_file in SUBDIR_FILES:
  180. cache_loc = os.path.join(fileclient.__opts__['cachedir'],
  181. 'files',
  182. saltenv,
  183. SUBDIR,
  184. subdir_file)
  185. # Double check that the content of the cached file
  186. # identifies it as being from the correct saltenv. The
  187. # setUp function creates the file with the name of the
  188. # saltenv mentioned in the file, so a simple 'in' check is
  189. # sufficient here. If opening the file raises an exception,
  190. # this is a problem, so we are not catching the exception
  191. # and letting it be raised so that the test fails.
  192. with salt.utils.files.fopen(cache_loc) as fp_:
  193. content = fp_.read()
  194. log.debug('cache_loc = %s', cache_loc)
  195. log.debug('content = %s', content)
  196. self.assertTrue(subdir_file in content)
  197. self.assertTrue(SUBDIR in content)
  198. self.assertTrue(saltenv in content)
  199. def test_cache_dir_with_alternate_cachedir_and_absolute_path(self):
  200. '''
  201. Ensure entire directory is cached to correct location when an alternate
  202. cachedir is specified and that cachedir is an absolute path
  203. '''
  204. patched_opts = dict((x, y) for x, y in six.iteritems(self.minion_opts))
  205. patched_opts.update(self.MOCKED_OPTS)
  206. alt_cachedir = os.path.join(RUNTIME_VARS.TMP, 'abs_cachedir')
  207. with patch.dict(fileclient.__opts__, patched_opts):
  208. client = fileclient.get_file_client(fileclient.__opts__, pillar=False)
  209. for saltenv in SALTENVS:
  210. self.assertTrue(
  211. client.cache_dir(
  212. 'salt://{0}'.format(SUBDIR),
  213. saltenv,
  214. cachedir=alt_cachedir
  215. )
  216. )
  217. for subdir_file in SUBDIR_FILES:
  218. cache_loc = os.path.join(alt_cachedir,
  219. 'files',
  220. saltenv,
  221. SUBDIR,
  222. subdir_file)
  223. # Double check that the content of the cached file
  224. # identifies it as being from the correct saltenv. The
  225. # setUp function creates the file with the name of the
  226. # saltenv mentioned in the file, so a simple 'in' check is
  227. # sufficient here. If opening the file raises an exception,
  228. # this is a problem, so we are not catching the exception
  229. # and letting it be raised so that the test fails.
  230. with salt.utils.files.fopen(cache_loc) as fp_:
  231. content = fp_.read()
  232. log.debug('cache_loc = %s', cache_loc)
  233. log.debug('content = %s', content)
  234. self.assertTrue(subdir_file in content)
  235. self.assertTrue(SUBDIR in content)
  236. self.assertTrue(saltenv in content)
  237. def test_cache_dir_with_alternate_cachedir_and_relative_path(self):
  238. '''
  239. Ensure entire directory is cached to correct location when an alternate
  240. cachedir is specified and that cachedir is a relative path
  241. '''
  242. patched_opts = dict((x, y) for x, y in six.iteritems(self.minion_opts))
  243. patched_opts.update(self.MOCKED_OPTS)
  244. alt_cachedir = 'foo'
  245. with patch.dict(fileclient.__opts__, patched_opts):
  246. client = fileclient.get_file_client(fileclient.__opts__, pillar=False)
  247. for saltenv in SALTENVS:
  248. self.assertTrue(
  249. client.cache_dir(
  250. 'salt://{0}'.format(SUBDIR),
  251. saltenv,
  252. cachedir=alt_cachedir
  253. )
  254. )
  255. for subdir_file in SUBDIR_FILES:
  256. cache_loc = os.path.join(fileclient.__opts__['cachedir'],
  257. alt_cachedir,
  258. 'files',
  259. saltenv,
  260. SUBDIR,
  261. subdir_file)
  262. # Double check that the content of the cached file
  263. # identifies it as being from the correct saltenv. The
  264. # setUp function creates the file with the name of the
  265. # saltenv mentioned in the file, so a simple 'in' check is
  266. # sufficient here. If opening the file raises an exception,
  267. # this is a problem, so we are not catching the exception
  268. # and letting it be raised so that the test fails.
  269. with salt.utils.files.fopen(cache_loc) as fp_:
  270. content = fp_.read()
  271. log.debug('cache_loc = %s', cache_loc)
  272. log.debug('content = %s', content)
  273. self.assertTrue(subdir_file in content)
  274. self.assertTrue(SUBDIR in content)
  275. self.assertTrue(saltenv in content)
  276. def test_cache_file(self):
  277. '''
  278. Ensure file is cached to correct location
  279. '''
  280. patched_opts = dict((x, y) for x, y in six.iteritems(self.minion_opts))
  281. patched_opts.update(self.MOCKED_OPTS)
  282. with patch.dict(fileclient.__opts__, patched_opts):
  283. client = fileclient.get_file_client(fileclient.__opts__, pillar=False)
  284. for saltenv in SALTENVS:
  285. self.assertTrue(
  286. client.cache_file('salt://foo.txt', saltenv, cachedir=None)
  287. )
  288. cache_loc = os.path.join(
  289. fileclient.__opts__['cachedir'], 'files', saltenv, 'foo.txt')
  290. # Double check that the content of the cached file identifies
  291. # it as being from the correct saltenv. The setUp function
  292. # creates the file with the name of the saltenv mentioned in
  293. # the file, so a simple 'in' check is sufficient here. If
  294. # opening the file raises an exception, this is a problem, so
  295. # we are not catching the exception and letting it be raised so
  296. # that the test fails.
  297. with salt.utils.files.fopen(cache_loc) as fp_:
  298. content = fp_.read()
  299. log.debug('cache_loc = %s', cache_loc)
  300. log.debug('content = %s', content)
  301. self.assertTrue(saltenv in content)
  302. def test_cache_file_with_alternate_cachedir_and_absolute_path(self):
  303. '''
  304. Ensure file is cached to correct location when an alternate cachedir is
  305. specified and that cachedir is an absolute path
  306. '''
  307. patched_opts = dict((x, y) for x, y in six.iteritems(self.minion_opts))
  308. patched_opts.update(self.MOCKED_OPTS)
  309. alt_cachedir = os.path.join(RUNTIME_VARS.TMP, 'abs_cachedir')
  310. with patch.dict(fileclient.__opts__, patched_opts):
  311. client = fileclient.get_file_client(fileclient.__opts__, pillar=False)
  312. for saltenv in SALTENVS:
  313. self.assertTrue(
  314. client.cache_file('salt://foo.txt',
  315. saltenv,
  316. cachedir=alt_cachedir)
  317. )
  318. cache_loc = os.path.join(alt_cachedir,
  319. 'files',
  320. saltenv,
  321. 'foo.txt')
  322. # Double check that the content of the cached file identifies
  323. # it as being from the correct saltenv. The setUp function
  324. # creates the file with the name of the saltenv mentioned in
  325. # the file, so a simple 'in' check is sufficient here. If
  326. # opening the file raises an exception, this is a problem, so
  327. # we are not catching the exception and letting it be raised so
  328. # that the test fails.
  329. with salt.utils.files.fopen(cache_loc) as fp_:
  330. content = fp_.read()
  331. log.debug('cache_loc = %s', cache_loc)
  332. log.debug('content = %s', content)
  333. self.assertTrue(saltenv in content)
  334. def test_cache_file_with_alternate_cachedir_and_relative_path(self):
  335. '''
  336. Ensure file is cached to correct location when an alternate cachedir is
  337. specified and that cachedir is a relative path
  338. '''
  339. patched_opts = dict((x, y) for x, y in six.iteritems(self.minion_opts))
  340. patched_opts.update(self.MOCKED_OPTS)
  341. alt_cachedir = 'foo'
  342. with patch.dict(fileclient.__opts__, patched_opts):
  343. client = fileclient.get_file_client(fileclient.__opts__, pillar=False)
  344. for saltenv in SALTENVS:
  345. self.assertTrue(
  346. client.cache_file('salt://foo.txt',
  347. saltenv,
  348. cachedir=alt_cachedir)
  349. )
  350. cache_loc = os.path.join(fileclient.__opts__['cachedir'],
  351. alt_cachedir,
  352. 'files',
  353. saltenv,
  354. 'foo.txt')
  355. # Double check that the content of the cached file identifies
  356. # it as being from the correct saltenv. The setUp function
  357. # creates the file with the name of the saltenv mentioned in
  358. # the file, so a simple 'in' check is sufficient here. If
  359. # opening the file raises an exception, this is a problem, so
  360. # we are not catching the exception and letting it be raised so
  361. # that the test fails.
  362. with salt.utils.files.fopen(cache_loc) as fp_:
  363. content = fp_.read()
  364. log.debug('cache_loc = %s', cache_loc)
  365. log.debug('content = %s', content)
  366. self.assertTrue(saltenv in content)