mixins.py 28 KB

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