mixins.py 27 KB

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