1
0

test_loader.py 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244
  1. # -*- coding: utf-8 -*-
  2. '''
  3. unit.loader
  4. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  5. Test Salt's loader
  6. '''
  7. # Import Python libs
  8. from __future__ import absolute_import, print_function, unicode_literals
  9. import collections
  10. import compileall
  11. import copy
  12. import imp
  13. import inspect
  14. import logging
  15. import os
  16. import shutil
  17. import sys
  18. import tempfile
  19. import textwrap
  20. # Import Salt Testing libs
  21. from tests.support.case import ModuleCase
  22. from tests.support.unit import TestCase
  23. from tests.support.mock import patch
  24. from tests.support.paths import TMP
  25. # Import Salt libs
  26. import salt.config
  27. import salt.loader
  28. import salt.utils.files
  29. import salt.utils.stringutils
  30. # pylint: disable=import-error,no-name-in-module,redefined-builtin
  31. from salt.ext import six
  32. from salt.ext.six.moves import range
  33. # pylint: enable=no-name-in-module,redefined-builtin
  34. log = logging.getLogger(__name__)
  35. def remove_bytecode(module_path):
  36. paths = [module_path + 'c']
  37. if hasattr(imp, 'get_tag'):
  38. modname, ext = os.path.splitext(module_path.split(os.sep)[-1])
  39. paths.append(
  40. os.path.join(os.path.dirname(module_path),
  41. '__pycache__',
  42. '{}.{}.pyc'.format(modname, imp.get_tag())))
  43. for path in paths:
  44. if os.path.exists(path):
  45. os.unlink(path)
  46. loader_template = '''
  47. import os
  48. from salt.utils.decorators import depends
  49. @depends('os')
  50. def loaded():
  51. return True
  52. @depends('non_existantmodulename')
  53. def not_loaded():
  54. return True
  55. '''
  56. class LazyLoaderTest(TestCase):
  57. '''
  58. Test the loader
  59. '''
  60. module_name = 'lazyloadertest'
  61. @classmethod
  62. def setUpClass(cls):
  63. cls.opts = salt.config.minion_config(None)
  64. cls.opts['grains'] = salt.loader.grains(cls.opts)
  65. if not os.path.isdir(TMP):
  66. os.makedirs(TMP)
  67. def setUp(self):
  68. # Setup the module
  69. self.module_dir = tempfile.mkdtemp(dir=TMP)
  70. self.module_file = os.path.join(self.module_dir,
  71. '{0}.py'.format(self.module_name))
  72. with salt.utils.files.fopen(self.module_file, 'w') as fh:
  73. fh.write(salt.utils.stringutils.to_str(loader_template))
  74. fh.flush()
  75. os.fsync(fh.fileno())
  76. # Invoke the loader
  77. self.loader = salt.loader.LazyLoader([self.module_dir], copy.deepcopy(self.opts), tag='module')
  78. def tearDown(self):
  79. shutil.rmtree(self.module_dir)
  80. if os.path.isdir(self.module_dir):
  81. shutil.rmtree(self.module_dir)
  82. del self.module_dir
  83. del self.module_file
  84. del self.loader
  85. @classmethod
  86. def tearDownClass(cls):
  87. del cls.opts
  88. def test_depends(self):
  89. '''
  90. Test that the depends decorator works properly
  91. '''
  92. # Make sure depends correctly allowed a function to load. If this
  93. # results in a KeyError, the decorator is broken.
  94. self.assertTrue(
  95. inspect.isfunction(
  96. self.loader[self.module_name + '.loaded']
  97. )
  98. )
  99. # Make sure depends correctly kept a function from loading
  100. self.assertTrue(self.module_name + '.not_loaded' not in self.loader)
  101. class LazyLoaderVirtualEnabledTest(TestCase):
  102. '''
  103. Test the base loader of salt.
  104. '''
  105. @classmethod
  106. def setUpClass(cls):
  107. cls.opts = salt.config.minion_config(None)
  108. cls.opts['disable_modules'] = ['pillar']
  109. cls.opts['grains'] = salt.loader.grains(cls.opts)
  110. def setUp(self):
  111. self.loader = salt.loader.LazyLoader(
  112. salt.loader._module_dirs(copy.deepcopy(self.opts), 'modules', 'module'),
  113. copy.deepcopy(self.opts),
  114. tag='module')
  115. def tearDown(self):
  116. del self.loader
  117. @classmethod
  118. def tearDownClass(cls):
  119. del cls.opts
  120. def test_basic(self):
  121. '''
  122. Ensure that it only loads stuff when needed
  123. '''
  124. # make sure it starts empty
  125. self.assertEqual(self.loader._dict, {})
  126. # get something, and make sure its a func
  127. self.assertTrue(inspect.isfunction(self.loader['test.ping']))
  128. # make sure we only loaded "test" functions
  129. for key, val in six.iteritems(self.loader._dict):
  130. self.assertEqual(key.split('.', 1)[0], 'test')
  131. # make sure the depends thing worked (double check of the depends testing,
  132. # since the loader does the calling magically
  133. self.assertFalse('test.missing_func' in self.loader._dict)
  134. def test_badkey(self):
  135. with self.assertRaises(KeyError):
  136. self.loader[None] # pylint: disable=W0104
  137. with self.assertRaises(KeyError):
  138. self.loader[1] # pylint: disable=W0104
  139. def test_disable(self):
  140. self.assertNotIn('pillar.items', self.loader)
  141. def test_len_load(self):
  142. '''
  143. Since LazyLoader is a MutableMapping, if someone asks for len() we have
  144. to load all
  145. '''
  146. self.assertEqual(self.loader._dict, {})
  147. len(self.loader) # force a load all
  148. self.assertNotEqual(self.loader._dict, {})
  149. def test_iter_load(self):
  150. '''
  151. Since LazyLoader is a MutableMapping, if someone asks to iterate we have
  152. to load all
  153. '''
  154. self.assertEqual(self.loader._dict, {})
  155. # force a load all
  156. for key, func in six.iteritems(self.loader):
  157. break
  158. self.assertNotEqual(self.loader._dict, {})
  159. def test_context(self):
  160. '''
  161. Make sure context is shared across modules
  162. '''
  163. # make sure it starts empty
  164. self.assertEqual(self.loader._dict, {})
  165. # get something, and make sure its a func
  166. func = self.loader['test.ping']
  167. with patch.dict(func.__globals__['__context__'], {'foo': 'bar'}):
  168. self.assertEqual(self.loader['test.echo'].__globals__['__context__']['foo'], 'bar')
  169. self.assertEqual(self.loader['grains.get'].__globals__['__context__']['foo'], 'bar')
  170. def test_globals(self):
  171. func_globals = self.loader['test.ping'].__globals__
  172. self.assertEqual(func_globals['__grains__'], self.opts.get('grains', {}))
  173. self.assertEqual(func_globals['__pillar__'], self.opts.get('pillar', {}))
  174. # the opts passed into modules is at least a subset of the whole opts
  175. for key, val in six.iteritems(func_globals['__opts__']):
  176. if key in salt.config.DEFAULT_MASTER_OPTS and key not in salt.config.DEFAULT_MINION_OPTS:
  177. # We loaded the minion opts, but somewhere in the code, the master options got pulled in
  178. # Let's just not check for equality since the option won't even exist in the loaded
  179. # minion options
  180. continue
  181. if key not in salt.config.DEFAULT_MASTER_OPTS and key not in salt.config.DEFAULT_MINION_OPTS:
  182. # This isn't even a default configuration setting, lets carry on
  183. continue
  184. self.assertEqual(self.opts[key], val)
  185. def test_pack(self):
  186. self.loader.pack['__foo__'] = 'bar'
  187. func_globals = self.loader['test.ping'].__globals__
  188. self.assertEqual(func_globals['__foo__'], 'bar')
  189. def test_virtual(self):
  190. self.assertNotIn('test_virtual.ping', self.loader)
  191. class LazyLoaderVirtualDisabledTest(TestCase):
  192. '''
  193. Test the loader of salt without __virtual__
  194. '''
  195. @classmethod
  196. def setUpClass(cls):
  197. cls.opts = salt.config.minion_config(None)
  198. cls.opts['grains'] = salt.loader.grains(cls.opts)
  199. def setUp(self):
  200. self.loader = salt.loader.LazyLoader(
  201. salt.loader._module_dirs(copy.deepcopy(self.opts), 'modules', 'module'),
  202. copy.deepcopy(self.opts),
  203. tag='module',
  204. virtual_enable=False)
  205. def tearDown(self):
  206. del self.loader
  207. @classmethod
  208. def tearDownClass(cls):
  209. del cls.opts
  210. def test_virtual(self):
  211. self.assertTrue(inspect.isfunction(self.loader['test_virtual.ping']))
  212. class LazyLoaderWhitelistTest(TestCase):
  213. '''
  214. Test the loader of salt with a whitelist
  215. '''
  216. @classmethod
  217. def setUpClass(cls):
  218. cls.opts = salt.config.minion_config(None)
  219. cls.opts['grains'] = salt.loader.grains(cls.opts)
  220. def setUp(self):
  221. self.loader = salt.loader.LazyLoader(
  222. salt.loader._module_dirs(copy.deepcopy(self.opts), 'modules', 'module'),
  223. copy.deepcopy(self.opts),
  224. tag='module',
  225. whitelist=['test', 'pillar'])
  226. def tearDown(self):
  227. del self.loader
  228. @classmethod
  229. def tearDownClass(cls):
  230. del cls.opts
  231. def test_whitelist(self):
  232. self.assertTrue(inspect.isfunction(self.loader['test.ping']))
  233. self.assertTrue(inspect.isfunction(self.loader['pillar.get']))
  234. self.assertNotIn('grains.get', self.loader)
  235. class LazyLoaderSingleItem(TestCase):
  236. '''
  237. Test loading a single item via the _load() function
  238. '''
  239. @classmethod
  240. def setUpClass(cls):
  241. cls.opts = salt.config.minion_config(None)
  242. cls.opts['grains'] = salt.loader.grains(cls.opts)
  243. def setUp(self):
  244. self.loader = salt.loader.LazyLoader(
  245. salt.loader._module_dirs(copy.deepcopy(self.opts), 'modules', 'module'),
  246. copy.deepcopy(self.opts),
  247. tag='module')
  248. def tearDown(self):
  249. del self.loader
  250. def test_single_item_no_dot(self):
  251. '''
  252. Checks that a KeyError is raised when the function key does not contain a '.'
  253. '''
  254. key = 'testing_no_dot'
  255. expected = "The key '{0}' should contain a '.'".format(key)
  256. with self.assertRaises(KeyError) as err:
  257. inspect.isfunction(self.loader['testing_no_dot'])
  258. result = err.exception.args[0]
  259. assert result == expected, result
  260. module_template = '''
  261. __load__ = ['test', 'test_alias']
  262. __func_alias__ = dict(test_alias='working_alias')
  263. from salt.utils.decorators import depends
  264. def test():
  265. return {count}
  266. def test_alias():
  267. return True
  268. def test2():
  269. return True
  270. @depends('non_existantmodulename')
  271. def test3():
  272. return True
  273. @depends('non_existantmodulename', fallback_function=test)
  274. def test4():
  275. return True
  276. '''
  277. class LazyLoaderReloadingTest(TestCase):
  278. '''
  279. Test the loader of salt with changing modules
  280. '''
  281. module_name = 'loadertest'
  282. module_key = 'loadertest.test'
  283. @classmethod
  284. def setUpClass(cls):
  285. cls.opts = salt.config.minion_config(None)
  286. cls.opts['grains'] = salt.loader.grains(cls.opts)
  287. if not os.path.isdir(TMP):
  288. os.makedirs(TMP)
  289. def setUp(self):
  290. self.tmp_dir = tempfile.mkdtemp(dir=TMP)
  291. self.count = 0
  292. opts = copy.deepcopy(self.opts)
  293. dirs = salt.loader._module_dirs(opts, 'modules', 'module')
  294. dirs.append(self.tmp_dir)
  295. self.utils = salt.loader.utils(opts)
  296. self.proxy = salt.loader.proxy(opts)
  297. self.minion_mods = salt.loader.minion_mods(opts)
  298. self.loader = salt.loader.LazyLoader(
  299. dirs,
  300. opts,
  301. tag='module',
  302. pack={'__utils__': self.utils,
  303. '__proxy__': self.proxy,
  304. '__salt__': self.minion_mods})
  305. def tearDown(self):
  306. shutil.rmtree(self.tmp_dir)
  307. for attrname in ('tmp_dir', 'utils', 'proxy', 'loader', 'minion_mods', 'utils'):
  308. try:
  309. delattr(self, attrname)
  310. except AttributeError:
  311. continue
  312. @classmethod
  313. def tearDownClass(cls):
  314. del cls.opts
  315. def update_module(self):
  316. self.count += 1
  317. with salt.utils.files.fopen(self.module_path, 'wb') as fh:
  318. fh.write(
  319. salt.utils.stringutils.to_bytes(
  320. module_template.format(count=self.count)
  321. )
  322. )
  323. fh.flush()
  324. os.fsync(fh.fileno()) # flush to disk
  325. # pyc files don't like it when we change the original quickly
  326. # since the header bytes only contain the timestamp (granularity of seconds)
  327. # TODO: don't write them? Is *much* slower on re-load (~3x)
  328. # https://docs.python.org/2/library/sys.html#sys.dont_write_bytecode
  329. remove_bytecode(self.module_path)
  330. def rm_module(self):
  331. os.unlink(self.module_path)
  332. remove_bytecode(self.module_path)
  333. @property
  334. def module_path(self):
  335. return os.path.join(self.tmp_dir, '{0}.py'.format(self.module_name))
  336. def test_alias(self):
  337. '''
  338. Make sure that you can access alias-d modules
  339. '''
  340. # ensure it doesn't exist
  341. self.assertNotIn(self.module_key, self.loader)
  342. self.update_module()
  343. self.assertNotIn('{0}.test_alias'.format(self.module_name), self.loader)
  344. self.assertTrue(inspect.isfunction(self.loader['{0}.working_alias'.format(self.module_name)]))
  345. def test_clear(self):
  346. self.assertTrue(inspect.isfunction(self.loader['test.ping']))
  347. self.update_module() # write out out custom module
  348. self.loader.clear() # clear the loader dict
  349. # force a load of our module
  350. self.assertTrue(inspect.isfunction(self.loader[self.module_key]))
  351. # make sure we only loaded our custom module
  352. # which means that we did correctly refresh the file mapping
  353. for k, v in six.iteritems(self.loader._dict):
  354. self.assertTrue(k.startswith(self.module_name))
  355. def test_load(self):
  356. # ensure it doesn't exist
  357. self.assertNotIn(self.module_key, self.loader)
  358. self.update_module()
  359. self.assertTrue(inspect.isfunction(self.loader[self.module_key]))
  360. def test__load__(self):
  361. '''
  362. If a module specifies __load__ we should only load/expose those modules
  363. '''
  364. self.update_module()
  365. # ensure it doesn't exist
  366. self.assertNotIn(self.module_key + '2', self.loader)
  367. def test__load__and_depends(self):
  368. '''
  369. If a module specifies __load__ we should only load/expose those modules
  370. '''
  371. self.update_module()
  372. # ensure it doesn't exist
  373. self.assertNotIn(self.module_key + '3', self.loader)
  374. self.assertNotIn(self.module_key + '4', self.loader)
  375. def test_reload(self):
  376. # ensure it doesn't exist
  377. self.assertNotIn(self.module_key, self.loader)
  378. # make sure it updates correctly
  379. for x in range(1, 3):
  380. self.update_module()
  381. self.loader.clear()
  382. self.assertEqual(self.loader[self.module_key](), self.count)
  383. self.rm_module()
  384. # make sure that even if we remove the module, its still loaded until a clear
  385. self.assertEqual(self.loader[self.module_key](), self.count)
  386. self.loader.clear()
  387. self.assertNotIn(self.module_key, self.loader)
  388. virtual_aliases = ('loadertest2', 'loadertest3')
  389. virtual_alias_module_template = '''
  390. __virtual_aliases__ = {0}
  391. def test():
  392. return True
  393. '''.format(virtual_aliases)
  394. class LazyLoaderVirtualAliasTest(TestCase):
  395. '''
  396. Test the loader of salt with changing modules
  397. '''
  398. module_name = 'loadertest'
  399. @classmethod
  400. def setUpClass(cls):
  401. cls.opts = salt.config.minion_config(None)
  402. cls.opts['grains'] = salt.loader.grains(cls.opts)
  403. if not os.path.isdir(TMP):
  404. os.makedirs(TMP)
  405. def setUp(self):
  406. self.tmp_dir = tempfile.mkdtemp(dir=TMP)
  407. opts = copy.deepcopy(self.opts)
  408. dirs = salt.loader._module_dirs(opts, 'modules', 'module')
  409. dirs.append(self.tmp_dir)
  410. self.utils = salt.loader.utils(opts)
  411. self.proxy = salt.loader.proxy(opts)
  412. self.minion_mods = salt.loader.minion_mods(opts)
  413. self.loader = salt.loader.LazyLoader(
  414. dirs,
  415. opts,
  416. tag='module',
  417. pack={'__utils__': self.utils,
  418. '__proxy__': self.proxy,
  419. '__salt__': self.minion_mods})
  420. def tearDown(self):
  421. del self.tmp_dir
  422. del self.utils
  423. del self.proxy
  424. del self.minion_mods
  425. del self.loader
  426. @classmethod
  427. def tearDownClass(cls):
  428. del cls.opts
  429. def update_module(self):
  430. with salt.utils.files.fopen(self.module_path, 'wb') as fh:
  431. fh.write(salt.utils.stringutils.to_bytes(virtual_alias_module_template))
  432. fh.flush()
  433. os.fsync(fh.fileno()) # flush to disk
  434. # pyc files don't like it when we change the original quickly
  435. # since the header bytes only contain the timestamp (granularity of seconds)
  436. # TODO: don't write them? Is *much* slower on re-load (~3x)
  437. # https://docs.python.org/2/library/sys.html#sys.dont_write_bytecode
  438. remove_bytecode(self.module_path)
  439. @property
  440. def module_path(self):
  441. return os.path.join(self.tmp_dir, '{0}.py'.format(self.module_name))
  442. def test_virtual_alias(self):
  443. '''
  444. Test the __virtual_alias__ feature
  445. '''
  446. self.update_module()
  447. mod_names = [self.module_name] + list(virtual_aliases)
  448. for mod_name in mod_names:
  449. func_name = '.'.join((mod_name, 'test'))
  450. log.debug('Running %s (dict attribute)', func_name)
  451. self.assertTrue(self.loader[func_name]())
  452. log.debug('Running %s (loader attribute)', func_name)
  453. self.assertTrue(getattr(self.loader, mod_name).test())
  454. submodule_template = '''
  455. from __future__ import absolute_import
  456. import {0}.lib
  457. def test():
  458. return ({count}, {0}.lib.test())
  459. '''
  460. submodule_lib_template = '''
  461. def test():
  462. return {count}
  463. '''
  464. class LazyLoaderSubmodReloadingTest(TestCase):
  465. '''
  466. Test the loader of salt with changing modules
  467. '''
  468. module_name = 'loadertestsubmod'
  469. module_key = 'loadertestsubmod.test'
  470. @classmethod
  471. def setUpClass(cls):
  472. cls.opts = salt.config.minion_config(None)
  473. cls.opts['grains'] = salt.loader.grains(cls.opts)
  474. if not os.path.isdir(TMP):
  475. os.makedirs(TMP)
  476. def setUp(self):
  477. self.tmp_dir = tempfile.mkdtemp(dir=TMP)
  478. os.makedirs(self.module_dir)
  479. self.count = 0
  480. self.lib_count = 0
  481. opts = copy.deepcopy(self.opts)
  482. dirs = salt.loader._module_dirs(opts, 'modules', 'module')
  483. dirs.append(self.tmp_dir)
  484. self.utils = salt.loader.utils(opts)
  485. self.proxy = salt.loader.proxy(opts)
  486. self.minion_mods = salt.loader.minion_mods(opts)
  487. self.loader = salt.loader.LazyLoader(
  488. dirs,
  489. opts,
  490. tag='module',
  491. pack={'__utils__': self.utils,
  492. '__proxy__': self.proxy,
  493. '__salt__': self.minion_mods})
  494. def tearDown(self):
  495. shutil.rmtree(self.tmp_dir)
  496. del self.tmp_dir
  497. del self.utils
  498. del self.proxy
  499. del self.minion_mods
  500. del self.loader
  501. @classmethod
  502. def tearDownClass(cls):
  503. del cls.opts
  504. def update_module(self):
  505. self.count += 1
  506. with salt.utils.files.fopen(self.module_path, 'wb') as fh:
  507. fh.write(
  508. salt.utils.stringutils.to_bytes(
  509. submodule_template.format(self.module_name, count=self.count)
  510. )
  511. )
  512. fh.flush()
  513. os.fsync(fh.fileno()) # flush to disk
  514. # pyc files don't like it when we change the original quickly
  515. # since the header bytes only contain the timestamp (granularity of seconds)
  516. # TODO: don't write them? Is *much* slower on re-load (~3x)
  517. # https://docs.python.org/2/library/sys.html#sys.dont_write_bytecode
  518. remove_bytecode(self.module_path)
  519. def rm_module(self):
  520. os.unlink(self.module_path)
  521. remove_bytecode(self.module_path)
  522. def update_lib(self):
  523. self.lib_count += 1
  524. for modname in list(sys.modules):
  525. if modname.startswith(self.module_name):
  526. del sys.modules[modname]
  527. with salt.utils.files.fopen(self.lib_path, 'wb') as fh:
  528. fh.write(
  529. salt.utils.stringutils.to_bytes(
  530. submodule_lib_template.format(count=self.lib_count)
  531. )
  532. )
  533. fh.flush()
  534. os.fsync(fh.fileno()) # flush to disk
  535. # pyc files don't like it when we change the original quickly
  536. # since the header bytes only contain the timestamp (granularity of seconds)
  537. # TODO: don't write them? Is *much* slower on re-load (~3x)
  538. # https://docs.python.org/2/library/sys.html#sys.dont_write_bytecode
  539. remove_bytecode(self.lib_path)
  540. def rm_lib(self):
  541. for modname in list(sys.modules):
  542. if modname.startswith(self.module_name):
  543. del sys.modules[modname]
  544. os.unlink(self.lib_path)
  545. remove_bytecode(self.lib_path)
  546. @property
  547. def module_dir(self):
  548. return os.path.join(self.tmp_dir, self.module_name)
  549. @property
  550. def module_path(self):
  551. return os.path.join(self.module_dir, '__init__.py')
  552. @property
  553. def lib_path(self):
  554. return os.path.join(self.module_dir, 'lib.py')
  555. def test_basic(self):
  556. # ensure it doesn't exist
  557. self.assertNotIn(self.module_key, self.loader)
  558. self.update_module()
  559. self.update_lib()
  560. self.loader.clear()
  561. self.assertIn(self.module_key, self.loader)
  562. def test_reload(self):
  563. # ensure it doesn't exist
  564. self.assertNotIn(self.module_key, self.loader)
  565. # update both the module and the lib
  566. for x in range(1, 3):
  567. self.update_lib()
  568. self.update_module()
  569. self.loader.clear()
  570. self.assertNotIn(self.module_key, self.loader._dict)
  571. self.assertIn(self.module_key, self.loader)
  572. self.assertEqual(self.loader[self.module_key](), (self.count, self.lib_count))
  573. # update just the module
  574. for x in range(1, 3):
  575. self.update_module()
  576. self.loader.clear()
  577. self.assertNotIn(self.module_key, self.loader._dict)
  578. self.assertIn(self.module_key, self.loader)
  579. self.assertEqual(self.loader[self.module_key](), (self.count, self.lib_count))
  580. # update just the lib
  581. for x in range(1, 3):
  582. self.update_lib()
  583. self.loader.clear()
  584. self.assertNotIn(self.module_key, self.loader._dict)
  585. self.assertIn(self.module_key, self.loader)
  586. self.assertEqual(self.loader[self.module_key](), (self.count, self.lib_count))
  587. self.rm_module()
  588. # make sure that even if we remove the module, its still loaded until a clear
  589. self.assertEqual(self.loader[self.module_key](), (self.count, self.lib_count))
  590. self.loader.clear()
  591. self.assertNotIn(self.module_key, self.loader)
  592. def test_reload_missing_lib(self):
  593. # ensure it doesn't exist
  594. self.assertNotIn(self.module_key, self.loader)
  595. # update both the module and the lib
  596. self.update_module()
  597. self.update_lib()
  598. self.loader.clear()
  599. self.assertEqual(self.loader[self.module_key](), (self.count, self.lib_count))
  600. # remove the lib, this means we should fail to load the module next time
  601. self.rm_lib()
  602. self.loader.clear()
  603. self.assertNotIn(self.module_key, self.loader)
  604. mod_template = '''
  605. def test():
  606. return ({val})
  607. '''
  608. class LazyLoaderModulePackageTest(TestCase):
  609. '''
  610. Test the loader of salt with changing modules
  611. '''
  612. module_name = 'loadertestmodpkg'
  613. module_key = 'loadertestmodpkg.test'
  614. @classmethod
  615. def setUpClass(cls):
  616. cls.opts = salt.config.minion_config(None)
  617. cls.opts['grains'] = salt.loader.grains(cls.opts)
  618. if not os.path.isdir(TMP):
  619. os.makedirs(TMP)
  620. def setUp(self):
  621. self.tmp_dir = tempfile.mkdtemp(dir=TMP)
  622. dirs = salt.loader._module_dirs(copy.deepcopy(self.opts), 'modules', 'module')
  623. dirs.append(self.tmp_dir)
  624. self.loader = salt.loader.LazyLoader(
  625. dirs,
  626. copy.deepcopy(self.opts),
  627. tag='module')
  628. def tearDown(self):
  629. shutil.rmtree(self.tmp_dir)
  630. del self.tmp_dir
  631. del self.loader
  632. @classmethod
  633. def tearDownClass(cls):
  634. del cls.opts
  635. def update_pyfile(self, pyfile, contents):
  636. dirname = os.path.dirname(pyfile)
  637. if not os.path.exists(dirname):
  638. os.makedirs(dirname)
  639. with salt.utils.files.fopen(pyfile, 'wb') as fh:
  640. fh.write(salt.utils.stringutils.to_bytes(contents))
  641. fh.flush()
  642. os.fsync(fh.fileno()) # flush to disk
  643. # pyc files don't like it when we change the original quickly
  644. # since the header bytes only contain the timestamp (granularity of seconds)
  645. # TODO: don't write them? Is *much* slower on re-load (~3x)
  646. # https://docs.python.org/2/library/sys.html#sys.dont_write_bytecode
  647. remove_bytecode(pyfile)
  648. def rm_pyfile(self, pyfile):
  649. os.unlink(pyfile)
  650. remove_bytecode(pyfile)
  651. def update_module(self, relative_path, contents):
  652. self.update_pyfile(os.path.join(self.tmp_dir, relative_path), contents)
  653. def rm_module(self, relative_path):
  654. self.rm_pyfile(os.path.join(self.tmp_dir, relative_path))
  655. def test_module(self):
  656. # ensure it doesn't exist
  657. self.assertNotIn('foo', self.loader)
  658. self.assertNotIn('foo.test', self.loader)
  659. self.update_module('foo.py', mod_template.format(val=1))
  660. self.loader.clear()
  661. self.assertIn('foo.test', self.loader)
  662. self.assertEqual(self.loader['foo.test'](), 1)
  663. def test_package(self):
  664. # ensure it doesn't exist
  665. self.assertNotIn('foo', self.loader)
  666. self.assertNotIn('foo.test', self.loader)
  667. self.update_module('foo/__init__.py', mod_template.format(val=2))
  668. self.loader.clear()
  669. self.assertIn('foo.test', self.loader)
  670. self.assertEqual(self.loader['foo.test'](), 2)
  671. def test_module_package_collision(self):
  672. # ensure it doesn't exist
  673. self.assertNotIn('foo', self.loader)
  674. self.assertNotIn('foo.test', self.loader)
  675. self.update_module('foo.py', mod_template.format(val=3))
  676. self.loader.clear()
  677. self.assertIn('foo.test', self.loader)
  678. self.assertEqual(self.loader['foo.test'](), 3)
  679. self.update_module('foo/__init__.py', mod_template.format(val=4))
  680. self.loader.clear()
  681. self.assertIn('foo.test', self.loader)
  682. self.assertEqual(self.loader['foo.test'](), 4)
  683. deep_init_base = '''
  684. from __future__ import absolute_import
  685. import {0}.top_lib
  686. import {0}.top_lib.mid_lib
  687. import {0}.top_lib.mid_lib.bot_lib
  688. def top():
  689. return {0}.top_lib.test()
  690. def mid():
  691. return {0}.top_lib.mid_lib.test()
  692. def bot():
  693. return {0}.top_lib.mid_lib.bot_lib.test()
  694. '''
  695. class LazyLoaderDeepSubmodReloadingTest(TestCase):
  696. module_name = 'loadertestsubmoddeep'
  697. libs = ('top_lib', 'mid_lib', 'bot_lib')
  698. @classmethod
  699. def setUpClass(cls):
  700. cls.opts = salt.config.minion_config(None)
  701. cls.opts['grains'] = salt.loader.grains(cls.opts)
  702. if not os.path.isdir(TMP):
  703. os.makedirs(TMP)
  704. def setUp(self):
  705. self.tmp_dir = tempfile.mkdtemp(dir=TMP)
  706. os.makedirs(self.module_dir)
  707. self.lib_count = collections.defaultdict(int) # mapping of path -> count
  708. # bootstrap libs
  709. with salt.utils.files.fopen(os.path.join(self.module_dir, '__init__.py'), 'w') as fh:
  710. # No .decode() needed here as deep_init_base is defined as str and
  711. # not bytes.
  712. fh.write(
  713. salt.utils.stringutils.to_str(
  714. deep_init_base.format(self.module_name)
  715. )
  716. )
  717. fh.flush()
  718. os.fsync(fh.fileno()) # flush to disk
  719. self.lib_paths = {}
  720. dir_path = self.module_dir
  721. for lib_name in self.libs:
  722. dir_path = os.path.join(dir_path, lib_name)
  723. self.lib_paths[lib_name] = dir_path
  724. os.makedirs(dir_path)
  725. self.update_lib(lib_name)
  726. opts = copy.deepcopy(self.opts)
  727. dirs = salt.loader._module_dirs(opts, 'modules', 'module')
  728. dirs.append(self.tmp_dir)
  729. self.utils = salt.loader.utils(opts)
  730. self.proxy = salt.loader.proxy(opts)
  731. self.minion_mods = salt.loader.minion_mods(opts)
  732. self.loader = salt.loader.LazyLoader(
  733. dirs,
  734. copy.deepcopy(opts),
  735. tag='module',
  736. pack={'__utils__': self.utils,
  737. '__proxy__': self.proxy,
  738. '__salt__': self.minion_mods})
  739. self.assertIn('{0}.top'.format(self.module_name), self.loader)
  740. def tearDown(self):
  741. shutil.rmtree(self.tmp_dir)
  742. del self.tmp_dir
  743. del self.lib_paths
  744. del self.utils
  745. del self.proxy
  746. del self.minion_mods
  747. del self.loader
  748. del self.lib_count
  749. @classmethod
  750. def tearDownClass(cls):
  751. del cls.opts
  752. @property
  753. def module_dir(self):
  754. return os.path.join(self.tmp_dir, self.module_name)
  755. def update_lib(self, lib_name):
  756. for modname in list(sys.modules):
  757. if modname.startswith(self.module_name):
  758. del sys.modules[modname]
  759. path = os.path.join(self.lib_paths[lib_name], '__init__.py')
  760. self.lib_count[lib_name] += 1
  761. with salt.utils.files.fopen(path, 'wb') as fh:
  762. fh.write(
  763. salt.utils.stringutils.to_bytes(
  764. submodule_lib_template.format(count=self.lib_count[lib_name])
  765. )
  766. )
  767. fh.flush()
  768. os.fsync(fh.fileno()) # flush to disk
  769. # pyc files don't like it when we change the original quickly
  770. # since the header bytes only contain the timestamp (granularity of seconds)
  771. # TODO: don't write them? Is *much* slower on re-load (~3x)
  772. # https://docs.python.org/2/library/sys.html#sys.dont_write_bytecode
  773. remove_bytecode(path)
  774. def test_basic(self):
  775. self.assertIn('{0}.top'.format(self.module_name), self.loader)
  776. def _verify_libs(self):
  777. for lib in self.libs:
  778. self.assertEqual(self.loader['{0}.{1}'.format(self.module_name, lib.replace('_lib', ''))](),
  779. self.lib_count[lib])
  780. def test_reload(self):
  781. '''
  782. Make sure that we can reload all libraries of arbitrary depth
  783. '''
  784. self._verify_libs()
  785. # update them all
  786. for lib in self.libs:
  787. for x in range(5):
  788. self.update_lib(lib)
  789. self.loader.clear()
  790. self._verify_libs()
  791. class LoaderGlobalsTest(ModuleCase):
  792. '''
  793. Test all of the globals that the loader is responsible for adding to modules
  794. This shouldn't be done here, but should rather be done per module type (in the cases where they are used)
  795. so they can check ALL globals that they have (or should have) access to.
  796. This is intended as a shorter term way of testing these so we don't break the loader
  797. '''
  798. def _verify_globals(self, mod_dict):
  799. '''
  800. Verify that the globals listed in the doc string (from the test) are in these modules
  801. '''
  802. # find the globals
  803. global_vars = []
  804. for val in six.itervalues(mod_dict):
  805. # only find salty globals
  806. if val.__module__.startswith('salt.loaded'):
  807. if hasattr(val, '__globals__'):
  808. if hasattr(val, '__wrapped__'):
  809. global_vars.append(sys.modules[val.__module__].__dict__)
  810. else:
  811. global_vars.append(val.__globals__)
  812. # if we couldn't find any, then we have no modules -- so something is broken
  813. self.assertNotEqual(global_vars, [], msg='No modules were loaded.')
  814. # get the names of the globals you should have
  815. func_name = inspect.stack()[1][3]
  816. names = next(six.itervalues(salt.utils.yaml.safe_load(getattr(self, func_name).__doc__)))
  817. # Now, test each module!
  818. for item in global_vars:
  819. for name in names:
  820. self.assertIn(name, list(item.keys()))
  821. def test_auth(self):
  822. '''
  823. Test that auth mods have:
  824. - __pillar__
  825. - __grains__
  826. - __salt__
  827. - __context__
  828. '''
  829. self._verify_globals(salt.loader.auth(self.master_opts))
  830. def test_runners(self):
  831. '''
  832. Test that runners have:
  833. - __pillar__
  834. - __salt__
  835. - __opts__
  836. - __grains__
  837. - __context__
  838. '''
  839. self._verify_globals(salt.loader.runner(self.master_opts))
  840. def test_returners(self):
  841. '''
  842. Test that returners have:
  843. - __salt__
  844. - __opts__
  845. - __pillar__
  846. - __grains__
  847. - __context__
  848. '''
  849. self._verify_globals(salt.loader.returners(self.master_opts, {}))
  850. def test_pillars(self):
  851. '''
  852. Test that pillars have:
  853. - __salt__
  854. - __opts__
  855. - __pillar__
  856. - __grains__
  857. - __context__
  858. '''
  859. self._verify_globals(salt.loader.pillars(self.master_opts, {}))
  860. def test_tops(self):
  861. '''
  862. Test that tops have: []
  863. '''
  864. self._verify_globals(salt.loader.tops(self.master_opts))
  865. def test_outputters(self):
  866. '''
  867. Test that outputters have:
  868. - __opts__
  869. - __pillar__
  870. - __grains__
  871. - __context__
  872. '''
  873. self._verify_globals(salt.loader.outputters(self.master_opts))
  874. def test_serializers(self):
  875. '''
  876. Test that serializers have: []
  877. '''
  878. self._verify_globals(salt.loader.serializers(self.master_opts))
  879. def test_states(self):
  880. '''
  881. Test that states have:
  882. - __pillar__
  883. - __salt__
  884. - __opts__
  885. - __grains__
  886. - __context__
  887. '''
  888. self._verify_globals(salt.loader.states(self.master_opts, {}, {}, {}))
  889. def test_renderers(self):
  890. '''
  891. Test that renderers have:
  892. - __salt__ # Execution functions (i.e. __salt__['test.echo']('foo'))
  893. - __grains__ # Grains (i.e. __grains__['os'])
  894. - __pillar__ # Pillar data (i.e. __pillar__['foo'])
  895. - __opts__ # Minion configuration options
  896. - __context__ # Context dict shared amongst all modules of the same type
  897. '''
  898. self._verify_globals(salt.loader.render(self.master_opts, {}))
  899. class RawModTest(TestCase):
  900. '''
  901. Test the interface of raw_mod
  902. '''
  903. def setUp(self):
  904. self.opts = salt.config.minion_config(None)
  905. def tearDown(self):
  906. del self.opts
  907. def test_basic(self):
  908. testmod = salt.loader.raw_mod(self.opts, 'test', None)
  909. for k, v in six.iteritems(testmod):
  910. self.assertEqual(k.split('.')[0], 'test')
  911. def test_bad_name(self):
  912. testmod = salt.loader.raw_mod(self.opts, 'module_we_do_not_have', None)
  913. self.assertEqual(testmod, {})
  914. class NetworkUtilsTestCase(ModuleCase):
  915. def test_is_private(self):
  916. mod = salt.loader.raw_mod(self.minion_opts, 'network', None)
  917. self.assertTrue(mod['network.is_private']('10.0.0.1'), True)
  918. def test_is_loopback(self):
  919. mod = salt.loader.raw_mod(self.minion_opts, 'network', None)
  920. self.assertTrue(mod['network.is_loopback']('127.0.0.1'), True)
  921. class LazyLoaderOptimizationOrderTest(TestCase):
  922. '''
  923. Test the optimization order priority in the loader (PY3)
  924. '''
  925. module_name = 'lazyloadertest'
  926. module_content = textwrap.dedent('''\
  927. # -*- coding: utf-8 -*-
  928. from __future__ import absolute_import
  929. def test():
  930. return True
  931. ''')
  932. @classmethod
  933. def setUpClass(cls):
  934. cls.opts = salt.config.minion_config(None)
  935. cls.opts['grains'] = salt.loader.grains(cls.opts)
  936. def setUp(self):
  937. # Setup the module
  938. self.module_dir = tempfile.mkdtemp(dir=TMP)
  939. self.module_file = os.path.join(self.module_dir,
  940. '{0}.py'.format(self.module_name))
  941. def _get_loader(self, order=None):
  942. opts = copy.deepcopy(self.opts)
  943. if order is not None:
  944. opts['optimization_order'] = order
  945. # Return a loader
  946. return salt.loader.LazyLoader([self.module_dir], opts, tag='module')
  947. def _get_module_filename(self):
  948. # The act of referencing the loader entry forces the module to be
  949. # loaded by the LazyDict.
  950. mod_fullname = self.loader[next(iter(self.loader))].__module__
  951. return sys.modules[mod_fullname].__file__
  952. def _expected(self, optimize=0):
  953. if six.PY3:
  954. return 'lazyloadertest.cpython-{0}{1}{2}.pyc'.format(
  955. sys.version_info[0],
  956. sys.version_info[1],
  957. '' if not optimize else '.opt-{0}'.format(optimize)
  958. )
  959. else:
  960. return 'lazyloadertest.pyc'
  961. def _write_module_file(self):
  962. with salt.utils.files.fopen(self.module_file, 'w') as fh:
  963. fh.write(self.module_content)
  964. fh.flush()
  965. os.fsync(fh.fileno())
  966. def _byte_compile(self):
  967. if salt.loader.USE_IMPORTLIB:
  968. # Skip this check as "optimize" is unique to PY3's compileall
  969. # module, and this will be a false error when Pylint is run on
  970. # Python 2.
  971. # pylint: disable=unexpected-keyword-arg
  972. compileall.compile_file(self.module_file, quiet=1, optimize=0)
  973. compileall.compile_file(self.module_file, quiet=1, optimize=1)
  974. compileall.compile_file(self.module_file, quiet=1, optimize=2)
  975. # pylint: enable=unexpected-keyword-arg
  976. else:
  977. compileall.compile_file(self.module_file, quiet=1)
  978. def _test_optimization_order(self, order):
  979. self._write_module_file()
  980. self._byte_compile()
  981. # Clean up the original file so that we can be assured we're only
  982. # loading the byte-compiled files(s).
  983. os.remove(self.module_file)
  984. self.loader = self._get_loader(order)
  985. filename = self._get_module_filename()
  986. basename = os.path.basename(filename)
  987. assert basename == self._expected(order[0]), basename
  988. if not salt.loader.USE_IMPORTLIB:
  989. # We are only testing multiple optimization levels on Python 3.5+
  990. return
  991. # Remove the file and make a new loader. We should now load the
  992. # byte-compiled file with an optimization level matching the 2nd
  993. # element of the order list.
  994. os.remove(filename)
  995. self.loader = self._get_loader(order)
  996. filename = self._get_module_filename()
  997. basename = os.path.basename(filename)
  998. assert basename == self._expected(order[1]), basename
  999. # Remove the file and make a new loader. We should now load the
  1000. # byte-compiled file with an optimization level matching the 3rd
  1001. # element of the order list.
  1002. os.remove(filename)
  1003. self.loader = self._get_loader(order)
  1004. filename = self._get_module_filename()
  1005. basename = os.path.basename(filename)
  1006. assert basename == self._expected(order[2]), basename
  1007. def test_optimization_order(self):
  1008. '''
  1009. Test the optimization_order config param
  1010. '''
  1011. self._test_optimization_order([0, 1, 2])
  1012. self._test_optimization_order([0, 2, 1])
  1013. if salt.loader.USE_IMPORTLIB:
  1014. # optimization_order only supported on Python 3.5+, earlier
  1015. # releases only support unoptimized .pyc files.
  1016. self._test_optimization_order([1, 2, 0])
  1017. self._test_optimization_order([1, 0, 2])
  1018. self._test_optimization_order([2, 0, 1])
  1019. self._test_optimization_order([2, 1, 0])
  1020. def test_load_source_file(self):
  1021. '''
  1022. Make sure that .py files are preferred over .pyc files
  1023. '''
  1024. self._write_module_file()
  1025. self._byte_compile()
  1026. self.loader = self._get_loader()
  1027. filename = self._get_module_filename()
  1028. basename = os.path.basename(filename)
  1029. expected = 'lazyloadertest.py' if six.PY3 else 'lazyloadertest.pyc'
  1030. assert basename == expected, basename