1
0

mixins.py 31 KB

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