mixins.py 25 KB

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