mixins.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854
  1. # -*- coding: utf-8 -*-
  2. """
  3. :codeauthor: Pedro Algarvio (pedro@algarvio.me)
  4. =============
  5. Class Mix-Ins
  6. =============
  7. Some reusable class Mixins
  8. """
  9. # pylint: disable=repr-flag-used-in-string
  10. # Import python libs
  11. from __future__ import absolute_import, print_function
  12. import atexit
  13. import copy
  14. import functools
  15. import logging
  16. import multiprocessing
  17. import os
  18. import pprint
  19. import subprocess
  20. import sys
  21. import tempfile
  22. import time
  23. import types
  24. from collections import OrderedDict
  25. # Import salt libs
  26. import salt.config
  27. import salt.exceptions
  28. import salt.utils.event
  29. import salt.utils.files
  30. import salt.utils.functools
  31. import salt.utils.path
  32. import salt.utils.process
  33. import salt.utils.stringutils
  34. import salt.utils.yaml
  35. import salt.version
  36. from salt._compat import ElementTree as etree
  37. # Import 3rd-party libs
  38. from salt.ext import six
  39. from salt.ext.six.moves import zip # pylint: disable=import-error,redefined-builtin
  40. from salt.ext.six.moves.queue import ( # pylint: disable=import-error,no-name-in-module
  41. Empty,
  42. )
  43. from salt.utils.immutabletypes import freeze
  44. from salt.utils.verify import verify_env
  45. # Import Salt Testing Libs
  46. from tests.support.mock import patch
  47. from tests.support.paths import CODE_DIR
  48. from tests.support.runtests import RUNTIME_VARS
  49. log = logging.getLogger(__name__)
  50. class CheckShellBinaryNameAndVersionMixin(object):
  51. """
  52. Simple class mix-in to subclass in companion to :class:`ShellTestCase<tests.support.case.ShellTestCase>` which
  53. adds a test case to verify proper version report from Salt's CLI tools.
  54. """
  55. _call_binary_ = None
  56. _call_binary_expected_version_ = None
  57. def test_version_includes_binary_name(self):
  58. if getattr(self, "_call_binary_", None) is None:
  59. self.skipTest("'_call_binary_' not defined.")
  60. if self._call_binary_expected_version_ is None:
  61. # Late import
  62. self._call_binary_expected_version_ = salt.version.__version__
  63. out = "\n".join(self.run_script(self._call_binary_, "--version"))
  64. # Assert that the binary name is in the output
  65. try:
  66. self.assertIn(self._call_binary_, out)
  67. except AssertionError:
  68. # We might have generated the CLI scripts in which case we replace '-' with '_'
  69. alternate_binary_name = self._call_binary_.replace("-", "_")
  70. errmsg = "Neither '{}' or '{}' were found as part of the binary name in:\n'{}'".format(
  71. self._call_binary_, alternate_binary_name, out
  72. )
  73. self.assertIn(alternate_binary_name, out, msg=errmsg)
  74. # Assert that the version is in the output
  75. self.assertIn(self._call_binary_expected_version_, out)
  76. class AdaptedConfigurationTestCaseMixin(object):
  77. __slots__ = ()
  78. @staticmethod
  79. def get_temp_config(config_for, **config_overrides):
  80. rootdir = config_overrides.get(
  81. "root_dir", tempfile.mkdtemp(dir=RUNTIME_VARS.TMP)
  82. )
  83. conf_dir = config_overrides.pop("conf_dir", os.path.join(rootdir, "conf"))
  84. for key in ("cachedir", "pki_dir", "sock_dir"):
  85. if key not in config_overrides:
  86. config_overrides[key] = key
  87. if "log_file" not in config_overrides:
  88. config_overrides["log_file"] = "logs/{}.log".format(config_for)
  89. if "user" not in config_overrides:
  90. config_overrides["user"] = RUNTIME_VARS.RUNNING_TESTS_USER
  91. config_overrides["root_dir"] = rootdir
  92. cdict = AdaptedConfigurationTestCaseMixin.get_config(
  93. config_for, from_scratch=True
  94. )
  95. if config_for in ("master", "client_config"):
  96. rdict = salt.config.apply_master_config(config_overrides, cdict)
  97. if config_for == "minion":
  98. rdict = salt.config.apply_minion_config(config_overrides, cdict)
  99. verify_env(
  100. [
  101. os.path.join(rdict["pki_dir"], "minions"),
  102. os.path.join(rdict["pki_dir"], "minions_pre"),
  103. os.path.join(rdict["pki_dir"], "minions_rejected"),
  104. os.path.join(rdict["pki_dir"], "minions_denied"),
  105. os.path.join(rdict["cachedir"], "jobs"),
  106. os.path.join(rdict["cachedir"], "tokens"),
  107. os.path.join(rdict["root_dir"], "cache", "tokens"),
  108. os.path.join(rdict["pki_dir"], "accepted"),
  109. os.path.join(rdict["pki_dir"], "rejected"),
  110. os.path.join(rdict["pki_dir"], "pending"),
  111. os.path.dirname(rdict["log_file"]),
  112. rdict["sock_dir"],
  113. conf_dir,
  114. ],
  115. RUNTIME_VARS.RUNNING_TESTS_USER,
  116. root_dir=rdict["root_dir"],
  117. )
  118. rdict["conf_file"] = os.path.join(conf_dir, config_for)
  119. with salt.utils.files.fopen(rdict["conf_file"], "w") as wfh:
  120. salt.utils.yaml.safe_dump(rdict, wfh, default_flow_style=False)
  121. return rdict
  122. @staticmethod
  123. def get_config(config_for, from_scratch=False):
  124. if from_scratch:
  125. if config_for in ("master", "syndic_master", "mm_master", "mm_sub_master"):
  126. return salt.config.master_config(
  127. AdaptedConfigurationTestCaseMixin.get_config_file_path(config_for)
  128. )
  129. elif config_for in ("minion", "sub_minion"):
  130. return salt.config.minion_config(
  131. AdaptedConfigurationTestCaseMixin.get_config_file_path(config_for)
  132. )
  133. elif config_for in ("syndic",):
  134. return salt.config.syndic_config(
  135. AdaptedConfigurationTestCaseMixin.get_config_file_path(config_for),
  136. AdaptedConfigurationTestCaseMixin.get_config_file_path("minion"),
  137. )
  138. elif config_for == "client_config":
  139. return salt.config.client_config(
  140. AdaptedConfigurationTestCaseMixin.get_config_file_path("master")
  141. )
  142. if config_for not in RUNTIME_VARS.RUNTIME_CONFIGS:
  143. if config_for in ("master", "syndic_master", "mm_master", "mm_sub_master"):
  144. RUNTIME_VARS.RUNTIME_CONFIGS[config_for] = freeze(
  145. salt.config.master_config(
  146. AdaptedConfigurationTestCaseMixin.get_config_file_path(
  147. config_for
  148. )
  149. )
  150. )
  151. elif config_for in ("minion", "sub_minion"):
  152. RUNTIME_VARS.RUNTIME_CONFIGS[config_for] = freeze(
  153. salt.config.minion_config(
  154. AdaptedConfigurationTestCaseMixin.get_config_file_path(
  155. config_for
  156. )
  157. )
  158. )
  159. elif config_for in ("syndic",):
  160. RUNTIME_VARS.RUNTIME_CONFIGS[config_for] = freeze(
  161. salt.config.syndic_config(
  162. AdaptedConfigurationTestCaseMixin.get_config_file_path(
  163. config_for
  164. ),
  165. AdaptedConfigurationTestCaseMixin.get_config_file_path(
  166. "minion"
  167. ),
  168. )
  169. )
  170. elif config_for == "client_config":
  171. RUNTIME_VARS.RUNTIME_CONFIGS[config_for] = freeze(
  172. salt.config.client_config(
  173. AdaptedConfigurationTestCaseMixin.get_config_file_path("master")
  174. )
  175. )
  176. return RUNTIME_VARS.RUNTIME_CONFIGS[config_for]
  177. @property
  178. def config_dir(self):
  179. return RUNTIME_VARS.TMP_CONF_DIR
  180. def get_config_dir(self):
  181. log.warning("Use the config_dir attribute instead of calling get_config_dir()")
  182. return self.config_dir
  183. @staticmethod
  184. def get_config_file_path(filename):
  185. if filename == "syndic_master":
  186. return os.path.join(RUNTIME_VARS.TMP_SYNDIC_MASTER_CONF_DIR, "master")
  187. if filename == "syndic":
  188. return os.path.join(RUNTIME_VARS.TMP_SYNDIC_MINION_CONF_DIR, "minion")
  189. if filename == "sub_minion":
  190. return os.path.join(RUNTIME_VARS.TMP_SUB_MINION_CONF_DIR, "minion")
  191. if filename == "mm_master":
  192. return os.path.join(RUNTIME_VARS.TMP_MM_CONF_DIR, "master")
  193. if filename == "mm_sub_master":
  194. return os.path.join(RUNTIME_VARS.TMP_MM_SUB_CONF_DIR, "master")
  195. if filename == "mm_minion":
  196. return os.path.join(RUNTIME_VARS.TMP_MM_CONF_DIR, "minion")
  197. if filename == "mm_sub_minion":
  198. return os.path.join(RUNTIME_VARS.TMP_MM_SUB_CONF_DIR, "minion")
  199. return os.path.join(RUNTIME_VARS.TMP_CONF_DIR, filename)
  200. @property
  201. def master_opts(self):
  202. """
  203. Return the options used for the master
  204. """
  205. return self.get_config("master")
  206. @property
  207. def minion_opts(self):
  208. """
  209. Return the options used for the minion
  210. """
  211. return self.get_config("minion")
  212. @property
  213. def sub_minion_opts(self):
  214. """
  215. Return the options used for the sub_minion
  216. """
  217. return self.get_config("sub_minion")
  218. @property
  219. def mm_master_opts(self):
  220. """
  221. Return the options used for the multimaster master
  222. """
  223. return self.get_config("mm_master")
  224. @property
  225. def mm_sub_master_opts(self):
  226. """
  227. Return the options used for the multimaster sub-master
  228. """
  229. return self.get_config("mm_sub_master")
  230. @property
  231. def mm_minion_opts(self):
  232. """
  233. Return the options used for the minion
  234. """
  235. return self.get_config("mm_minion")
  236. class SaltClientTestCaseMixin(AdaptedConfigurationTestCaseMixin):
  237. """
  238. Mix-in class that provides a ``client`` attribute which returns a Salt
  239. :class:`LocalClient<salt:salt.client.LocalClient>`.
  240. .. code-block:: python
  241. class LocalClientTestCase(TestCase, SaltClientTestCaseMixin):
  242. def test_check_pub_data(self):
  243. just_minions = {'minions': ['m1', 'm2']}
  244. jid_no_minions = {'jid': '1234', 'minions': []}
  245. valid_pub_data = {'minions': ['m1', 'm2'], 'jid': '1234'}
  246. self.assertRaises(EauthAuthenticationError,
  247. self.client._check_pub_data, None)
  248. self.assertDictEqual({},
  249. self.client._check_pub_data(just_minions),
  250. 'Did not handle lack of jid correctly')
  251. self.assertDictEqual(
  252. {},
  253. self.client._check_pub_data({'jid': '0'}),
  254. 'Passing JID of zero is not handled gracefully')
  255. """
  256. _salt_client_config_file_name_ = "master"
  257. @property
  258. def client(self):
  259. # Late import
  260. import salt.client
  261. if "runtime_client" not in RUNTIME_VARS.RUNTIME_CONFIGS:
  262. mopts = self.get_config(
  263. self._salt_client_config_file_name_, from_scratch=True
  264. )
  265. RUNTIME_VARS.RUNTIME_CONFIGS[
  266. "runtime_client"
  267. ] = salt.client.get_local_client(mopts=mopts)
  268. return RUNTIME_VARS.RUNTIME_CONFIGS["runtime_client"]
  269. class SaltMultimasterClientTestCaseMixin(AdaptedConfigurationTestCaseMixin):
  270. """
  271. Mix-in class that provides a ``clients`` attribute which returns a list of Salt
  272. :class:`LocalClient<salt:salt.client.LocalClient>`.
  273. .. code-block:: python
  274. class LocalClientTestCase(TestCase, SaltMultimasterClientTestCaseMixin):
  275. def test_check_pub_data(self):
  276. just_minions = {'minions': ['m1', 'm2']}
  277. jid_no_minions = {'jid': '1234', 'minions': []}
  278. valid_pub_data = {'minions': ['m1', 'm2'], 'jid': '1234'}
  279. for client in self.clients:
  280. self.assertRaises(EauthAuthenticationError,
  281. client._check_pub_data, None)
  282. self.assertDictEqual({},
  283. client._check_pub_data(just_minions),
  284. 'Did not handle lack of jid correctly')
  285. self.assertDictEqual(
  286. {},
  287. client._check_pub_data({'jid': '0'}),
  288. 'Passing JID of zero is not handled gracefully')
  289. """
  290. _salt_client_config_file_name_ = "master"
  291. @property
  292. def clients(self):
  293. # Late import
  294. import salt.client
  295. if "runtime_clients" not in RUNTIME_VARS.RUNTIME_CONFIGS:
  296. RUNTIME_VARS.RUNTIME_CONFIGS["runtime_clients"] = OrderedDict()
  297. runtime_clients = RUNTIME_VARS.RUNTIME_CONFIGS["runtime_clients"]
  298. for master_id in ("mm-master", "mm-sub-master"):
  299. if master_id in runtime_clients:
  300. continue
  301. mopts = self.get_config(master_id.replace("-", "_"), from_scratch=True)
  302. runtime_clients[master_id] = salt.client.get_local_client(mopts=mopts)
  303. return runtime_clients
  304. class ShellCaseCommonTestsMixin(CheckShellBinaryNameAndVersionMixin):
  305. _call_binary_expected_version_ = salt.version.__version__
  306. def test_salt_with_git_version(self):
  307. if getattr(self, "_call_binary_", None) is None:
  308. self.skipTest("'_call_binary_' not defined.")
  309. from salt.version import __version_info__, SaltStackVersion
  310. git = salt.utils.path.which("git")
  311. if not git:
  312. self.skipTest("The git binary is not available")
  313. opts = {
  314. "stdout": subprocess.PIPE,
  315. "stderr": subprocess.PIPE,
  316. "cwd": CODE_DIR,
  317. }
  318. if not salt.utils.platform.is_windows():
  319. opts["close_fds"] = True
  320. # Let's get the output of git describe
  321. process = subprocess.Popen(
  322. [git, "describe", "--tags", "--first-parent", "--match", "v[0-9]*"], **opts
  323. )
  324. out, err = process.communicate()
  325. if process.returncode != 0:
  326. process = subprocess.Popen(
  327. [git, "describe", "--tags", "--match", "v[0-9]*"], **opts
  328. )
  329. out, err = process.communicate()
  330. if not out:
  331. self.skipTest(
  332. "Failed to get the output of 'git describe'. "
  333. "Error: '{0}'".format(salt.utils.stringutils.to_str(err))
  334. )
  335. parsed_version = SaltStackVersion.parse(out)
  336. if parsed_version.info < __version_info__:
  337. self.skipTest(
  338. "We're likely about to release a new version. This test "
  339. "would fail. Parsed('{0}') < Expected('{1}')".format(
  340. parsed_version.info, __version_info__
  341. )
  342. )
  343. elif parsed_version.info != __version_info__:
  344. self.skipTest(
  345. "In order to get the proper salt version with the "
  346. "git hash you need to update salt's local git "
  347. "tags. Something like: 'git fetch --tags' or "
  348. "'git fetch --tags upstream' if you followed "
  349. "salt's contribute documentation. The version "
  350. "string WILL NOT include the git hash."
  351. )
  352. out = "\n".join(self.run_script(self._call_binary_, "--version"))
  353. self.assertIn(parsed_version.string, out)
  354. class _FixLoaderModuleMockMixinMroOrder(type):
  355. """
  356. This metaclass will make sure that LoaderModuleMockMixin will always come as the first
  357. base class in order for LoaderModuleMockMixin.setUp to actually run
  358. """
  359. def __new__(mcs, cls_name, cls_bases, cls_dict):
  360. if cls_name == "LoaderModuleMockMixin":
  361. return super(_FixLoaderModuleMockMixinMroOrder, mcs).__new__(
  362. mcs, cls_name, cls_bases, cls_dict
  363. )
  364. bases = list(cls_bases)
  365. for idx, base in enumerate(bases):
  366. if base.__name__ == "LoaderModuleMockMixin":
  367. bases.insert(0, bases.pop(idx))
  368. break
  369. # Create the class instance
  370. instance = super(_FixLoaderModuleMockMixinMroOrder, mcs).__new__(
  371. mcs, cls_name, tuple(bases), cls_dict
  372. )
  373. # Apply our setUp function decorator
  374. instance.setUp = LoaderModuleMockMixin.__setup_loader_modules_mocks__(
  375. instance.setUp
  376. )
  377. return instance
  378. class LoaderModuleMockMixin(
  379. six.with_metaclass(_FixLoaderModuleMockMixinMroOrder, object)
  380. ):
  381. """
  382. This class will setup salt loader dunders.
  383. Please check `set_up_loader_mocks` above
  384. """
  385. # Define our setUp function decorator
  386. @staticmethod
  387. def __setup_loader_modules_mocks__(setup_func):
  388. @functools.wraps(setup_func)
  389. def wrapper(self):
  390. loader_modules_configs = self.setup_loader_modules()
  391. if not isinstance(loader_modules_configs, dict):
  392. raise RuntimeError(
  393. "{}.setup_loader_modules() must return a dictionary where the keys are the "
  394. "modules that require loader mocking setup and the values, the global module "
  395. "variables for each of the module being mocked. For example '__salt__', "
  396. "'__opts__', etc.".format(self.__class__.__name__)
  397. )
  398. salt_dunders = (
  399. "__opts__",
  400. "__salt__",
  401. "__runner__",
  402. "__context__",
  403. "__utils__",
  404. "__ext_pillar__",
  405. "__thorium__",
  406. "__states__",
  407. "__serializers__",
  408. "__ret__",
  409. "__grains__",
  410. "__pillar__",
  411. "__sdb__",
  412. # Proxy is commented out on purpose since some code in salt expects a NameError
  413. # and is most of the time not a required dunder
  414. # '__proxy__'
  415. )
  416. for module, module_globals in six.iteritems(loader_modules_configs):
  417. if not isinstance(module, types.ModuleType):
  418. raise RuntimeError(
  419. "The dictionary keys returned by {}.setup_loader_modules() "
  420. "must be an imported module, not {}".format(
  421. self.__class__.__name__, type(module)
  422. )
  423. )
  424. if not isinstance(module_globals, dict):
  425. raise RuntimeError(
  426. "The dictionary values returned by {}.setup_loader_modules() "
  427. "must be a dictionary, not {}".format(
  428. self.__class__.__name__, type(module_globals)
  429. )
  430. )
  431. module_blacklisted_dunders = module_globals.pop(
  432. "blacklisted_dunders", ()
  433. )
  434. minion_funcs = {}
  435. if (
  436. "__salt__" in module_globals
  437. and module_globals["__salt__"] == "autoload"
  438. ):
  439. if "__opts__" not in module_globals:
  440. raise RuntimeError(
  441. "You must provide '__opts__' on the {} module globals dictionary "
  442. "to auto load the minion functions".format(module.__name__)
  443. )
  444. import salt.loader
  445. ctx = {}
  446. if "__utils__" not in module_globals:
  447. utils = salt.loader.utils(
  448. module_globals["__opts__"],
  449. context=module_globals.get("__context__") or ctx,
  450. )
  451. module_globals["__utils__"] = utils
  452. minion_funcs = salt.loader.minion_mods(
  453. module_globals["__opts__"],
  454. context=module_globals.get("__context__") or ctx,
  455. utils=module_globals.get("__utils__"),
  456. )
  457. module_globals["__salt__"] = minion_funcs
  458. for dunder_name in salt_dunders:
  459. if dunder_name not in module_globals:
  460. if dunder_name in module_blacklisted_dunders:
  461. continue
  462. module_globals[dunder_name] = {}
  463. sys_modules = module_globals.pop("sys.modules", None)
  464. if sys_modules is not None:
  465. if not isinstance(sys_modules, dict):
  466. raise RuntimeError(
  467. "'sys.modules' must be a dictionary not: {}".format(
  468. type(sys_modules)
  469. )
  470. )
  471. patcher = patch.dict(sys.modules, sys_modules)
  472. patcher.start()
  473. def cleanup_sys_modules(patcher, sys_modules):
  474. patcher.stop()
  475. del patcher
  476. del sys_modules
  477. self.addCleanup(cleanup_sys_modules, patcher, sys_modules)
  478. for key in module_globals:
  479. if not hasattr(module, key):
  480. if key in salt_dunders:
  481. setattr(module, key, {})
  482. else:
  483. setattr(module, key, None)
  484. if module_globals:
  485. patcher = patch.multiple(module, **module_globals)
  486. patcher.start()
  487. def cleanup_module_globals(patcher, module_globals):
  488. patcher.stop()
  489. del patcher
  490. del module_globals
  491. self.addCleanup(cleanup_module_globals, patcher, module_globals)
  492. if minion_funcs:
  493. # Since we autoloaded the minion_funcs, let's namespace the functions with the globals
  494. # used to patch above
  495. import salt.utils
  496. for func in minion_funcs:
  497. minion_funcs[func] = salt.utils.functools.namespaced_function(
  498. minion_funcs[func], module_globals, preserve_context=True
  499. )
  500. return setup_func(self)
  501. return wrapper
  502. def setup_loader_modules(self):
  503. raise NotImplementedError(
  504. "'{}.setup_loader_modules()' must be implemented".format(
  505. self.__class__.__name__
  506. )
  507. )
  508. class XMLEqualityMixin(object):
  509. def assertEqualXML(self, e1, e2):
  510. if six.PY3 and isinstance(e1, bytes):
  511. e1 = e1.decode("utf-8")
  512. if six.PY3 and isinstance(e2, bytes):
  513. e2 = e2.decode("utf-8")
  514. if isinstance(e1, six.string_types):
  515. e1 = etree.XML(e1)
  516. if isinstance(e2, six.string_types):
  517. e2 = etree.XML(e2)
  518. if e1.tag != e2.tag:
  519. return False
  520. if e1.text != e2.text:
  521. return False
  522. if e1.tail != e2.tail:
  523. return False
  524. if e1.attrib != e2.attrib:
  525. return False
  526. if len(e1) != len(e2):
  527. return False
  528. return all(self.assertEqualXML(c1, c2) for c1, c2 in zip(e1, e2))
  529. class SaltReturnAssertsMixin(object):
  530. def assertReturnSaltType(self, ret):
  531. try:
  532. self.assertTrue(isinstance(ret, dict))
  533. except AssertionError:
  534. raise AssertionError(
  535. "{0} is not dict. Salt returned: {1}".format(type(ret).__name__, ret)
  536. )
  537. def assertReturnNonEmptySaltType(self, ret):
  538. self.assertReturnSaltType(ret)
  539. try:
  540. self.assertNotEqual(ret, {})
  541. except AssertionError:
  542. raise AssertionError(
  543. "{} is equal to {}. Salt returned an empty dictionary."
  544. )
  545. def __return_valid_keys(self, keys):
  546. if isinstance(keys, tuple):
  547. # If it's a tuple, turn it into a list
  548. keys = list(keys)
  549. elif isinstance(keys, six.string_types):
  550. # If it's a string, make it a one item list
  551. keys = [keys]
  552. elif not isinstance(keys, list):
  553. # If we've reached here, it's a bad type passed to keys
  554. raise RuntimeError("The passed keys need to be a list")
  555. return keys
  556. def __getWithinSaltReturn(self, ret, keys):
  557. self.assertReturnNonEmptySaltType(ret)
  558. ret_data = []
  559. for part in six.itervalues(ret):
  560. keys = self.__return_valid_keys(keys)
  561. okeys = keys[:]
  562. try:
  563. ret_item = part[okeys.pop(0)]
  564. except (KeyError, TypeError):
  565. raise AssertionError(
  566. "Could not get ret{0} from salt's return: {1}".format(
  567. "".join(["['{0}']".format(k) for k in keys]), part
  568. )
  569. )
  570. while okeys:
  571. try:
  572. ret_item = ret_item[okeys.pop(0)]
  573. except (KeyError, TypeError):
  574. raise AssertionError(
  575. "Could not get ret{0} from salt's return: {1}".format(
  576. "".join(["['{0}']".format(k) for k in keys]), part
  577. )
  578. )
  579. ret_data.append(ret_item)
  580. return ret_data
  581. def assertSaltTrueReturn(self, ret):
  582. try:
  583. for saltret in self.__getWithinSaltReturn(ret, "result"):
  584. self.assertTrue(saltret)
  585. except AssertionError:
  586. log.info("Salt Full Return:\n{0}".format(pprint.pformat(ret)))
  587. try:
  588. raise AssertionError(
  589. "{result} is not True. Salt Comment:\n{comment}".format(
  590. **(next(six.itervalues(ret)))
  591. )
  592. )
  593. except (AttributeError, IndexError):
  594. raise AssertionError(
  595. "Failed to get result. Salt Returned:\n{0}".format(
  596. pprint.pformat(ret)
  597. )
  598. )
  599. def assertSaltFalseReturn(self, ret):
  600. try:
  601. for saltret in self.__getWithinSaltReturn(ret, "result"):
  602. self.assertFalse(saltret)
  603. except AssertionError:
  604. log.info("Salt Full Return:\n{0}".format(pprint.pformat(ret)))
  605. try:
  606. raise AssertionError(
  607. "{result} is not False. Salt Comment:\n{comment}".format(
  608. **(next(six.itervalues(ret)))
  609. )
  610. )
  611. except (AttributeError, IndexError):
  612. raise AssertionError(
  613. "Failed to get result. Salt Returned: {0}".format(ret)
  614. )
  615. def assertSaltNoneReturn(self, ret):
  616. try:
  617. for saltret in self.__getWithinSaltReturn(ret, "result"):
  618. self.assertIsNone(saltret)
  619. except AssertionError:
  620. log.info("Salt Full Return:\n{0}".format(pprint.pformat(ret)))
  621. try:
  622. raise AssertionError(
  623. "{result} is not None. Salt Comment:\n{comment}".format(
  624. **(next(six.itervalues(ret)))
  625. )
  626. )
  627. except (AttributeError, IndexError):
  628. raise AssertionError(
  629. "Failed to get result. Salt Returned: {0}".format(ret)
  630. )
  631. def assertInSaltComment(self, in_comment, ret):
  632. for saltret in self.__getWithinSaltReturn(ret, "comment"):
  633. self.assertIn(in_comment, saltret)
  634. def assertNotInSaltComment(self, not_in_comment, ret):
  635. for saltret in self.__getWithinSaltReturn(ret, "comment"):
  636. self.assertNotIn(not_in_comment, saltret)
  637. def assertSaltCommentRegexpMatches(self, ret, pattern):
  638. return self.assertInSaltReturnRegexpMatches(ret, pattern, "comment")
  639. def assertInSaltStateWarning(self, in_comment, ret):
  640. for saltret in self.__getWithinSaltReturn(ret, "warnings"):
  641. self.assertIn(in_comment, saltret)
  642. def assertNotInSaltStateWarning(self, not_in_comment, ret):
  643. for saltret in self.__getWithinSaltReturn(ret, "warnings"):
  644. self.assertNotIn(not_in_comment, saltret)
  645. def assertInSaltReturn(self, item_to_check, ret, keys):
  646. for saltret in self.__getWithinSaltReturn(ret, keys):
  647. self.assertIn(item_to_check, saltret)
  648. def assertNotInSaltReturn(self, item_to_check, ret, keys):
  649. for saltret in self.__getWithinSaltReturn(ret, keys):
  650. self.assertNotIn(item_to_check, saltret)
  651. def assertInSaltReturnRegexpMatches(self, ret, pattern, keys=()):
  652. for saltret in self.__getWithinSaltReturn(ret, keys):
  653. self.assertRegex(saltret, pattern)
  654. def assertSaltStateChangesEqual(self, ret, comparison, keys=()):
  655. keys = ["changes"] + self.__return_valid_keys(keys)
  656. for saltret in self.__getWithinSaltReturn(ret, keys):
  657. self.assertEqual(saltret, comparison)
  658. def assertSaltStateChangesNotEqual(self, ret, comparison, keys=()):
  659. keys = ["changes"] + self.__return_valid_keys(keys)
  660. for saltret in self.__getWithinSaltReturn(ret, keys):
  661. self.assertNotEqual(saltret, comparison)
  662. def _fetch_events(q, opts):
  663. """
  664. Collect events and store them
  665. """
  666. def _clean_queue():
  667. log.info("Cleaning queue!")
  668. while not q.empty():
  669. queue_item = q.get()
  670. queue_item.task_done()
  671. atexit.register(_clean_queue)
  672. event = salt.utils.event.get_event("minion", sock_dir=opts["sock_dir"], opts=opts)
  673. # Wait for event bus to be connected
  674. while not event.connect_pull(30):
  675. time.sleep(1)
  676. # Notify parent process that the event bus is connected
  677. q.put("CONNECTED")
  678. while True:
  679. try:
  680. events = event.get_event(full=False)
  681. except Exception as exc: # pylint: disable=broad-except
  682. # This is broad but we'll see all kinds of issues right now
  683. # if we drop the proc out from under the socket while we're reading
  684. log.exception("Exception caught while getting events %r", exc)
  685. q.put(events)
  686. class SaltMinionEventAssertsMixin(object):
  687. """
  688. Asserts to verify that a given event was seen
  689. """
  690. @classmethod
  691. def setUpClass(cls):
  692. opts = copy.deepcopy(RUNTIME_VARS.RUNTIME_CONFIGS["minion"])
  693. cls.q = multiprocessing.Queue()
  694. cls.fetch_proc = salt.utils.process.SignalHandlingProcess(
  695. target=_fetch_events,
  696. args=(cls.q, opts),
  697. name="Process-{}-Queue".format(cls.__name__),
  698. )
  699. cls.fetch_proc.start()
  700. # Wait for the event bus to be connected
  701. msg = cls.q.get(block=True)
  702. if msg != "CONNECTED":
  703. # Just in case something very bad happens
  704. raise RuntimeError("Unexpected message in test's event queue")
  705. @classmethod
  706. def tearDownClass(cls):
  707. cls.fetch_proc.join()
  708. del cls.q
  709. del cls.fetch_proc
  710. def assertMinionEventFired(self, tag):
  711. # TODO
  712. raise salt.exceptions.NotImplemented("assertMinionEventFired() not implemented")
  713. def assertMinionEventReceived(self, desired_event, timeout=5, sleep_time=0.5):
  714. start = time.time()
  715. while True:
  716. try:
  717. event = self.q.get(False)
  718. except Empty:
  719. time.sleep(sleep_time)
  720. if time.time() - start >= timeout:
  721. break
  722. continue
  723. if isinstance(event, dict):
  724. event.pop("_stamp")
  725. if desired_event == event:
  726. self.fetch_proc.terminate()
  727. return True
  728. if time.time() - start >= timeout:
  729. break
  730. self.fetch_proc.terminate()
  731. raise AssertionError(
  732. "Event {0} was not received by minion".format(desired_event)
  733. )