mixins.py 30 KB

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