test_loader.py 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621
  1. """
  2. unit.loader
  3. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  4. Test Salt's loader
  5. """
  6. import collections
  7. import compileall
  8. import copy
  9. import imp
  10. import inspect
  11. import logging
  12. import os
  13. import shutil
  14. import sys
  15. import tempfile
  16. import textwrap
  17. import salt.config
  18. import salt.loader
  19. import salt.utils.files
  20. import salt.utils.stringutils
  21. # pylint: disable=import-error,no-name-in-module,redefined-builtin
  22. from salt.ext import six
  23. from salt.ext.six.moves import range
  24. from tests.support.case import ModuleCase
  25. # Import Salt Testing libs
  26. from tests.support.helpers import slowTest
  27. from tests.support.mock import MagicMock, patch
  28. from tests.support.runtests import RUNTIME_VARS
  29. from tests.support.unit import TestCase
  30. # pylint: enable=no-name-in-module,redefined-builtin
  31. log = logging.getLogger(__name__)
  32. def remove_bytecode(module_path):
  33. paths = [module_path + "c"]
  34. if hasattr(imp, "get_tag"):
  35. modname, ext = os.path.splitext(module_path.split(os.sep)[-1])
  36. paths.append(
  37. os.path.join(
  38. os.path.dirname(module_path),
  39. "__pycache__",
  40. "{}.{}.pyc".format(modname, imp.get_tag()),
  41. )
  42. )
  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(RUNTIME_VARS.TMP):
  66. os.makedirs(RUNTIME_VARS.TMP)
  67. cls.utils = salt.loader.utils(cls.opts)
  68. cls.proxy = salt.loader.proxy(cls.opts)
  69. cls.funcs = salt.loader.minion_mods(cls.opts, utils=cls.utils, proxy=cls.proxy)
  70. def setUp(self):
  71. # Setup the module
  72. self.module_dir = tempfile.mkdtemp(dir=RUNTIME_VARS.TMP)
  73. self.addCleanup(shutil.rmtree, self.module_dir, ignore_errors=True)
  74. self.module_file = os.path.join(
  75. self.module_dir, "{}.py".format(self.module_name)
  76. )
  77. with salt.utils.files.fopen(self.module_file, "w") as fh:
  78. fh.write(salt.utils.stringutils.to_str(loader_template))
  79. fh.flush()
  80. os.fsync(fh.fileno())
  81. # Invoke the loader
  82. self.loader = salt.loader.LazyLoader(
  83. [self.module_dir],
  84. copy.deepcopy(self.opts),
  85. pack={
  86. "__utils__": self.utils,
  87. "__salt__": self.funcs,
  88. "__proxy__": self.proxy,
  89. },
  90. tag="module",
  91. )
  92. def tearDown(self):
  93. del self.module_dir
  94. del self.module_file
  95. del self.loader
  96. @classmethod
  97. def tearDownClass(cls):
  98. del cls.opts
  99. del cls.funcs
  100. del cls.utils
  101. del cls.proxy
  102. @slowTest
  103. def test_depends(self):
  104. """
  105. Test that the depends decorator works properly
  106. """
  107. # Make sure depends correctly allowed a function to load. If this
  108. # results in a KeyError, the decorator is broken.
  109. self.assertTrue(inspect.isfunction(self.loader[self.module_name + ".loaded"]))
  110. # Make sure depends correctly kept a function from loading
  111. self.assertTrue(self.module_name + ".not_loaded" not in self.loader)
  112. loader_template_module = """
  113. import my_utils
  114. def run():
  115. return my_utils.run()
  116. """
  117. loader_template_utils = """
  118. def run():
  119. return True
  120. """
  121. class LazyLoaderUtilsTest(TestCase):
  122. """
  123. Test the loader
  124. """
  125. module_name = "lazyloaderutilstest"
  126. utils_name = "my_utils"
  127. @classmethod
  128. def setUpClass(cls):
  129. cls.opts = salt.config.minion_config(None)
  130. cls.opts["grains"] = salt.loader.grains(cls.opts)
  131. if not os.path.isdir(RUNTIME_VARS.TMP):
  132. os.makedirs(RUNTIME_VARS.TMP)
  133. def setUp(self):
  134. # Setup the module
  135. self.module_dir = tempfile.mkdtemp(dir=RUNTIME_VARS.TMP)
  136. self.module_file = os.path.join(
  137. self.module_dir, "{}.py".format(self.module_name)
  138. )
  139. with salt.utils.files.fopen(self.module_file, "w") as fh:
  140. fh.write(salt.utils.stringutils.to_str(loader_template_module))
  141. fh.flush()
  142. os.fsync(fh.fileno())
  143. self.utils_dir = tempfile.mkdtemp(dir=RUNTIME_VARS.TMP)
  144. self.utils_file = os.path.join(self.utils_dir, "{}.py".format(self.utils_name))
  145. with salt.utils.files.fopen(self.utils_file, "w") as fh:
  146. fh.write(salt.utils.stringutils.to_str(loader_template_utils))
  147. fh.flush()
  148. os.fsync(fh.fileno())
  149. def tearDown(self):
  150. shutil.rmtree(self.module_dir)
  151. if os.path.isdir(self.module_dir):
  152. shutil.rmtree(self.module_dir)
  153. shutil.rmtree(self.utils_dir)
  154. if os.path.isdir(self.utils_dir):
  155. shutil.rmtree(self.utils_dir)
  156. del self.module_dir
  157. del self.module_file
  158. del self.utils_dir
  159. del self.utils_file
  160. if self.module_name in sys.modules:
  161. del sys.modules[self.module_name]
  162. if self.utils_name in sys.modules:
  163. del sys.modules[self.utils_name]
  164. @classmethod
  165. def tearDownClass(cls):
  166. del cls.opts
  167. def test_utils_found(self):
  168. """
  169. Test that the extra module directory is available for imports
  170. """
  171. loader = salt.loader.LazyLoader(
  172. [self.module_dir],
  173. copy.deepcopy(self.opts),
  174. tag="module",
  175. extra_module_dirs=[self.utils_dir],
  176. )
  177. self.assertTrue(inspect.isfunction(loader[self.module_name + ".run"]))
  178. self.assertTrue(loader[self.module_name + ".run"]())
  179. def test_utils_not_found(self):
  180. """
  181. Test that the extra module directory is not available for imports
  182. """
  183. loader = salt.loader.LazyLoader(
  184. [self.module_dir], copy.deepcopy(self.opts), tag="module"
  185. )
  186. self.assertTrue(self.module_name + ".run" not in loader)
  187. class LazyLoaderVirtualEnabledTest(TestCase):
  188. """
  189. Test the base loader of salt.
  190. """
  191. @classmethod
  192. def setUpClass(cls):
  193. cls.opts = salt.config.minion_config(None)
  194. cls.opts["disable_modules"] = ["pillar"]
  195. cls.opts["grains"] = salt.loader.grains(cls.opts)
  196. cls.utils = salt.loader.utils(copy.deepcopy(cls.opts))
  197. cls.proxy = salt.loader.proxy(cls.opts)
  198. cls.funcs = salt.loader.minion_mods(cls.opts, utils=cls.utils, proxy=cls.proxy)
  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. pack={
  204. "__utils__": self.utils,
  205. "__salt__": self.funcs,
  206. "__proxy__": self.proxy,
  207. },
  208. tag="module",
  209. )
  210. def tearDown(self):
  211. del self.loader
  212. @classmethod
  213. def tearDownClass(cls):
  214. del cls.opts
  215. del cls.funcs
  216. del cls.utils
  217. del cls.proxy
  218. @slowTest
  219. def test_basic(self):
  220. """
  221. Ensure that it only loads stuff when needed
  222. """
  223. # make sure it starts empty
  224. self.assertEqual(self.loader._dict, {})
  225. # get something, and make sure its a func
  226. self.assertTrue(inspect.isfunction(self.loader["test.ping"]))
  227. # make sure we only loaded "test" functions
  228. for key, val in self.loader._dict.items():
  229. self.assertEqual(key.split(".", 1)[0], "test")
  230. # make sure the depends thing worked (double check of the depends testing,
  231. # since the loader does the calling magically
  232. self.assertFalse("test.missing_func" in self.loader._dict)
  233. def test_badkey(self):
  234. with self.assertRaises(KeyError):
  235. self.loader[None] # pylint: disable=W0104
  236. with self.assertRaises(KeyError):
  237. self.loader[1] # pylint: disable=W0104
  238. @slowTest
  239. def test_disable(self):
  240. self.assertNotIn("pillar.items", self.loader)
  241. @slowTest
  242. def test_len_load(self):
  243. """
  244. Since LazyLoader is a MutableMapping, if someone asks for len() we have
  245. to load all
  246. """
  247. self.assertEqual(self.loader._dict, {})
  248. len(self.loader) # force a load all
  249. self.assertNotEqual(self.loader._dict, {})
  250. @slowTest
  251. def test_iter_load(self):
  252. """
  253. Since LazyLoader is a MutableMapping, if someone asks to iterate we have
  254. to load all
  255. """
  256. self.assertEqual(self.loader._dict, {})
  257. # force a load all
  258. for key, func in self.loader.items():
  259. break
  260. self.assertNotEqual(self.loader._dict, {})
  261. def test_context(self):
  262. """
  263. Make sure context is shared across modules
  264. """
  265. # make sure it starts empty
  266. self.assertEqual(self.loader._dict, {})
  267. # get something, and make sure its a func
  268. func = self.loader["test.ping"]
  269. with patch.dict(func.__globals__["__context__"], {"foo": "bar"}):
  270. self.assertEqual(
  271. self.loader["test.echo"].__globals__["__context__"]["foo"], "bar"
  272. )
  273. self.assertEqual(
  274. self.loader["grains.get"].__globals__["__context__"]["foo"], "bar"
  275. )
  276. def test_globals(self):
  277. func_globals = self.loader["test.ping"].__globals__
  278. self.assertEqual(func_globals["__grains__"], self.opts.get("grains", {}))
  279. self.assertEqual(func_globals["__pillar__"], self.opts.get("pillar", {}))
  280. # the opts passed into modules is at least a subset of the whole opts
  281. for key, val in func_globals["__opts__"].items():
  282. if (
  283. key in salt.config.DEFAULT_MASTER_OPTS
  284. and key not in salt.config.DEFAULT_MINION_OPTS
  285. ):
  286. # We loaded the minion opts, but somewhere in the code, the master options got pulled in
  287. # Let's just not check for equality since the option won't even exist in the loaded
  288. # minion options
  289. continue
  290. if (
  291. key not in salt.config.DEFAULT_MASTER_OPTS
  292. and key not in salt.config.DEFAULT_MINION_OPTS
  293. ):
  294. # This isn't even a default configuration setting, lets carry on
  295. continue
  296. self.assertEqual(self.opts[key], val)
  297. def test_pack(self):
  298. self.loader.pack["__foo__"] = "bar"
  299. func_globals = self.loader["test.ping"].__globals__
  300. self.assertEqual(func_globals["__foo__"], "bar")
  301. @slowTest
  302. def test_virtual(self):
  303. self.assertNotIn("test_virtual.ping", self.loader)
  304. class LazyLoaderVirtualDisabledTest(TestCase):
  305. """
  306. Test the loader of salt without __virtual__
  307. """
  308. @classmethod
  309. def setUpClass(cls):
  310. cls.opts = salt.config.minion_config(None)
  311. cls.opts["grains"] = salt.loader.grains(cls.opts)
  312. cls.utils = salt.loader.utils(copy.deepcopy(cls.opts))
  313. cls.proxy = salt.loader.proxy(cls.opts)
  314. cls.funcs = salt.loader.minion_mods(cls.opts, utils=cls.utils, proxy=cls.proxy)
  315. def setUp(self):
  316. self.loader = salt.loader.LazyLoader(
  317. salt.loader._module_dirs(copy.deepcopy(self.opts), "modules", "module"),
  318. copy.deepcopy(self.opts),
  319. tag="module",
  320. pack={
  321. "__utils__": self.utils,
  322. "__salt__": self.funcs,
  323. "__proxy__": self.proxy,
  324. },
  325. virtual_enable=False,
  326. )
  327. def tearDown(self):
  328. del self.loader
  329. @classmethod
  330. def tearDownClass(cls):
  331. del cls.opts
  332. del cls.utils
  333. del cls.funcs
  334. del cls.proxy
  335. @slowTest
  336. def test_virtual(self):
  337. self.assertTrue(inspect.isfunction(self.loader["test_virtual.ping"]))
  338. class LazyLoaderWhitelistTest(TestCase):
  339. """
  340. Test the loader of salt with a whitelist
  341. """
  342. @classmethod
  343. def setUpClass(cls):
  344. cls.opts = salt.config.minion_config(None)
  345. cls.opts["grains"] = salt.loader.grains(cls.opts)
  346. cls.utils = salt.loader.utils(copy.deepcopy(cls.opts))
  347. cls.proxy = salt.loader.proxy(cls.opts)
  348. cls.funcs = salt.loader.minion_mods(cls.opts, utils=cls.utils, proxy=cls.proxy)
  349. def setUp(self):
  350. self.loader = salt.loader.LazyLoader(
  351. salt.loader._module_dirs(copy.deepcopy(self.opts), "modules", "module"),
  352. copy.deepcopy(self.opts),
  353. tag="module",
  354. pack={
  355. "__utils__": self.utils,
  356. "__salt__": self.funcs,
  357. "__proxy__": self.proxy,
  358. },
  359. whitelist=["test", "pillar"],
  360. )
  361. def tearDown(self):
  362. del self.loader
  363. @classmethod
  364. def tearDownClass(cls):
  365. del cls.opts
  366. del cls.funcs
  367. del cls.utils
  368. del cls.proxy
  369. @slowTest
  370. def test_whitelist(self):
  371. self.assertTrue(inspect.isfunction(self.loader["test.ping"]))
  372. self.assertTrue(inspect.isfunction(self.loader["pillar.get"]))
  373. self.assertNotIn("grains.get", self.loader)
  374. class LazyLoaderGrainsBlacklistTest(TestCase):
  375. """
  376. Test the loader of grains with a blacklist
  377. """
  378. def setUp(self):
  379. self.opts = salt.config.minion_config(None)
  380. def tearDown(self):
  381. del self.opts
  382. @slowTest
  383. def test_whitelist(self):
  384. opts = copy.deepcopy(self.opts)
  385. opts["grains_blacklist"] = ["master", "os*", "ipv[46]"]
  386. grains = salt.loader.grains(opts)
  387. self.assertNotIn("master", grains)
  388. self.assertNotIn("os", {g[:2] for g in list(grains)})
  389. self.assertNotIn("ipv4", grains)
  390. self.assertNotIn("ipv6", grains)
  391. class LazyLoaderSingleItem(TestCase):
  392. """
  393. Test loading a single item via the _load() function
  394. """
  395. @classmethod
  396. def setUpClass(cls):
  397. cls.opts = salt.config.minion_config(None)
  398. cls.opts["grains"] = salt.loader.grains(cls.opts)
  399. cls.utils = salt.loader.utils(copy.deepcopy(cls.opts))
  400. cls.proxy = salt.loader.proxy(cls.opts)
  401. cls.funcs = salt.loader.minion_mods(cls.opts, utils=cls.utils, proxy=cls.proxy)
  402. @classmethod
  403. def tearDownClass(cls):
  404. del cls.opts
  405. del cls.funcs
  406. del cls.utils
  407. del cls.proxy
  408. def setUp(self):
  409. self.loader = salt.loader.LazyLoader(
  410. salt.loader._module_dirs(copy.deepcopy(self.opts), "modules", "module"),
  411. copy.deepcopy(self.opts),
  412. pack={
  413. "__utils__": self.utils,
  414. "__salt__": self.funcs,
  415. "__proxy__": self.proxy,
  416. },
  417. tag="module",
  418. )
  419. def tearDown(self):
  420. del self.loader
  421. def test_single_item_no_dot(self):
  422. """
  423. Checks that a KeyError is raised when the function key does not contain a '.'
  424. """
  425. key = "testing_no_dot"
  426. expected = "The key '{}' should contain a '.'".format(key)
  427. with self.assertRaises(KeyError) as err:
  428. inspect.isfunction(self.loader["testing_no_dot"])
  429. result = err.exception.args[0]
  430. assert result == expected, result
  431. module_template = """
  432. __load__ = ['test', 'test_alias']
  433. __func_alias__ = dict(test_alias='working_alias')
  434. from salt.utils.decorators import depends
  435. def test():
  436. return {count}
  437. def test_alias():
  438. return True
  439. def test2():
  440. return True
  441. @depends('non_existantmodulename')
  442. def test3():
  443. return True
  444. @depends('non_existantmodulename', fallback_function=test)
  445. def test4():
  446. return True
  447. """
  448. class LazyLoaderReloadingTest(TestCase):
  449. """
  450. Test the loader of salt with changing modules
  451. """
  452. module_name = "loadertest"
  453. module_key = "loadertest.test"
  454. @classmethod
  455. def setUpClass(cls):
  456. cls.opts = salt.config.minion_config(None)
  457. cls.opts["grains"] = salt.loader.grains(cls.opts)
  458. if not os.path.isdir(RUNTIME_VARS.TMP):
  459. os.makedirs(RUNTIME_VARS.TMP)
  460. def setUp(self):
  461. self.tmp_dir = tempfile.mkdtemp(dir=RUNTIME_VARS.TMP)
  462. self.addCleanup(shutil.rmtree, self.tmp_dir, ignore_errors=True)
  463. self.count = 0
  464. opts = copy.deepcopy(self.opts)
  465. dirs = salt.loader._module_dirs(opts, "modules", "module")
  466. dirs.append(self.tmp_dir)
  467. self.utils = salt.loader.utils(opts)
  468. self.proxy = salt.loader.proxy(opts)
  469. self.minion_mods = salt.loader.minion_mods(opts)
  470. self.loader = salt.loader.LazyLoader(
  471. dirs,
  472. opts,
  473. tag="module",
  474. pack={
  475. "__utils__": self.utils,
  476. "__proxy__": self.proxy,
  477. "__salt__": self.minion_mods,
  478. },
  479. )
  480. def tearDown(self):
  481. for attrname in ("tmp_dir", "utils", "proxy", "loader", "minion_mods", "utils"):
  482. try:
  483. delattr(self, attrname)
  484. except AttributeError:
  485. continue
  486. @classmethod
  487. def tearDownClass(cls):
  488. del cls.opts
  489. def update_module(self):
  490. self.count += 1
  491. with salt.utils.files.fopen(self.module_path, "wb") as fh:
  492. fh.write(
  493. salt.utils.stringutils.to_bytes(
  494. module_template.format(count=self.count)
  495. )
  496. )
  497. fh.flush()
  498. os.fsync(fh.fileno()) # flush to disk
  499. # pyc files don't like it when we change the original quickly
  500. # since the header bytes only contain the timestamp (granularity of seconds)
  501. # TODO: don't write them? Is *much* slower on re-load (~3x)
  502. # https://docs.python.org/2/library/sys.html#sys.dont_write_bytecode
  503. remove_bytecode(self.module_path)
  504. def rm_module(self):
  505. os.unlink(self.module_path)
  506. remove_bytecode(self.module_path)
  507. @property
  508. def module_path(self):
  509. return os.path.join(self.tmp_dir, "{}.py".format(self.module_name))
  510. @slowTest
  511. def test_alias(self):
  512. """
  513. Make sure that you can access alias-d modules
  514. """
  515. # ensure it doesn't exist
  516. self.assertNotIn(self.module_key, self.loader)
  517. self.update_module()
  518. self.assertNotIn("{}.test_alias".format(self.module_name), self.loader)
  519. self.assertTrue(
  520. inspect.isfunction(self.loader["{}.working_alias".format(self.module_name)])
  521. )
  522. @slowTest
  523. def test_clear(self):
  524. self.assertTrue(inspect.isfunction(self.loader["test.ping"]))
  525. self.update_module() # write out out custom module
  526. self.loader.clear() # clear the loader dict
  527. # force a load of our module
  528. self.assertTrue(inspect.isfunction(self.loader[self.module_key]))
  529. # make sure we only loaded our custom module
  530. # which means that we did correctly refresh the file mapping
  531. for k, v in self.loader._dict.items():
  532. self.assertTrue(k.startswith(self.module_name))
  533. @slowTest
  534. def test_load(self):
  535. # ensure it doesn't exist
  536. self.assertNotIn(self.module_key, self.loader)
  537. self.update_module()
  538. self.assertTrue(inspect.isfunction(self.loader[self.module_key]))
  539. @slowTest
  540. def test__load__(self):
  541. """
  542. If a module specifies __load__ we should only load/expose those modules
  543. """
  544. self.update_module()
  545. # ensure it doesn't exist
  546. self.assertNotIn(self.module_key + "2", self.loader)
  547. @slowTest
  548. def test__load__and_depends(self):
  549. """
  550. If a module specifies __load__ we should only load/expose those modules
  551. """
  552. self.update_module()
  553. # ensure it doesn't exist
  554. self.assertNotIn(self.module_key + "3", self.loader)
  555. self.assertNotIn(self.module_key + "4", self.loader)
  556. @slowTest
  557. def test_reload(self):
  558. # ensure it doesn't exist
  559. self.assertNotIn(self.module_key, self.loader)
  560. # make sure it updates correctly
  561. for x in range(1, 3):
  562. self.update_module()
  563. self.loader.clear()
  564. self.assertEqual(self.loader[self.module_key](), self.count)
  565. self.rm_module()
  566. # make sure that even if we remove the module, its still loaded until a clear
  567. self.assertEqual(self.loader[self.module_key](), self.count)
  568. self.loader.clear()
  569. self.assertNotIn(self.module_key, self.loader)
  570. virtual_aliases = ("loadertest2", "loadertest3")
  571. virtual_alias_module_template = """
  572. __virtual_aliases__ = {}
  573. def test():
  574. return True
  575. """.format(
  576. virtual_aliases
  577. )
  578. class LazyLoaderVirtualAliasTest(TestCase):
  579. """
  580. Test the loader of salt with changing modules
  581. """
  582. module_name = "loadertest"
  583. @classmethod
  584. def setUpClass(cls):
  585. cls.opts = salt.config.minion_config(None)
  586. cls.opts["grains"] = salt.loader.grains(cls.opts)
  587. if not os.path.isdir(RUNTIME_VARS.TMP):
  588. os.makedirs(RUNTIME_VARS.TMP)
  589. def setUp(self):
  590. self.tmp_dir = tempfile.mkdtemp(dir=RUNTIME_VARS.TMP)
  591. opts = copy.deepcopy(self.opts)
  592. dirs = salt.loader._module_dirs(opts, "modules", "module")
  593. dirs.append(self.tmp_dir)
  594. self.utils = salt.loader.utils(opts)
  595. self.proxy = salt.loader.proxy(opts)
  596. self.minion_mods = salt.loader.minion_mods(opts)
  597. self.loader = salt.loader.LazyLoader(
  598. dirs,
  599. opts,
  600. tag="module",
  601. pack={
  602. "__utils__": self.utils,
  603. "__proxy__": self.proxy,
  604. "__salt__": self.minion_mods,
  605. },
  606. )
  607. def tearDown(self):
  608. del self.tmp_dir
  609. del self.utils
  610. del self.proxy
  611. del self.minion_mods
  612. del self.loader
  613. @classmethod
  614. def tearDownClass(cls):
  615. del cls.opts
  616. def update_module(self):
  617. with salt.utils.files.fopen(self.module_path, "wb") as fh:
  618. fh.write(salt.utils.stringutils.to_bytes(virtual_alias_module_template))
  619. fh.flush()
  620. os.fsync(fh.fileno()) # flush to disk
  621. # pyc files don't like it when we change the original quickly
  622. # since the header bytes only contain the timestamp (granularity of seconds)
  623. # TODO: don't write them? Is *much* slower on re-load (~3x)
  624. # https://docs.python.org/2/library/sys.html#sys.dont_write_bytecode
  625. remove_bytecode(self.module_path)
  626. @property
  627. def module_path(self):
  628. return os.path.join(self.tmp_dir, "{}.py".format(self.module_name))
  629. @slowTest
  630. def test_virtual_alias(self):
  631. """
  632. Test the __virtual_alias__ feature
  633. """
  634. self.update_module()
  635. mod_names = [self.module_name] + list(virtual_aliases)
  636. for mod_name in mod_names:
  637. func_name = ".".join((mod_name, "test"))
  638. log.debug("Running %s (dict attribute)", func_name)
  639. self.assertTrue(self.loader[func_name]())
  640. log.debug("Running %s (loader attribute)", func_name)
  641. self.assertTrue(getattr(self.loader, mod_name).test())
  642. submodule_template = """
  643. from __future__ import absolute_import
  644. import {0}.lib
  645. def test():
  646. return ({count}, {0}.lib.test())
  647. """
  648. submodule_lib_template = """
  649. def test():
  650. return {count}
  651. """
  652. class LazyLoaderSubmodReloadingTest(TestCase):
  653. """
  654. Test the loader of salt with changing modules
  655. """
  656. module_name = "loadertestsubmod"
  657. module_key = "loadertestsubmod.test"
  658. @classmethod
  659. def setUpClass(cls):
  660. cls.opts = salt.config.minion_config(None)
  661. cls.opts["grains"] = salt.loader.grains(cls.opts)
  662. if not os.path.isdir(RUNTIME_VARS.TMP):
  663. os.makedirs(RUNTIME_VARS.TMP)
  664. def setUp(self):
  665. self.tmp_dir = tempfile.mkdtemp(dir=RUNTIME_VARS.TMP)
  666. self.addCleanup(shutil.rmtree, self.tmp_dir, ignore_errors=True)
  667. os.makedirs(self.module_dir)
  668. self.count = 0
  669. self.lib_count = 0
  670. opts = copy.deepcopy(self.opts)
  671. dirs = salt.loader._module_dirs(opts, "modules", "module")
  672. dirs.append(self.tmp_dir)
  673. self.utils = salt.loader.utils(opts)
  674. self.proxy = salt.loader.proxy(opts)
  675. self.minion_mods = salt.loader.minion_mods(opts)
  676. self.loader = salt.loader.LazyLoader(
  677. dirs,
  678. opts,
  679. tag="module",
  680. pack={
  681. "__utils__": self.utils,
  682. "__proxy__": self.proxy,
  683. "__salt__": self.minion_mods,
  684. },
  685. )
  686. def tearDown(self):
  687. del self.tmp_dir
  688. del self.utils
  689. del self.proxy
  690. del self.minion_mods
  691. del self.loader
  692. @classmethod
  693. def tearDownClass(cls):
  694. del cls.opts
  695. def update_module(self):
  696. self.count += 1
  697. with salt.utils.files.fopen(self.module_path, "wb") as fh:
  698. fh.write(
  699. salt.utils.stringutils.to_bytes(
  700. submodule_template.format(self.module_name, count=self.count)
  701. )
  702. )
  703. fh.flush()
  704. os.fsync(fh.fileno()) # flush to disk
  705. # pyc files don't like it when we change the original quickly
  706. # since the header bytes only contain the timestamp (granularity of seconds)
  707. # TODO: don't write them? Is *much* slower on re-load (~3x)
  708. # https://docs.python.org/2/library/sys.html#sys.dont_write_bytecode
  709. remove_bytecode(self.module_path)
  710. def rm_module(self):
  711. os.unlink(self.module_path)
  712. remove_bytecode(self.module_path)
  713. def update_lib(self):
  714. self.lib_count += 1
  715. for modname in list(sys.modules):
  716. if modname.startswith(self.module_name):
  717. del sys.modules[modname]
  718. with salt.utils.files.fopen(self.lib_path, "wb") as fh:
  719. fh.write(
  720. salt.utils.stringutils.to_bytes(
  721. submodule_lib_template.format(count=self.lib_count)
  722. )
  723. )
  724. fh.flush()
  725. os.fsync(fh.fileno()) # flush to disk
  726. # pyc files don't like it when we change the original quickly
  727. # since the header bytes only contain the timestamp (granularity of seconds)
  728. # TODO: don't write them? Is *much* slower on re-load (~3x)
  729. # https://docs.python.org/2/library/sys.html#sys.dont_write_bytecode
  730. remove_bytecode(self.lib_path)
  731. def rm_lib(self):
  732. for modname in list(sys.modules):
  733. if modname.startswith(self.module_name):
  734. del sys.modules[modname]
  735. os.unlink(self.lib_path)
  736. remove_bytecode(self.lib_path)
  737. @property
  738. def module_dir(self):
  739. return os.path.join(self.tmp_dir, self.module_name)
  740. @property
  741. def module_path(self):
  742. return os.path.join(self.module_dir, "__init__.py")
  743. @property
  744. def lib_path(self):
  745. return os.path.join(self.module_dir, "lib.py")
  746. @slowTest
  747. def test_basic(self):
  748. # ensure it doesn't exist
  749. self.assertNotIn(self.module_key, self.loader)
  750. self.update_module()
  751. self.update_lib()
  752. self.loader.clear()
  753. self.assertIn(self.module_key, self.loader)
  754. @slowTest
  755. def test_reload(self):
  756. # ensure it doesn't exist
  757. self.assertNotIn(self.module_key, self.loader)
  758. # update both the module and the lib
  759. for x in range(1, 3):
  760. self.update_lib()
  761. self.update_module()
  762. self.loader.clear()
  763. self.assertNotIn(self.module_key, self.loader._dict)
  764. self.assertIn(self.module_key, self.loader)
  765. self.assertEqual(
  766. self.loader[self.module_key](), (self.count, self.lib_count)
  767. )
  768. # update just the module
  769. for x in range(1, 3):
  770. self.update_module()
  771. self.loader.clear()
  772. self.assertNotIn(self.module_key, self.loader._dict)
  773. self.assertIn(self.module_key, self.loader)
  774. self.assertEqual(
  775. self.loader[self.module_key](), (self.count, self.lib_count)
  776. )
  777. # update just the lib
  778. for x in range(1, 3):
  779. self.update_lib()
  780. self.loader.clear()
  781. self.assertNotIn(self.module_key, self.loader._dict)
  782. self.assertIn(self.module_key, self.loader)
  783. self.assertEqual(
  784. self.loader[self.module_key](), (self.count, self.lib_count)
  785. )
  786. self.rm_module()
  787. # make sure that even if we remove the module, its still loaded until a clear
  788. self.assertEqual(self.loader[self.module_key](), (self.count, self.lib_count))
  789. self.loader.clear()
  790. self.assertNotIn(self.module_key, self.loader)
  791. @slowTest
  792. def test_reload_missing_lib(self):
  793. # ensure it doesn't exist
  794. self.assertNotIn(self.module_key, self.loader)
  795. # update both the module and the lib
  796. self.update_module()
  797. self.update_lib()
  798. self.loader.clear()
  799. self.assertEqual(self.loader[self.module_key](), (self.count, self.lib_count))
  800. # remove the lib, this means we should fail to load the module next time
  801. self.rm_lib()
  802. self.loader.clear()
  803. self.assertNotIn(self.module_key, self.loader)
  804. mod_template = """
  805. def test():
  806. return ({val})
  807. """
  808. class LazyLoaderModulePackageTest(TestCase):
  809. """
  810. Test the loader of salt with changing modules
  811. """
  812. module_name = "loadertestmodpkg"
  813. module_key = "loadertestmodpkg.test"
  814. @classmethod
  815. def setUpClass(cls):
  816. cls.opts = salt.config.minion_config(None)
  817. cls.opts["grains"] = salt.loader.grains(cls.opts)
  818. if not os.path.isdir(RUNTIME_VARS.TMP):
  819. os.makedirs(RUNTIME_VARS.TMP)
  820. cls.utils = salt.loader.utils(copy.deepcopy(cls.opts))
  821. cls.proxy = salt.loader.proxy(cls.opts)
  822. cls.funcs = salt.loader.minion_mods(cls.opts, utils=cls.utils, proxy=cls.proxy)
  823. def setUp(self):
  824. self.tmp_dir = tempfile.mkdtemp(dir=RUNTIME_VARS.TMP)
  825. self.addCleanup(shutil.rmtree, self.tmp_dir, ignore_errors=True)
  826. dirs = salt.loader._module_dirs(copy.deepcopy(self.opts), "modules", "module")
  827. dirs.append(self.tmp_dir)
  828. self.loader = salt.loader.LazyLoader(
  829. dirs,
  830. copy.deepcopy(self.opts),
  831. pack={
  832. "__utils__": self.utils,
  833. "__salt__": self.funcs,
  834. "__proxy__": self.proxy,
  835. },
  836. tag="module",
  837. )
  838. def tearDown(self):
  839. del self.tmp_dir
  840. del self.loader
  841. @classmethod
  842. def tearDownClass(cls):
  843. del cls.opts
  844. del cls.funcs
  845. del cls.utils
  846. del cls.proxy
  847. def update_pyfile(self, pyfile, contents):
  848. dirname = os.path.dirname(pyfile)
  849. if not os.path.exists(dirname):
  850. os.makedirs(dirname)
  851. with salt.utils.files.fopen(pyfile, "wb") as fh:
  852. fh.write(salt.utils.stringutils.to_bytes(contents))
  853. fh.flush()
  854. os.fsync(fh.fileno()) # flush to disk
  855. # pyc files don't like it when we change the original quickly
  856. # since the header bytes only contain the timestamp (granularity of seconds)
  857. # TODO: don't write them? Is *much* slower on re-load (~3x)
  858. # https://docs.python.org/2/library/sys.html#sys.dont_write_bytecode
  859. remove_bytecode(pyfile)
  860. def rm_pyfile(self, pyfile):
  861. os.unlink(pyfile)
  862. remove_bytecode(pyfile)
  863. def update_module(self, relative_path, contents):
  864. self.update_pyfile(os.path.join(self.tmp_dir, relative_path), contents)
  865. def rm_module(self, relative_path):
  866. self.rm_pyfile(os.path.join(self.tmp_dir, relative_path))
  867. @slowTest
  868. def test_module(self):
  869. # ensure it doesn't exist
  870. self.assertNotIn("foo", self.loader)
  871. self.assertNotIn("foo.test", self.loader)
  872. self.update_module("foo.py", mod_template.format(val=1))
  873. self.loader.clear()
  874. self.assertIn("foo.test", self.loader)
  875. self.assertEqual(self.loader["foo.test"](), 1)
  876. @slowTest
  877. def test_package(self):
  878. # ensure it doesn't exist
  879. self.assertNotIn("foo", self.loader)
  880. self.assertNotIn("foo.test", self.loader)
  881. self.update_module("foo/__init__.py", mod_template.format(val=2))
  882. self.loader.clear()
  883. self.assertIn("foo.test", self.loader)
  884. self.assertEqual(self.loader["foo.test"](), 2)
  885. @slowTest
  886. def test_module_package_collision(self):
  887. # ensure it doesn't exist
  888. self.assertNotIn("foo", self.loader)
  889. self.assertNotIn("foo.test", self.loader)
  890. self.update_module("foo.py", mod_template.format(val=3))
  891. self.loader.clear()
  892. self.assertIn("foo.test", self.loader)
  893. self.assertEqual(self.loader["foo.test"](), 3)
  894. self.update_module("foo/__init__.py", mod_template.format(val=4))
  895. self.loader.clear()
  896. self.assertIn("foo.test", self.loader)
  897. self.assertEqual(self.loader["foo.test"](), 4)
  898. deep_init_base = """
  899. from __future__ import absolute_import
  900. import {0}.top_lib
  901. import {0}.top_lib.mid_lib
  902. import {0}.top_lib.mid_lib.bot_lib
  903. def top():
  904. return {0}.top_lib.test()
  905. def mid():
  906. return {0}.top_lib.mid_lib.test()
  907. def bot():
  908. return {0}.top_lib.mid_lib.bot_lib.test()
  909. """
  910. class LazyLoaderDeepSubmodReloadingTest(TestCase):
  911. module_name = "loadertestsubmoddeep"
  912. libs = ("top_lib", "mid_lib", "bot_lib")
  913. @classmethod
  914. def setUpClass(cls):
  915. cls.opts = salt.config.minion_config(None)
  916. cls.opts["grains"] = salt.loader.grains(cls.opts)
  917. if not os.path.isdir(RUNTIME_VARS.TMP):
  918. os.makedirs(RUNTIME_VARS.TMP)
  919. def setUp(self):
  920. self.tmp_dir = tempfile.mkdtemp(dir=RUNTIME_VARS.TMP)
  921. self.addCleanup(shutil.rmtree, self.tmp_dir, ignore_errors=True)
  922. os.makedirs(self.module_dir)
  923. self.lib_count = collections.defaultdict(int) # mapping of path -> count
  924. # bootstrap libs
  925. with salt.utils.files.fopen(
  926. os.path.join(self.module_dir, "__init__.py"), "w"
  927. ) as fh:
  928. # No .decode() needed here as deep_init_base is defined as str and
  929. # not bytes.
  930. fh.write(
  931. salt.utils.stringutils.to_str(deep_init_base.format(self.module_name))
  932. )
  933. fh.flush()
  934. os.fsync(fh.fileno()) # flush to disk
  935. self.lib_paths = {}
  936. dir_path = self.module_dir
  937. for lib_name in self.libs:
  938. dir_path = os.path.join(dir_path, lib_name)
  939. self.lib_paths[lib_name] = dir_path
  940. os.makedirs(dir_path)
  941. self.update_lib(lib_name)
  942. opts = copy.deepcopy(self.opts)
  943. dirs = salt.loader._module_dirs(opts, "modules", "module")
  944. dirs.append(self.tmp_dir)
  945. self.utils = salt.loader.utils(opts)
  946. self.proxy = salt.loader.proxy(opts)
  947. self.minion_mods = salt.loader.minion_mods(opts)
  948. self.loader = salt.loader.LazyLoader(
  949. dirs,
  950. copy.deepcopy(opts),
  951. tag="module",
  952. pack={
  953. "__utils__": self.utils,
  954. "__proxy__": self.proxy,
  955. "__salt__": self.minion_mods,
  956. },
  957. )
  958. self.assertIn("{}.top".format(self.module_name), self.loader)
  959. def tearDown(self):
  960. del self.tmp_dir
  961. del self.lib_paths
  962. del self.utils
  963. del self.proxy
  964. del self.minion_mods
  965. del self.loader
  966. del self.lib_count
  967. @classmethod
  968. def tearDownClass(cls):
  969. del cls.opts
  970. @property
  971. def module_dir(self):
  972. return os.path.join(self.tmp_dir, self.module_name)
  973. def update_lib(self, lib_name):
  974. for modname in list(sys.modules):
  975. if modname.startswith(self.module_name):
  976. del sys.modules[modname]
  977. path = os.path.join(self.lib_paths[lib_name], "__init__.py")
  978. self.lib_count[lib_name] += 1
  979. with salt.utils.files.fopen(path, "wb") as fh:
  980. fh.write(
  981. salt.utils.stringutils.to_bytes(
  982. submodule_lib_template.format(count=self.lib_count[lib_name])
  983. )
  984. )
  985. fh.flush()
  986. os.fsync(fh.fileno()) # flush to disk
  987. # pyc files don't like it when we change the original quickly
  988. # since the header bytes only contain the timestamp (granularity of seconds)
  989. # TODO: don't write them? Is *much* slower on re-load (~3x)
  990. # https://docs.python.org/2/library/sys.html#sys.dont_write_bytecode
  991. remove_bytecode(path)
  992. @slowTest
  993. def test_basic(self):
  994. self.assertIn("{}.top".format(self.module_name), self.loader)
  995. def _verify_libs(self):
  996. for lib in self.libs:
  997. self.assertEqual(
  998. self.loader[
  999. "{}.{}".format(self.module_name, lib.replace("_lib", ""))
  1000. ](),
  1001. self.lib_count[lib],
  1002. )
  1003. @slowTest
  1004. def test_reload(self):
  1005. """
  1006. Make sure that we can reload all libraries of arbitrary depth
  1007. """
  1008. self._verify_libs()
  1009. # update them all
  1010. for lib in self.libs:
  1011. for x in range(5):
  1012. self.update_lib(lib)
  1013. self.loader.clear()
  1014. self._verify_libs()
  1015. class LoaderGlobalsTest(ModuleCase):
  1016. """
  1017. Test all of the globals that the loader is responsible for adding to modules
  1018. This shouldn't be done here, but should rather be done per module type (in the cases where they are used)
  1019. so they can check ALL globals that they have (or should have) access to.
  1020. This is intended as a shorter term way of testing these so we don't break the loader
  1021. """
  1022. def _verify_globals(self, mod_dict):
  1023. """
  1024. Verify that the globals listed in the doc string (from the test) are in these modules
  1025. """
  1026. # find the globals
  1027. global_vars = {}
  1028. for val in mod_dict.values():
  1029. # only find salty globals
  1030. if val.__module__.startswith("salt.loaded"):
  1031. if hasattr(val, "__globals__"):
  1032. if hasattr(val, "__wrapped__") or "__wrapped__" in val.__globals__:
  1033. global_vars[val.__module__] = sys.modules[
  1034. val.__module__
  1035. ].__dict__
  1036. else:
  1037. global_vars[val.__module__] = val.__globals__
  1038. # if we couldn't find any, then we have no modules -- so something is broken
  1039. self.assertNotEqual(global_vars, {}, msg="No modules were loaded.")
  1040. # get the names of the globals you should have
  1041. func_name = inspect.stack()[1][3]
  1042. names = next(
  1043. iter(salt.utils.yaml.safe_load(getattr(self, func_name).__doc__).values())
  1044. )
  1045. # Now, test each module!
  1046. for item in global_vars.values():
  1047. for name in names:
  1048. self.assertIn(name, list(item.keys()))
  1049. def test_auth(self):
  1050. """
  1051. Test that auth mods have:
  1052. - __pillar__
  1053. - __grains__
  1054. - __salt__
  1055. - __context__
  1056. """
  1057. self._verify_globals(salt.loader.auth(self.master_opts))
  1058. def test_runners(self):
  1059. """
  1060. Test that runners have:
  1061. - __pillar__
  1062. - __salt__
  1063. - __opts__
  1064. - __grains__
  1065. - __context__
  1066. """
  1067. self._verify_globals(salt.loader.runner(self.master_opts))
  1068. def test_returners(self):
  1069. """
  1070. Test that returners have:
  1071. - __salt__
  1072. - __opts__
  1073. - __pillar__
  1074. - __grains__
  1075. - __context__
  1076. """
  1077. self._verify_globals(salt.loader.returners(self.master_opts, {}))
  1078. def test_pillars(self):
  1079. """
  1080. Test that pillars have:
  1081. - __salt__
  1082. - __opts__
  1083. - __pillar__
  1084. - __grains__
  1085. - __context__
  1086. """
  1087. self._verify_globals(salt.loader.pillars(self.master_opts, {}))
  1088. def test_tops(self):
  1089. """
  1090. Test that tops have: []
  1091. """
  1092. self._verify_globals(salt.loader.tops(self.master_opts))
  1093. def test_outputters(self):
  1094. """
  1095. Test that outputters have:
  1096. - __opts__
  1097. - __pillar__
  1098. - __grains__
  1099. - __context__
  1100. """
  1101. self._verify_globals(salt.loader.outputters(self.master_opts))
  1102. def test_serializers(self):
  1103. """
  1104. Test that serializers have: []
  1105. """
  1106. self._verify_globals(salt.loader.serializers(self.master_opts))
  1107. @slowTest
  1108. def test_states(self):
  1109. """
  1110. Test that states have:
  1111. - __pillar__
  1112. - __salt__
  1113. - __opts__
  1114. - __grains__
  1115. - __context__
  1116. """
  1117. opts = salt.config.minion_config(None)
  1118. opts["grains"] = salt.loader.grains(opts)
  1119. utils = salt.loader.utils(opts)
  1120. proxy = salt.loader.proxy(opts)
  1121. funcs = salt.loader.minion_mods(opts, utils=utils, proxy=proxy)
  1122. self._verify_globals(salt.loader.states(opts, funcs, utils, {}, proxy=proxy))
  1123. def test_renderers(self):
  1124. """
  1125. Test that renderers have:
  1126. - __salt__ # Execution functions (i.e. __salt__['test.echo']('foo'))
  1127. - __grains__ # Grains (i.e. __grains__['os'])
  1128. - __pillar__ # Pillar data (i.e. __pillar__['foo'])
  1129. - __opts__ # Minion configuration options
  1130. - __context__ # Context dict shared amongst all modules of the same type
  1131. """
  1132. self._verify_globals(salt.loader.render(self.master_opts, {}))
  1133. class RawModTest(TestCase):
  1134. """
  1135. Test the interface of raw_mod
  1136. """
  1137. def setUp(self):
  1138. self.opts = salt.config.minion_config(None)
  1139. def tearDown(self):
  1140. del self.opts
  1141. @slowTest
  1142. def test_basic(self):
  1143. testmod = salt.loader.raw_mod(self.opts, "test", None)
  1144. for k, v in testmod.items():
  1145. self.assertEqual(k.split(".")[0], "test")
  1146. def test_bad_name(self):
  1147. testmod = salt.loader.raw_mod(self.opts, "module_we_do_not_have", None)
  1148. self.assertEqual(testmod, {})
  1149. class NetworkUtilsTestCase(ModuleCase):
  1150. def test_is_private(self):
  1151. mod = salt.loader.raw_mod(self.minion_opts, "network", None)
  1152. self.assertTrue(mod["network.is_private"]("10.0.0.1"), True)
  1153. def test_is_loopback(self):
  1154. mod = salt.loader.raw_mod(self.minion_opts, "network", None)
  1155. self.assertTrue(mod["network.is_loopback"]("127.0.0.1"), True)
  1156. class LazyLoaderOptimizationOrderTest(TestCase):
  1157. """
  1158. Test the optimization order priority in the loader (PY3)
  1159. """
  1160. module_name = "lazyloadertest"
  1161. module_content = textwrap.dedent(
  1162. """\
  1163. # -*- coding: utf-8 -*-
  1164. from __future__ import absolute_import
  1165. def test():
  1166. return True
  1167. """
  1168. )
  1169. @classmethod
  1170. def setUpClass(cls):
  1171. cls.opts = salt.config.minion_config(None)
  1172. cls.opts["grains"] = salt.loader.grains(cls.opts)
  1173. cls.utils = salt.loader.utils(copy.deepcopy(cls.opts))
  1174. cls.proxy = salt.loader.proxy(cls.opts)
  1175. cls.funcs = salt.loader.minion_mods(cls.opts, utils=cls.utils, proxy=cls.proxy)
  1176. @classmethod
  1177. def tearDownClass(cls):
  1178. del cls.opts
  1179. del cls.funcs
  1180. del cls.utils
  1181. del cls.proxy
  1182. def setUp(self):
  1183. # Setup the module
  1184. self.module_dir = tempfile.mkdtemp(dir=RUNTIME_VARS.TMP)
  1185. self.addCleanup(shutil.rmtree, self.module_dir, ignore_errors=True)
  1186. self.module_file = os.path.join(
  1187. self.module_dir, "{}.py".format(self.module_name)
  1188. )
  1189. def tearDown(self):
  1190. try:
  1191. delattr(self, "loader")
  1192. except AttributeError:
  1193. pass
  1194. def _get_loader(self, order=None):
  1195. opts = copy.deepcopy(self.opts)
  1196. if order is not None:
  1197. opts["optimization_order"] = order
  1198. # Return a loader
  1199. return salt.loader.LazyLoader(
  1200. [self.module_dir],
  1201. opts,
  1202. pack={
  1203. "__utils__": self.utils,
  1204. "__salt__": self.funcs,
  1205. "__proxy__": self.proxy,
  1206. },
  1207. tag="module",
  1208. )
  1209. def _get_module_filename(self):
  1210. # The act of referencing the loader entry forces the module to be
  1211. # loaded by the LazyDict.
  1212. mod_fullname = self.loader[next(iter(self.loader))].__module__
  1213. return sys.modules[mod_fullname].__file__
  1214. def _expected(self, optimize=0):
  1215. return "lazyloadertest.cpython-{}{}{}.pyc".format(
  1216. sys.version_info[0],
  1217. sys.version_info[1],
  1218. "" if not optimize else ".opt-{}".format(optimize),
  1219. )
  1220. def _write_module_file(self):
  1221. with salt.utils.files.fopen(self.module_file, "w") as fh:
  1222. fh.write(self.module_content)
  1223. fh.flush()
  1224. os.fsync(fh.fileno())
  1225. def _byte_compile(self):
  1226. if salt.loader.USE_IMPORTLIB:
  1227. # Skip this check as "optimize" is unique to PY3's compileall
  1228. # module, and this will be a false error when Pylint is run on
  1229. # Python 2.
  1230. # pylint: disable=unexpected-keyword-arg
  1231. compileall.compile_file(self.module_file, quiet=1, optimize=0)
  1232. compileall.compile_file(self.module_file, quiet=1, optimize=1)
  1233. compileall.compile_file(self.module_file, quiet=1, optimize=2)
  1234. # pylint: enable=unexpected-keyword-arg
  1235. else:
  1236. compileall.compile_file(self.module_file, quiet=1)
  1237. def _test_optimization_order(self, order):
  1238. self._write_module_file()
  1239. self._byte_compile()
  1240. # Clean up the original file so that we can be assured we're only
  1241. # loading the byte-compiled files(s).
  1242. os.remove(self.module_file)
  1243. self.loader = self._get_loader(order)
  1244. filename = self._get_module_filename()
  1245. basename = os.path.basename(filename)
  1246. assert basename == self._expected(order[0]), basename
  1247. if not salt.loader.USE_IMPORTLIB:
  1248. # We are only testing multiple optimization levels on Python 3.5+
  1249. return
  1250. # Remove the file and make a new loader. We should now load the
  1251. # byte-compiled file with an optimization level matching the 2nd
  1252. # element of the order list.
  1253. os.remove(filename)
  1254. self.loader = self._get_loader(order)
  1255. filename = self._get_module_filename()
  1256. basename = os.path.basename(filename)
  1257. assert basename == self._expected(order[1]), basename
  1258. # Remove the file and make a new loader. We should now load the
  1259. # byte-compiled file with an optimization level matching the 3rd
  1260. # element of the order list.
  1261. os.remove(filename)
  1262. self.loader = self._get_loader(order)
  1263. filename = self._get_module_filename()
  1264. basename = os.path.basename(filename)
  1265. assert basename == self._expected(order[2]), basename
  1266. def test_optimization_order(self):
  1267. """
  1268. Test the optimization_order config param
  1269. """
  1270. self._test_optimization_order([0, 1, 2])
  1271. self._test_optimization_order([0, 2, 1])
  1272. if salt.loader.USE_IMPORTLIB:
  1273. # optimization_order only supported on Python 3.5+, earlier
  1274. # releases only support unoptimized .pyc files.
  1275. self._test_optimization_order([1, 2, 0])
  1276. self._test_optimization_order([1, 0, 2])
  1277. self._test_optimization_order([2, 0, 1])
  1278. self._test_optimization_order([2, 1, 0])
  1279. def test_load_source_file(self):
  1280. """
  1281. Make sure that .py files are preferred over .pyc files
  1282. """
  1283. self._write_module_file()
  1284. self._byte_compile()
  1285. self.loader = self._get_loader()
  1286. filename = self._get_module_filename()
  1287. basename = os.path.basename(filename)
  1288. expected = "lazyloadertest.py" if six.PY3 else "lazyloadertest.pyc"
  1289. assert basename == expected, basename
  1290. class LoaderLoadCachedGrainsTest(TestCase):
  1291. """
  1292. Test how the loader works with cached grains
  1293. """
  1294. @classmethod
  1295. def setUpClass(cls):
  1296. cls.opts = salt.config.minion_config(None)
  1297. if not os.path.isdir(RUNTIME_VARS.TMP):
  1298. os.makedirs(RUNTIME_VARS.TMP)
  1299. def setUp(self):
  1300. self.cache_dir = tempfile.mkdtemp(dir=RUNTIME_VARS.TMP)
  1301. self.addCleanup(shutil.rmtree, self.cache_dir, ignore_errors=True)
  1302. self.opts["cachedir"] = self.cache_dir
  1303. self.opts["grains_cache"] = True
  1304. self.opts["grains"] = salt.loader.grains(self.opts)
  1305. @slowTest
  1306. def test_osrelease_info_has_correct_type(self):
  1307. """
  1308. Make sure osrelease_info is tuple after caching
  1309. """
  1310. grains = salt.loader.grains(self.opts)
  1311. osrelease_info = grains["osrelease_info"]
  1312. assert isinstance(osrelease_info, tuple), osrelease_info
  1313. class LazyLoaderRefreshFileMappingTest(TestCase):
  1314. """
  1315. Test that _refresh_file_mapping is called using acquiring LazyLoader._lock
  1316. """
  1317. @classmethod
  1318. def setUpClass(cls):
  1319. cls.opts = salt.config.minion_config(None)
  1320. cls.opts["grains"] = salt.loader.grains(cls.opts)
  1321. cls.utils = salt.loader.utils(copy.deepcopy(cls.opts))
  1322. cls.proxy = salt.loader.proxy(cls.opts)
  1323. cls.funcs = salt.loader.minion_mods(cls.opts, utils=cls.utils, proxy=cls.proxy)
  1324. def setUp(self):
  1325. class LazyLoaderMock(salt.loader.LazyLoader):
  1326. pass
  1327. self.LOADER_CLASS = LazyLoaderMock
  1328. def __init_loader(self):
  1329. return self.LOADER_CLASS(
  1330. salt.loader._module_dirs(copy.deepcopy(self.opts), "modules", "module"),
  1331. copy.deepcopy(self.opts),
  1332. tag="module",
  1333. pack={
  1334. "__utils__": self.utils,
  1335. "__salt__": self.funcs,
  1336. "__proxy__": self.proxy,
  1337. },
  1338. )
  1339. @classmethod
  1340. def tearDownClass(cls):
  1341. del cls.opts
  1342. del cls.utils
  1343. del cls.funcs
  1344. del cls.proxy
  1345. def test_lazyloader_refresh_file_mapping_called_with_lock_at___init__(self):
  1346. func_mock = MagicMock()
  1347. lock_mock = MagicMock()
  1348. lock_mock.__enter__ = MagicMock()
  1349. self.LOADER_CLASS._refresh_file_mapping = func_mock
  1350. with patch("threading.RLock", MagicMock(return_value=lock_mock)):
  1351. loader = self.__init_loader()
  1352. lock_mock.__enter__.assert_called()
  1353. func_mock.assert_called()
  1354. assert len(func_mock.call_args_list) == len(lock_mock.__enter__.call_args_list)
  1355. del loader