1
0

test_state.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787
  1. # -*- coding: utf-8 -*-
  2. '''
  3. Tests for the state runner
  4. '''
  5. # Import Python Libs
  6. from __future__ import absolute_import, print_function, unicode_literals
  7. import errno
  8. import logging
  9. import os
  10. import shutil
  11. import signal
  12. import tempfile
  13. import time
  14. import textwrap
  15. import threading
  16. # Import Salt Testing Libs
  17. from tests.support.runtests import RUNTIME_VARS
  18. from tests.support.case import ShellCase
  19. from tests.support.helpers import flaky, expensiveTest
  20. from tests.support.mock import MagicMock, patch
  21. from tests.support.unit import skipIf
  22. # Import Salt Libs
  23. import salt.exceptions
  24. import salt.utils.platform
  25. import salt.utils.event
  26. import salt.utils.files
  27. import salt.utils.json
  28. import salt.utils.stringutils
  29. import salt.utils.yaml
  30. # Import 3rd-party libs
  31. from salt.ext import six
  32. from salt.ext.six.moves import queue
  33. log = logging.getLogger(__name__)
  34. @flaky
  35. class StateRunnerTest(ShellCase):
  36. '''
  37. Test the state runner.
  38. '''
  39. def add_to_queue(self, q, cmd):
  40. '''
  41. helper method to add salt-run
  42. return data to a queue
  43. '''
  44. ret = self.run_run(cmd)
  45. q.put(ret)
  46. q.task_done()
  47. def test_orchestrate_output(self):
  48. '''
  49. Ensure the orchestrate runner outputs useful state data.
  50. In Issue #31330, the output only contains ['outputter:', ' highstate'],
  51. and not the full stateful return. This tests ensures we don't regress in that
  52. manner again.
  53. Also test against some sample "good" output that would be included in a correct
  54. orchestrate run.
  55. '''
  56. ret_output = self.run_run('state.orchestrate orch.simple')
  57. bad_out = ['outputter:', ' highstate']
  58. good_out = [' Function: salt.state',
  59. ' Result: True',
  60. 'Succeeded: 1 (changed=1)',
  61. 'Failed: 0',
  62. 'Total states run: 1']
  63. # First, check that we don't have the "bad" output that was displaying in
  64. # Issue #31330 where only the highstate outputter was listed
  65. assert bad_out != ret_output
  66. # Now test that some expected good sample output is present in the return.
  67. for item in good_out:
  68. assert item in ret_output
  69. def test_orchestrate_nested(self):
  70. '''
  71. test salt-run state.orchestrate and failhard with nested orchestration
  72. '''
  73. if os.path.exists('/tmp/ewu-2016-12-13'):
  74. os.remove('/tmp/ewu-2016-12-13')
  75. _, code = self.run_run(
  76. 'state.orchestrate nested-orch.outer',
  77. with_retcode=True)
  78. assert os.path.exists('/tmp/ewu-2016-12-13') is False
  79. assert code != 0
  80. def test_orchestrate_with_mine(self):
  81. '''
  82. test salt-run state.orchestrate with mine.get call in sls
  83. '''
  84. fail_time = time.time() + 120
  85. self.run_run('mine.update "*"')
  86. exp_ret = 'Succeeded: 1 (changed=1)'
  87. while True:
  88. ret = self.run_run('state.orchestrate orch.mine')
  89. try:
  90. assert exp_ret in ret
  91. break
  92. except AssertionError:
  93. if time.time() > fail_time:
  94. self.fail('"{0}" was not found in the orchestration call'.format(exp_ret))
  95. def test_orchestrate_state_and_function_failure(self):
  96. '''
  97. Ensure that returns from failed minions are in the changes dict where
  98. they belong, so they can be programatically analyzed.
  99. See https://github.com/saltstack/salt/issues/43204
  100. '''
  101. self.run_run('saltutil.sync_modules')
  102. ret = salt.utils.json.loads(
  103. '\n'.join(
  104. self.run_run('state.orchestrate orch.issue43204 --out=json')
  105. )
  106. )
  107. # Drill down to the changes dict
  108. state_ret = ret['data']['master']['salt_|-Step01_|-Step01_|-state']['changes']
  109. func_ret = ret['data']['master']['salt_|-Step02_|-runtests_helpers.nonzero_retcode_return_false_|-function']['changes']
  110. # Remove duration and start time from the results, since they would
  111. # vary with each run and that would make it impossible to test.
  112. for item in ('duration', 'start_time'):
  113. state_ret['ret']['minion']['test_|-test fail with changes_|-test fail with changes_|-fail_with_changes'].pop(item)
  114. self.assertEqual(
  115. state_ret,
  116. {
  117. 'out': 'highstate',
  118. 'ret': {
  119. 'minion': {
  120. 'test_|-test fail with changes_|-test fail with changes_|-fail_with_changes': {
  121. '__id__': 'test fail with changes',
  122. '__run_num__': 0,
  123. '__sls__': 'orch.issue43204.fail_with_changes',
  124. 'changes': {
  125. 'testing': {
  126. 'new': 'Something pretended to change',
  127. 'old': 'Unchanged'
  128. }
  129. },
  130. 'comment': 'Failure!',
  131. 'name': 'test fail with changes',
  132. 'result': False,
  133. }
  134. }
  135. }
  136. }
  137. )
  138. self.assertEqual(
  139. func_ret,
  140. {'out': 'highstate', 'ret': {'minion': False}}
  141. )
  142. def test_orchestrate_target_exists(self):
  143. '''
  144. test orchestration when target exists
  145. while using multiple states
  146. '''
  147. ret = self.run_run('state.orchestrate orch.target-exists')
  148. first = [' ID: core',
  149. ' Function: salt.state',
  150. ' Result: True']
  151. second = [' ID: test-state',
  152. ' Function: salt.state',
  153. ' Result: True']
  154. third = [' ID: cmd.run',
  155. ' Function: salt.function',
  156. ' Result: True']
  157. ret_out = [first, second, third]
  158. for out in ret_out:
  159. for item in out:
  160. assert item in ret
  161. def test_orchestrate_retcode(self):
  162. '''
  163. Test orchestration with nonzero retcode set in __context__
  164. '''
  165. self.run_run('saltutil.sync_runners')
  166. self.run_run('saltutil.sync_wheel')
  167. ret = '\n'.join(self.run_run('state.orchestrate orch.retcode'))
  168. for result in (' ID: test_runner_success\n'
  169. ' Function: salt.runner\n'
  170. ' Name: runtests_helpers.success\n'
  171. ' Result: True',
  172. ' ID: test_runner_failure\n'
  173. ' Function: salt.runner\n'
  174. ' Name: runtests_helpers.failure\n'
  175. ' Result: False',
  176. ' ID: test_wheel_success\n'
  177. ' Function: salt.wheel\n'
  178. ' Name: runtests_helpers.success\n'
  179. ' Result: True',
  180. ' ID: test_wheel_failure\n'
  181. ' Function: salt.wheel\n'
  182. ' Name: runtests_helpers.failure\n'
  183. ' Result: False'):
  184. self.assertIn(result, ret)
  185. def test_orchestrate_target_doesnt_exist(self):
  186. '''
  187. test orchestration when target doesn't exist
  188. while using multiple states
  189. '''
  190. ret = self.run_run('state.orchestrate orch.target-doesnt-exists')
  191. first = ['No minions matched the target. No command was sent, no jid was assigned.',
  192. ' ID: core',
  193. ' Function: salt.state',
  194. ' Result: False']
  195. second = [' ID: test-state',
  196. ' Function: salt.state',
  197. ' Result: True']
  198. third = [' ID: cmd.run',
  199. ' Function: salt.function',
  200. ' Result: True']
  201. ret_out = [first, second, third]
  202. for out in ret_out:
  203. for item in out:
  204. assert item in ret
  205. def test_orchestrate_batch_with_failhard_error(self):
  206. '''
  207. test orchestration properly stops with failhard and batch.
  208. '''
  209. ret = self.run_run('state.orchestrate orch.batch --out=json -l critical')
  210. ret_json = salt.utils.json.loads('\n'.join(ret))
  211. retcode = ret_json['retcode']
  212. result = ret_json['data']['master']['salt_|-call_fail_state_|-call_fail_state_|-state']['result']
  213. changes = ret_json['data']['master']['salt_|-call_fail_state_|-call_fail_state_|-state']['changes']
  214. # Looks like there is a platform differences in execution.
  215. # I see empty changes dict in MacOS for some reason. Maybe it's a bug?
  216. if changes:
  217. changes_ret = changes['ret']
  218. # Debug
  219. print('Retcode: {}'.format(retcode))
  220. print('Changes: {}'.format(changes))
  221. print('Result: {}'.format(result))
  222. assert retcode != 0
  223. assert result is False
  224. if changes:
  225. # The execution should stop after first error, so return dict should contain only one minion
  226. assert len(changes_ret) == 1
  227. def test_state_event(self):
  228. '''
  229. test to ensure state.event
  230. runner returns correct data
  231. '''
  232. q = queue.Queue(maxsize=0)
  233. cmd = 'state.event salt/job/*/new count=1'
  234. expect = '"minions": ["minion"]'
  235. server_thread = threading.Thread(target=self.add_to_queue, args=(q, cmd))
  236. server_thread.setDaemon(True)
  237. server_thread.start()
  238. while q.empty():
  239. self.run_salt('minion test.ping --static')
  240. out = q.get()
  241. assert expect in six.text_type(out)
  242. server_thread.join()
  243. def test_orchestrate_subset(self):
  244. '''
  245. test orchestration state using subset
  246. '''
  247. ret = self.run_run('state.orchestrate orch.subset', timeout=500)
  248. def count(thing, listobj):
  249. return sum([obj.strip() == thing for obj in listobj])
  250. assert count('ID: test subset', ret) == 1
  251. assert count('Succeeded: 1', ret) == 1
  252. assert count('Failed: 0', ret) == 1
  253. def test_orchestrate_salt_function_return_false_failure(self):
  254. '''
  255. Ensure that functions that only return False in the return
  256. are flagged as failed when run as orchestrations.
  257. See https://github.com/saltstack/salt/issues/30367
  258. '''
  259. self.run_run('saltutil.sync_modules')
  260. ret = salt.utils.json.loads(
  261. '\n'.join(
  262. self.run_run('state.orchestrate orch.issue30367 --out=json')
  263. )
  264. )
  265. # Drill down to the changes dict
  266. state_result = ret['data']['master']['salt_|-deploy_check_|-test.false_|-function']['result']
  267. func_ret = ret['data']['master']['salt_|-deploy_check_|-test.false_|-function']['changes']
  268. assert state_result is False
  269. self.assertEqual(
  270. func_ret,
  271. {'out': 'highstate', 'ret': {'minion': False}}
  272. )
  273. @skipIf(salt.utils.platform.is_windows(), '*NIX-only test')
  274. @flaky
  275. class OrchEventTest(ShellCase):
  276. '''
  277. Tests for orchestration events
  278. '''
  279. def setUp(self):
  280. self.timeout = 60
  281. self.master_d_dir = os.path.join(self.config_dir, 'master.d')
  282. try:
  283. os.makedirs(self.master_d_dir)
  284. except OSError as exc:
  285. if exc.errno != errno.EEXIST:
  286. raise
  287. self.conf = tempfile.NamedTemporaryFile(
  288. mode='w',
  289. suffix='.conf',
  290. dir=self.master_d_dir,
  291. delete=True,
  292. )
  293. self.base_env = tempfile.mkdtemp(dir=RUNTIME_VARS.TMP)
  294. self.addCleanup(shutil.rmtree, self.base_env)
  295. self.addCleanup(self.conf.close)
  296. for attr in ('timeout', 'master_d_dir', 'conf', 'base_env'):
  297. self.addCleanup(delattr, self, attr)
  298. # Force a reload of the configuration now that our temp config file has
  299. # been removed.
  300. self.addCleanup(self.run_run_plus, 'test.arg', __reload_config=True)
  301. def alarm_handler(self, signal, frame):
  302. raise Exception('Timeout of {0} seconds reached'.format(self.timeout))
  303. def write_conf(self, data):
  304. '''
  305. Dump the config dict to the conf file
  306. '''
  307. self.conf.write(salt.utils.yaml.safe_dump(data, default_flow_style=False))
  308. self.conf.flush()
  309. @expensiveTest
  310. def test_jid_in_ret_event(self):
  311. '''
  312. Test to confirm that the ret event for the orchestration contains the
  313. jid for the jobs spawned.
  314. '''
  315. self.write_conf({
  316. 'fileserver_backend': ['roots'],
  317. 'file_roots': {
  318. 'base': [self.base_env],
  319. },
  320. })
  321. state_sls = os.path.join(self.base_env, 'test_state.sls')
  322. with salt.utils.files.fopen(state_sls, 'w') as fp_:
  323. fp_.write(salt.utils.stringutils.to_str(textwrap.dedent('''
  324. date:
  325. cmd.run
  326. ''')))
  327. orch_sls = os.path.join(self.base_env, 'test_orch.sls')
  328. with salt.utils.files.fopen(orch_sls, 'w') as fp_:
  329. fp_.write(salt.utils.stringutils.to_str(textwrap.dedent('''
  330. date_cmd:
  331. salt.state:
  332. - tgt: minion
  333. - sls: test_state
  334. ping_minion:
  335. salt.function:
  336. - name: test.ping
  337. - tgt: minion
  338. fileserver.file_list:
  339. salt.runner
  340. config.values:
  341. salt.wheel
  342. ''')))
  343. listener = salt.utils.event.get_event(
  344. 'master',
  345. sock_dir=self.master_opts['sock_dir'],
  346. transport=self.master_opts['transport'],
  347. opts=self.master_opts)
  348. jid = self.run_run_plus(
  349. 'state.orchestrate',
  350. 'test_orch',
  351. __reload_config=True).get('jid')
  352. if jid is None:
  353. raise Exception('jid missing from run_run_plus output')
  354. signal.signal(signal.SIGALRM, self.alarm_handler)
  355. signal.alarm(self.timeout)
  356. try:
  357. while True:
  358. event = listener.get_event(full=True)
  359. if event is None:
  360. continue
  361. if event['tag'] == 'salt/run/{0}/ret'.format(jid):
  362. # Don't wrap this in a try/except. We want to know if the
  363. # data structure is different from what we expect!
  364. ret = event['data']['return']['data']['master']
  365. for job in ret:
  366. self.assertTrue('__jid__' in ret[job])
  367. break
  368. finally:
  369. del listener
  370. signal.alarm(0)
  371. @expensiveTest
  372. def test_parallel_orchestrations(self):
  373. '''
  374. Test to confirm that the parallel state requisite works in orch
  375. we do this by running 10 test.sleep's of 10 seconds, and insure it only takes roughly 10s
  376. '''
  377. self.write_conf({
  378. 'fileserver_backend': ['roots'],
  379. 'file_roots': {
  380. 'base': [self.base_env],
  381. },
  382. })
  383. orch_sls = os.path.join(self.base_env, 'test_par_orch.sls')
  384. with salt.utils.files.fopen(orch_sls, 'w') as fp_:
  385. fp_.write(textwrap.dedent('''
  386. {% for count in range(1, 20) %}
  387. sleep {{ count }}:
  388. module.run:
  389. - name: test.sleep
  390. - length: 10
  391. - parallel: True
  392. {% endfor %}
  393. sleep 21:
  394. module.run:
  395. - name: test.sleep
  396. - length: 10
  397. - parallel: True
  398. - require:
  399. - module: sleep 1
  400. '''))
  401. orch_sls = os.path.join(self.base_env, 'test_par_orch.sls')
  402. listener = salt.utils.event.get_event(
  403. 'master',
  404. sock_dir=self.master_opts['sock_dir'],
  405. transport=self.master_opts['transport'],
  406. opts=self.master_opts)
  407. start_time = time.time()
  408. jid = self.run_run_plus(
  409. 'state.orchestrate',
  410. 'test_par_orch',
  411. __reload_config=True).get('jid')
  412. if jid is None:
  413. raise Exception('jid missing from run_run_plus output')
  414. signal.signal(signal.SIGALRM, self.alarm_handler)
  415. signal.alarm(self.timeout)
  416. received = False
  417. try:
  418. while True:
  419. event = listener.get_event(full=True)
  420. if event is None:
  421. continue
  422. # if we receive the ret for this job before self.timeout (60),
  423. # the test is implicitly sucessful; if it were happening in serial it would be
  424. # atleast 110 seconds.
  425. if event['tag'] == 'salt/run/{0}/ret'.format(jid):
  426. received = True
  427. # Don't wrap this in a try/except. We want to know if the
  428. # data structure is different from what we expect!
  429. ret = event['data']['return']['data']['master']
  430. for state in ret:
  431. data = ret[state]
  432. # we expect each duration to be greater than 10s
  433. self.assertTrue(data['duration'] > 10000)
  434. break
  435. # self confirm that the total runtime is roughly 30s (left 10s for buffer)
  436. self.assertTrue((time.time() - start_time) < 40)
  437. finally:
  438. self.assertTrue(received)
  439. del listener
  440. signal.alarm(0)
  441. @expensiveTest
  442. def test_orchestration_soft_kill(self):
  443. '''
  444. Test to confirm that the parallel state requisite works in orch
  445. we do this by running 10 test.sleep's of 10 seconds, and insure it only takes roughly 10s
  446. '''
  447. self.write_conf({
  448. 'fileserver_backend': ['roots'],
  449. 'file_roots': {
  450. 'base': [self.base_env],
  451. },
  452. })
  453. orch_sls = os.path.join(self.base_env, 'two_stage_orch_kill.sls')
  454. with salt.utils.files.fopen(orch_sls, 'w') as fp_:
  455. fp_.write(textwrap.dedent('''
  456. stage_one:
  457. test.succeed_without_changes
  458. stage_two:
  459. test.fail_without_changes
  460. '''))
  461. listener = salt.utils.event.get_event(
  462. 'master',
  463. sock_dir=self.master_opts['sock_dir'],
  464. transport=self.master_opts['transport'],
  465. opts=self.master_opts)
  466. mock_jid = '20131219120000000000'
  467. self.run_run('state.soft_kill {0} stage_two'.format(mock_jid))
  468. with patch('salt.utils.jid.gen_jid', MagicMock(return_value=mock_jid)):
  469. jid = self.run_run_plus(
  470. 'state.orchestrate',
  471. 'two_stage_orch_kill',
  472. __reload_config=True).get('jid')
  473. if jid is None:
  474. raise Exception('jid missing from run_run_plus output')
  475. signal.signal(signal.SIGALRM, self.alarm_handler)
  476. signal.alarm(self.timeout)
  477. received = False
  478. try:
  479. while True:
  480. event = listener.get_event(full=True)
  481. if event is None:
  482. continue
  483. # Ensure that stage_two of the state does not run
  484. if event['tag'] == 'salt/run/{0}/ret'.format(jid):
  485. received = True
  486. # Don't wrap this in a try/except. We want to know if the
  487. # data structure is different from what we expect!
  488. ret = event['data']['return']['data']['master']
  489. self.assertNotIn('test_|-stage_two_|-stage_two_|-fail_without_changes', ret)
  490. break
  491. finally:
  492. self.assertTrue(received)
  493. del listener
  494. signal.alarm(0)
  495. def test_orchestration_with_pillar_dot_items(self):
  496. '''
  497. Test to confirm when using a state file that includes other state file, if
  498. one of those state files includes pillar related functions that will not
  499. be pulling from the pillar cache that all the state files are available and
  500. the file_roots has been preserved. See issues #48277 and #46986.
  501. '''
  502. self.write_conf({
  503. 'fileserver_backend': ['roots'],
  504. 'file_roots': {
  505. 'base': [self.base_env],
  506. },
  507. })
  508. orch_sls = os.path.join(self.base_env, 'main.sls')
  509. with salt.utils.files.fopen(orch_sls, 'w') as fp_:
  510. fp_.write(textwrap.dedent('''
  511. include:
  512. - one
  513. - two
  514. - three
  515. '''))
  516. orch_sls = os.path.join(self.base_env, 'one.sls')
  517. with salt.utils.files.fopen(orch_sls, 'w') as fp_:
  518. fp_.write(textwrap.dedent('''
  519. {%- set foo = salt['saltutil.runner']('pillar.show_pillar') %}
  520. placeholder_one:
  521. test.succeed_without_changes
  522. '''))
  523. orch_sls = os.path.join(self.base_env, 'two.sls')
  524. with salt.utils.files.fopen(orch_sls, 'w') as fp_:
  525. fp_.write(textwrap.dedent('''
  526. placeholder_two:
  527. test.succeed_without_changes
  528. '''))
  529. orch_sls = os.path.join(self.base_env, 'three.sls')
  530. with salt.utils.files.fopen(orch_sls, 'w') as fp_:
  531. fp_.write(textwrap.dedent('''
  532. placeholder_three:
  533. test.succeed_without_changes
  534. '''))
  535. orch_sls = os.path.join(self.base_env, 'main.sls')
  536. listener = salt.utils.event.get_event(
  537. 'master',
  538. sock_dir=self.master_opts['sock_dir'],
  539. transport=self.master_opts['transport'],
  540. opts=self.master_opts)
  541. jid = self.run_run_plus(
  542. 'state.orchestrate',
  543. 'main',
  544. __reload_config=True).get('jid')
  545. if jid is None:
  546. raise salt.exceptions.SaltInvocationError('jid missing from run_run_plus output')
  547. signal.signal(signal.SIGALRM, self.alarm_handler)
  548. signal.alarm(self.timeout)
  549. received = False
  550. try:
  551. while True:
  552. event = listener.get_event(full=True)
  553. if event is None:
  554. continue
  555. if event.get('tag', '') == 'salt/run/{0}/ret'.format(jid):
  556. received = True
  557. # Don't wrap this in a try/except. We want to know if the
  558. # data structure is different from what we expect!
  559. ret = event['data']['return']['data']['master']
  560. for state in ret:
  561. data = ret[state]
  562. # Each state should be successful
  563. self.assertEqual(data['comment'], 'Success!')
  564. break
  565. finally:
  566. self.assertTrue(received)
  567. del listener
  568. signal.alarm(0)
  569. def test_orchestration_onchanges_and_prereq(self):
  570. '''
  571. Test to confirm that the parallel state requisite works in orch
  572. we do this by running 10 test.sleep's of 10 seconds, and insure it only takes roughly 10s
  573. '''
  574. self.write_conf({
  575. 'fileserver_backend': ['roots'],
  576. 'file_roots': {
  577. 'base': [self.base_env],
  578. },
  579. })
  580. orch_sls = os.path.join(self.base_env, 'orch.sls')
  581. with salt.utils.files.fopen(orch_sls, 'w') as fp_:
  582. fp_.write(textwrap.dedent('''
  583. manage_a_file:
  584. salt.state:
  585. - tgt: minion
  586. - sls:
  587. - orch.req_test
  588. do_onchanges:
  589. salt.function:
  590. - tgt: minion
  591. - name: test.ping
  592. - onchanges:
  593. - salt: manage_a_file
  594. do_prereq:
  595. salt.function:
  596. - tgt: minion
  597. - name: test.ping
  598. - prereq:
  599. - salt: manage_a_file
  600. '''))
  601. listener = salt.utils.event.get_event(
  602. 'master',
  603. sock_dir=self.master_opts['sock_dir'],
  604. transport=self.master_opts['transport'],
  605. opts=self.master_opts)
  606. try:
  607. jid1 = self.run_run_plus(
  608. 'state.orchestrate',
  609. 'orch',
  610. test=True,
  611. __reload_config=True).get('jid')
  612. # Run for real to create the file
  613. self.run_run_plus(
  614. 'state.orchestrate',
  615. 'orch',
  616. __reload_config=True).get('jid')
  617. # Run again in test mode. Since there were no changes, the
  618. # requisites should not fire.
  619. jid2 = self.run_run_plus(
  620. 'state.orchestrate',
  621. 'orch',
  622. test=True,
  623. __reload_config=True).get('jid')
  624. finally:
  625. try:
  626. os.remove(os.path.join(RUNTIME_VARS.TMP, 'orch.req_test'))
  627. except OSError:
  628. pass
  629. assert jid1 is not None
  630. assert jid2 is not None
  631. tags = {'salt/run/{0}/ret'.format(x): x for x in (jid1, jid2)}
  632. ret = {}
  633. signal.signal(signal.SIGALRM, self.alarm_handler)
  634. signal.alarm(self.timeout)
  635. try:
  636. while True:
  637. event = listener.get_event(full=True)
  638. if event is None:
  639. continue
  640. if event['tag'] in tags:
  641. ret[tags.pop(event['tag'])] = self.repack_state_returns(
  642. event['data']['return']['data']['master']
  643. )
  644. if not tags:
  645. # If tags is empty, we've grabbed all the returns we
  646. # wanted, so let's stop listening to the event bus.
  647. break
  648. finally:
  649. del listener
  650. signal.alarm(0)
  651. for sls_id in ('manage_a_file', 'do_onchanges', 'do_prereq'):
  652. # The first time through, all three states should have a None
  653. # result, while the second time through, they should all have a
  654. # True result.
  655. assert ret[jid1][sls_id]['result'] is None, \
  656. 'result of {0} ({1}) is not None'.format(
  657. sls_id,
  658. ret[jid1][sls_id]['result'])
  659. assert ret[jid2][sls_id]['result'] is True, \
  660. 'result of {0} ({1}) is not True'.format(
  661. sls_id,
  662. ret[jid2][sls_id]['result'])
  663. # The file.managed state should have shown changes in the test mode
  664. # return data.
  665. assert ret[jid1]['manage_a_file']['changes']
  666. # After the file was created, running again in test mode should have
  667. # shown no changes.
  668. assert not ret[jid2]['manage_a_file']['changes'], \
  669. ret[jid2]['manage_a_file']['changes']