test_state.py 79 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034
  1. # -*- coding: utf-8 -*-
  2. # Import Python libs
  3. from __future__ import absolute_import, print_function, unicode_literals
  4. import logging
  5. import os
  6. import shutil
  7. import sys
  8. import tempfile
  9. import textwrap
  10. import threading
  11. import time
  12. # Import Salt Testing libs
  13. from tests.support.case import ModuleCase
  14. from tests.support.helpers import with_tempdir
  15. from tests.support.unit import skipIf
  16. from tests.support.paths import BASE_FILES, TMP, TMP_PILLAR_TREE
  17. from tests.support.mixins import SaltReturnAssertsMixin
  18. # Import Salt libs
  19. import salt.utils.atomicfile
  20. import salt.utils.files
  21. import salt.utils.path
  22. import salt.utils.platform
  23. import salt.utils.stringutils
  24. from salt.modules.virtualenv_mod import KNOWN_BINARY_NAMES
  25. # Import 3rd-party libs
  26. from salt.ext import six
  27. log = logging.getLogger(__name__)
  28. DEFAULT_ENDING = salt.utils.stringutils.to_bytes(os.linesep)
  29. def trim_line_end(line):
  30. '''
  31. Remove CRLF or LF from the end of line.
  32. '''
  33. if line[-2:] == salt.utils.stringutils.to_bytes('\r\n'):
  34. return line[:-2]
  35. elif line[-1:] == salt.utils.stringutils.to_bytes('\n'):
  36. return line[:-1]
  37. raise Exception("Invalid line ending")
  38. def reline(source, dest, force=False, ending=DEFAULT_ENDING):
  39. '''
  40. Normalize the line endings of a file.
  41. '''
  42. fp, tmp = tempfile.mkstemp()
  43. os.close(fp)
  44. with salt.utils.files.fopen(tmp, 'wb') as tmp_fd:
  45. with salt.utils.files.fopen(source, 'rb') as fd:
  46. lines = fd.readlines()
  47. for line in lines:
  48. line_noend = trim_line_end(line)
  49. tmp_fd.write(line_noend + ending)
  50. if os.path.exists(dest) and force:
  51. os.remove(dest)
  52. os.rename(tmp, dest)
  53. class StateModuleTest(ModuleCase, SaltReturnAssertsMixin):
  54. '''
  55. Validate the state module
  56. '''
  57. maxDiff = None
  58. @classmethod
  59. def setUpClass(cls):
  60. def _reline(path, ending=DEFAULT_ENDING):
  61. '''
  62. Normalize the line endings of a file.
  63. '''
  64. with salt.utils.files.fopen(path, 'rb') as fhr:
  65. lines = fhr.read().splitlines()
  66. with salt.utils.atomicfile.atomic_open(path, 'wb') as fhw:
  67. for line in lines:
  68. fhw.write(line + ending)
  69. destpath = os.path.join(BASE_FILES, 'testappend', 'firstif')
  70. destpath = os.path.join(BASE_FILES, 'testappend', 'secondif')
  71. def test_show_highstate(self):
  72. '''
  73. state.show_highstate
  74. '''
  75. high = self.run_function('state.show_highstate')
  76. destpath = os.path.join(TMP, 'testfile')
  77. self.assertTrue(isinstance(high, dict))
  78. self.assertTrue(destpath in high)
  79. self.assertEqual(high[destpath]['__env__'], 'base')
  80. def test_show_lowstate(self):
  81. '''
  82. state.show_lowstate
  83. '''
  84. low = self.run_function('state.show_lowstate')
  85. self.assertTrue(isinstance(low, list))
  86. self.assertTrue(isinstance(low[0], dict))
  87. def test_catch_recurse(self):
  88. '''
  89. state.show_sls used to catch a recursive ref
  90. '''
  91. err = self.run_function('state.sls', mods='recurse_fail')
  92. self.assertIn('recursive', err[0])
  93. def test_no_recurse(self):
  94. '''
  95. verify that a sls structure is NOT a recursive ref
  96. '''
  97. sls = self.run_function('state.show_sls', mods='recurse_ok')
  98. self.assertIn('snmpd', sls)
  99. def test_no_recurse_two(self):
  100. '''
  101. verify that a sls structure is NOT a recursive ref
  102. '''
  103. sls = self.run_function('state.show_sls', mods='recurse_ok_two')
  104. self.assertIn('/etc/nagios/nrpe.cfg', sls)
  105. def test_running_dictionary_consistency(self):
  106. '''
  107. Test the structure of the running dictionary so we don't change it
  108. without deprecating/documenting the change
  109. '''
  110. running_dict_fields = [
  111. '__id__',
  112. '__run_num__',
  113. '__sls__',
  114. 'changes',
  115. 'comment',
  116. 'duration',
  117. 'name',
  118. 'result',
  119. 'start_time',
  120. ]
  121. sls = self.run_function('state.single',
  122. fun='test.succeed_with_changes',
  123. name='gndn')
  124. for state, ret in sls.items():
  125. for field in running_dict_fields:
  126. self.assertIn(field, ret)
  127. def test_running_dictionary_key_sls(self):
  128. '''
  129. Ensure the __sls__ key is either null or a string
  130. '''
  131. sls1 = self.run_function('state.single',
  132. fun='test.succeed_with_changes',
  133. name='gndn')
  134. sls2 = self.run_function('state.sls', mods='gndn')
  135. for state, ret in sls1.items():
  136. self.assertTrue(isinstance(ret['__sls__'], type(None)))
  137. for state, ret in sls2.items():
  138. self.assertTrue(isinstance(ret['__sls__'], six.string_types))
  139. def _remove_request_cache_file(self):
  140. '''
  141. remove minion state request file
  142. '''
  143. cache_file = os.path.join(self.get_config('minion')['cachedir'], 'req_state.p')
  144. if os.path.exists(cache_file):
  145. os.remove(cache_file)
  146. def test_request(self):
  147. '''
  148. verify sending a state request to the minion(s)
  149. '''
  150. self._remove_request_cache_file()
  151. ret = self.run_function('state.request', mods='modules.state.requested')
  152. result = ret['cmd_|-count_root_dir_contents_|-ls -a / | wc -l_|-run']['result']
  153. self.assertEqual(result, None)
  154. def test_check_request(self):
  155. '''
  156. verify checking a state request sent to the minion(s)
  157. '''
  158. self._remove_request_cache_file()
  159. self.run_function('state.request', mods='modules.state.requested')
  160. ret = self.run_function('state.check_request')
  161. result = ret['default']['test_run']['cmd_|-count_root_dir_contents_|-ls -a / | wc -l_|-run']['result']
  162. self.assertEqual(result, None)
  163. def test_clear_request(self):
  164. '''
  165. verify clearing a state request sent to the minion(s)
  166. '''
  167. self._remove_request_cache_file()
  168. self.run_function('state.request', mods='modules.state.requested')
  169. ret = self.run_function('state.clear_request')
  170. self.assertTrue(ret)
  171. def test_run_request_succeeded(self):
  172. '''
  173. verify running a state request sent to the minion(s)
  174. '''
  175. self._remove_request_cache_file()
  176. if salt.utils.platform.is_windows():
  177. self.run_function('state.request', mods='modules.state.requested_win')
  178. else:
  179. self.run_function('state.request', mods='modules.state.requested')
  180. ret = self.run_function('state.run_request')
  181. if salt.utils.platform.is_windows():
  182. key = 'cmd_|-count_root_dir_contents_|-Get-ChildItem C:\\\\ | Measure-Object | %{$_.Count}_|-run'
  183. else:
  184. key = 'cmd_|-count_root_dir_contents_|-ls -a / | wc -l_|-run'
  185. result = ret[key]['result']
  186. self.assertTrue(result)
  187. def test_run_request_failed_no_request_staged(self):
  188. '''
  189. verify not running a state request sent to the minion(s)
  190. '''
  191. self._remove_request_cache_file()
  192. self.run_function('state.request', mods='modules.state.requested')
  193. self.run_function('state.clear_request')
  194. ret = self.run_function('state.run_request')
  195. self.assertEqual(ret, {})
  196. @with_tempdir()
  197. def test_issue_1896_file_append_source(self, base_dir):
  198. '''
  199. Verify that we can append a file's contents
  200. '''
  201. testfile = os.path.join(base_dir, 'test.append')
  202. ret = self.run_state('file.touch', name=testfile)
  203. self.assertSaltTrueReturn(ret)
  204. ret = self.run_state(
  205. 'file.append',
  206. name=testfile,
  207. source='salt://testappend/firstif')
  208. self.assertSaltTrueReturn(ret)
  209. ret = self.run_state(
  210. 'file.append',
  211. name=testfile,
  212. source='salt://testappend/secondif')
  213. self.assertSaltTrueReturn(ret)
  214. with salt.utils.files.fopen(testfile, 'r') as fp_:
  215. testfile_contents = salt.utils.stringutils.to_unicode(fp_.read())
  216. contents = textwrap.dedent('''\
  217. # set variable identifying the chroot you work in (used in the prompt below)
  218. if [ -z "$debian_chroot" ] && [ -r /etc/debian_chroot ]; then
  219. debian_chroot=$(cat /etc/debian_chroot)
  220. fi
  221. # enable bash completion in interactive shells
  222. if [ -f /etc/bash_completion ] && ! shopt -oq posix; then
  223. . /etc/bash_completion
  224. fi
  225. ''')
  226. if salt.utils.platform.is_windows():
  227. new_contents = contents.splitlines()
  228. contents = os.linesep.join(new_contents)
  229. contents += os.linesep
  230. self.assertMultiLineEqual(contents, testfile_contents)
  231. ret = self.run_state(
  232. 'file.append',
  233. name=testfile,
  234. source='salt://testappend/secondif')
  235. self.assertSaltTrueReturn(ret)
  236. ret = self.run_state(
  237. 'file.append',
  238. name=testfile,
  239. source='salt://testappend/firstif')
  240. self.assertSaltTrueReturn(ret)
  241. with salt.utils.files.fopen(testfile, 'r') as fp_:
  242. testfile_contents = salt.utils.stringutils.to_unicode(fp_.read())
  243. self.assertMultiLineEqual(contents, testfile_contents)
  244. def test_issue_1876_syntax_error(self):
  245. '''
  246. verify that we catch the following syntax error::
  247. /tmp/salttest/issue-1876:
  248. file:
  249. - managed
  250. - source: salt://testfile
  251. file.append:
  252. - text: foo
  253. '''
  254. testfile = os.path.join(TMP, 'issue-1876')
  255. sls = self.run_function('state.sls', mods='issue-1876')
  256. self.assertIn(
  257. 'ID \'{0}\' in SLS \'issue-1876\' contains multiple state '
  258. 'declarations of the same type'.format(testfile),
  259. sls
  260. )
  261. def test_issue_1879_too_simple_contains_check(self):
  262. expected = textwrap.dedent('''\
  263. # set variable identifying the chroot you work in (used in the prompt below)
  264. if [ -z "$debian_chroot" ] && [ -r /etc/debian_chroot ]; then
  265. debian_chroot=$(cat /etc/debian_chroot)
  266. fi
  267. # enable bash completion in interactive shells
  268. if [ -f /etc/bash_completion ] && ! shopt -oq posix; then
  269. . /etc/bash_completion
  270. fi
  271. ''')
  272. if salt.utils.platform.is_windows():
  273. new_contents = expected.splitlines()
  274. expected = os.linesep.join(new_contents)
  275. expected += os.linesep
  276. testfile = os.path.join(TMP, 'issue-1879')
  277. # Delete if exiting
  278. if os.path.isfile(testfile):
  279. os.unlink(testfile)
  280. # Create the file
  281. ret = self.run_function('state.sls', mods='issue-1879', timeout=120)
  282. self.assertSaltTrueReturn(ret)
  283. # The first append
  284. ret = self.run_function(
  285. 'state.sls', mods='issue-1879.step-1', timeout=120
  286. )
  287. self.assertSaltTrueReturn(ret)
  288. # The second append
  289. ret = self.run_function(
  290. 'state.sls', mods='issue-1879.step-2', timeout=120
  291. )
  292. self.assertSaltTrueReturn(ret)
  293. # Does it match?
  294. try:
  295. with salt.utils.files.fopen(testfile, 'r') as fp_:
  296. contents = salt.utils.stringutils.to_unicode(fp_.read())
  297. self.assertMultiLineEqual(expected, contents)
  298. # Make sure we don't re-append existing text
  299. ret = self.run_function(
  300. 'state.sls', mods='issue-1879.step-1', timeout=120
  301. )
  302. self.assertSaltTrueReturn(ret)
  303. ret = self.run_function(
  304. 'state.sls', mods='issue-1879.step-2', timeout=120
  305. )
  306. self.assertSaltTrueReturn(ret)
  307. with salt.utils.files.fopen(testfile, 'r') as fp_:
  308. contents = salt.utils.stringutils.to_unicode(fp_.read())
  309. self.assertMultiLineEqual(expected, contents)
  310. except Exception:
  311. if os.path.exists(testfile):
  312. shutil.copy(testfile, testfile + '.bak')
  313. raise
  314. finally:
  315. if os.path.exists(testfile):
  316. os.unlink(testfile)
  317. def test_include(self):
  318. tempdir = tempfile.mkdtemp(dir=TMP)
  319. self.addCleanup(shutil.rmtree, tempdir, ignore_errors=True)
  320. pillar = {}
  321. for path in ('include-test', 'to-include-test', 'exclude-test'):
  322. pillar[path] = os.path.join(tempdir, path)
  323. ret = self.run_function('state.sls', mods='include-test', pillar=pillar)
  324. self.assertSaltTrueReturn(ret)
  325. self.assertTrue(os.path.isfile(pillar['include-test']))
  326. self.assertTrue(os.path.isfile(pillar['to-include-test']))
  327. self.assertFalse(os.path.isfile(pillar['exclude-test']))
  328. def test_exclude(self):
  329. tempdir = tempfile.mkdtemp(dir=TMP)
  330. self.addCleanup(shutil.rmtree, tempdir, ignore_errors=True)
  331. pillar = {}
  332. for path in ('include-test', 'exclude-test', 'to-include-test'):
  333. pillar[path] = os.path.join(tempdir, path)
  334. ret = self.run_function('state.sls', mods='exclude-test', pillar=pillar)
  335. self.assertSaltTrueReturn(ret)
  336. self.assertTrue(os.path.isfile(pillar['include-test']))
  337. self.assertTrue(os.path.isfile(pillar['exclude-test']))
  338. self.assertFalse(os.path.isfile(pillar['to-include-test']))
  339. @skipIf(salt.utils.path.which_bin(KNOWN_BINARY_NAMES) is None, 'virtualenv not installed')
  340. def test_issue_2068_template_str(self):
  341. venv_dir = os.path.join(
  342. TMP, 'issue-2068-template-str'
  343. )
  344. try:
  345. ret = self.run_function(
  346. 'state.sls', mods='issue-2068-template-str-no-dot',
  347. timeout=120
  348. )
  349. self.assertSaltTrueReturn(ret)
  350. finally:
  351. if os.path.isdir(venv_dir):
  352. shutil.rmtree(venv_dir)
  353. # Let's load the template from the filesystem. If running this state
  354. # with state.sls works, so should using state.template_str
  355. template_path = os.path.join(
  356. os.path.dirname(os.path.dirname(__file__)),
  357. 'files', 'file', 'base', 'issue-2068-template-str-no-dot.sls'
  358. )
  359. with salt.utils.files.fopen(template_path, 'r') as fp_:
  360. template = salt.utils.stringutils.to_unicode(fp_.read())
  361. ret = self.run_function(
  362. 'state.template_str', [template], timeout=120
  363. )
  364. self.assertSaltTrueReturn(ret)
  365. # Now using state.template
  366. ret = self.run_function(
  367. 'state.template', [template_path], timeout=120
  368. )
  369. self.assertSaltTrueReturn(ret)
  370. # Now the problematic #2068 including dot's
  371. ret = self.run_function(
  372. 'state.sls', mods='issue-2068-template-str', timeout=120
  373. )
  374. self.assertSaltTrueReturn(ret)
  375. # Let's load the template from the filesystem. If running this state
  376. # with state.sls works, so should using state.template_str
  377. template_path = os.path.join(
  378. os.path.dirname(os.path.dirname(__file__)),
  379. 'files', 'file', 'base', 'issue-2068-template-str.sls'
  380. )
  381. with salt.utils.files.fopen(template_path, 'r') as fp_:
  382. template = salt.utils.stringutils.to_unicode(fp_.read())
  383. ret = self.run_function(
  384. 'state.template_str', [template], timeout=120
  385. )
  386. self.assertSaltTrueReturn(ret)
  387. # Now using state.template
  388. ret = self.run_function(
  389. 'state.template', [template_path], timeout=120
  390. )
  391. self.assertSaltTrueReturn(ret)
  392. def test_template_invalid_items(self):
  393. TEMPLATE = textwrap.dedent('''\
  394. {0}:
  395. - issue-2068-template-str
  396. /tmp/test-template-invalid-items:
  397. file:
  398. - managed
  399. - source: salt://testfile
  400. ''')
  401. for item in ('include', 'exclude', 'extends'):
  402. ret = self.run_function(
  403. 'state.template_str', [TEMPLATE.format(item)]
  404. )
  405. self.assertTrue(isinstance(ret, list))
  406. self.assertNotEqual(ret, [])
  407. self.assertEqual(
  408. ['The \'{0}\' declaration found on \'<template-str>\' is '
  409. 'invalid when rendering single templates'.format(item)],
  410. ret
  411. )
  412. def test_pydsl(self):
  413. '''
  414. Test the basics of the pydsl
  415. '''
  416. ret = self.run_function('state.sls', mods='pydsl-1')
  417. self.assertSaltTrueReturn(ret)
  418. def test_issues_7905_and_8174_sls_syntax_error(self):
  419. '''
  420. Call sls file with yaml syntax error.
  421. Ensure theses errors are detected and presented to the user without
  422. stack traces.
  423. '''
  424. ret = self.run_function('state.sls', mods='syntax.badlist')
  425. self.assertEqual(ret, [
  426. 'State \'A\' in SLS \'syntax.badlist\' is not formed as a list'
  427. ])
  428. ret = self.run_function('state.sls', mods='syntax.badlist2')
  429. self.assertEqual(ret, [
  430. 'State \'C\' in SLS \'syntax.badlist2\' is not formed as a list'
  431. ])
  432. def test_requisites_mixed_require_prereq_use(self):
  433. '''
  434. Call sls file containing several requisites.
  435. '''
  436. expected_simple_result = {
  437. 'cmd_|-A_|-echo A_|-run': {
  438. '__run_num__': 2,
  439. 'comment': 'Command "echo A" run',
  440. 'result': True,
  441. 'changes': True},
  442. 'cmd_|-B_|-echo B_|-run': {
  443. '__run_num__': 1,
  444. 'comment': 'Command "echo B" run',
  445. 'result': True,
  446. 'changes': True},
  447. 'cmd_|-C_|-echo C_|-run': {
  448. '__run_num__': 0,
  449. 'comment': 'Command "echo C" run',
  450. 'result': True,
  451. 'changes': True}
  452. }
  453. expected_result = {
  454. 'cmd_|-A_|-echo A fifth_|-run': {
  455. '__run_num__': 4,
  456. 'comment': 'Command "echo A fifth" run',
  457. 'result': True,
  458. 'changes': True},
  459. 'cmd_|-B_|-echo B third_|-run': {
  460. '__run_num__': 2,
  461. 'comment': 'Command "echo B third" run',
  462. 'result': True,
  463. 'changes': True},
  464. 'cmd_|-C_|-echo C second_|-run': {
  465. '__run_num__': 1,
  466. 'comment': 'Command "echo C second" run',
  467. 'result': True,
  468. 'changes': True},
  469. 'cmd_|-D_|-echo D first_|-run': {
  470. '__run_num__': 0,
  471. 'comment': 'Command "echo D first" run',
  472. 'result': True,
  473. 'changes': True},
  474. 'cmd_|-E_|-echo E fourth_|-run': {
  475. '__run_num__': 3,
  476. 'comment': 'Command "echo E fourth" run',
  477. 'result': True,
  478. 'changes': True}
  479. }
  480. expected_req_use_result = {
  481. 'cmd_|-A_|-echo A_|-run': {
  482. '__run_num__': 1,
  483. 'comment': 'Command "echo A" run',
  484. 'result': True,
  485. 'changes': True},
  486. 'cmd_|-B_|-echo B_|-run': {
  487. '__run_num__': 4,
  488. 'comment': 'Command "echo B" run',
  489. 'result': True,
  490. 'changes': True},
  491. 'cmd_|-C_|-echo C_|-run': {
  492. '__run_num__': 0,
  493. 'comment': 'Command "echo C" run',
  494. 'result': True,
  495. 'changes': True},
  496. 'cmd_|-D_|-echo D_|-run': {
  497. '__run_num__': 5,
  498. 'comment': 'Command "echo D" run',
  499. 'result': True,
  500. 'changes': True},
  501. 'cmd_|-E_|-echo E_|-run': {
  502. '__run_num__': 2,
  503. 'comment': 'Command "echo E" run',
  504. 'result': True,
  505. 'changes': True},
  506. 'cmd_|-F_|-echo F_|-run': {
  507. '__run_num__': 3,
  508. 'comment': 'Command "echo F" run',
  509. 'result': True,
  510. 'changes': True}
  511. }
  512. ret = self.run_function('state.sls', mods='requisites.mixed_simple')
  513. result = self.normalize_ret(ret)
  514. self.assertReturnNonEmptySaltType(ret)
  515. self.assertEqual(expected_simple_result, result)
  516. # test Traceback recursion prereq+require #8785
  517. # TODO: this is actually failing badly
  518. #ret = self.run_function('state.sls', mods='requisites.prereq_require_recursion_error2')
  519. #self.assertEqual(
  520. # ret,
  521. # ['A recursive requisite was found, SLS "requisites.prereq_require_recursion_error2" ID "B" ID "A"']
  522. #)
  523. # test Infinite recursion prereq+require #8785 v2
  524. # TODO: this is actually failing badly
  525. #ret = self.run_function('state.sls', mods='requisites.prereq_require_recursion_error3')
  526. #self.assertEqual(
  527. # ret,
  528. # ['A recursive requisite was found, SLS "requisites.prereq_require_recursion_error2" ID "B" ID "A"']
  529. #)
  530. # test Infinite recursion prereq+require #8785 v3
  531. # TODO: this is actually failing badly, and expected result is maybe not a recursion
  532. #ret = self.run_function('state.sls', mods='requisites.prereq_require_recursion_error4')
  533. #self.assertEqual(
  534. # ret,
  535. # ['A recursive requisite was found, SLS "requisites.prereq_require_recursion_error2" ID "B" ID "A"']
  536. #)
  537. # undetected infinite loopS prevents this test from running...
  538. # TODO: this is actually failing badly
  539. #ret = self.run_function('state.sls', mods='requisites.mixed_complex1')
  540. #result = self.normalize_ret(ret)
  541. #self.assertEqual(expected_result, result)
  542. def test_watch_in(self):
  543. '''
  544. test watch_in requisite when there is a success
  545. '''
  546. ret = self.run_function('state.sls', mods='requisites.watch_in')
  547. changes = 'test_|-return_changes_|-return_changes_|-succeed_with_changes'
  548. watch = 'test_|-watch_states_|-watch_states_|-succeed_without_changes'
  549. self.assertEqual(ret[changes]['__run_num__'], 0)
  550. self.assertEqual(ret[watch]['__run_num__'], 2)
  551. self.assertEqual('Watch statement fired.', ret[watch]['comment'])
  552. self.assertEqual('Something pretended to change',
  553. ret[changes]['changes']['testing']['new'])
  554. def test_watch_in_failure(self):
  555. '''
  556. test watch_in requisite when there is a failure
  557. '''
  558. ret = self.run_function('state.sls', mods='requisites.watch_in_failure')
  559. fail = 'test_|-return_changes_|-return_changes_|-fail_with_changes'
  560. watch = 'test_|-watch_states_|-watch_states_|-succeed_without_changes'
  561. self.assertEqual(False, ret[fail]['result'])
  562. self.assertEqual('One or more requisite failed: requisites.watch_in_failure.return_changes',
  563. ret[watch]['comment'])
  564. def normalize_ret(self, ret):
  565. '''
  566. Normalize the return to the format that we'll use for result checking
  567. '''
  568. result = {}
  569. for item, descr in six.iteritems(ret):
  570. result[item] = {
  571. '__run_num__': descr['__run_num__'],
  572. 'comment': descr['comment'],
  573. 'result': descr['result'],
  574. 'changes': descr['changes'] != {} # whether there where any changes
  575. }
  576. return result
  577. def test_requisites_require_ordering_and_errors(self):
  578. '''
  579. Call sls file containing several require_in and require.
  580. Ensure that some of them are failing and that the order is right.
  581. '''
  582. expected_result = {
  583. 'cmd_|-A_|-echo A fifth_|-run': {
  584. '__run_num__': 4,
  585. 'comment': 'Command "echo A fifth" run',
  586. 'result': True,
  587. 'changes': True,
  588. },
  589. 'cmd_|-B_|-echo B second_|-run': {
  590. '__run_num__': 1,
  591. 'comment': 'Command "echo B second" run',
  592. 'result': True,
  593. 'changes': True,
  594. },
  595. 'cmd_|-C_|-echo C third_|-run': {
  596. '__run_num__': 2,
  597. 'comment': 'Command "echo C third" run',
  598. 'result': True,
  599. 'changes': True,
  600. },
  601. 'cmd_|-D_|-echo D first_|-run': {
  602. '__run_num__': 0,
  603. 'comment': 'Command "echo D first" run',
  604. 'result': True,
  605. 'changes': True,
  606. },
  607. 'cmd_|-E_|-echo E fourth_|-run': {
  608. '__run_num__': 3,
  609. 'comment': 'Command "echo E fourth" run',
  610. 'result': True,
  611. 'changes': True,
  612. },
  613. 'cmd_|-F_|-echo F_|-run': {
  614. '__run_num__': 5,
  615. 'comment': 'The following requisites were not found:\n'
  616. + ' require:\n'
  617. + ' foobar: A\n',
  618. 'result': False,
  619. 'changes': False,
  620. },
  621. 'cmd_|-G_|-echo G_|-run': {
  622. '__run_num__': 6,
  623. 'comment': 'The following requisites were not found:\n'
  624. + ' require:\n'
  625. + ' cmd: Z\n',
  626. 'result': False,
  627. 'changes': False,
  628. },
  629. 'cmd_|-H_|-echo H_|-run': {
  630. '__run_num__': 7,
  631. 'comment': 'The following requisites were not found:\n'
  632. + ' require:\n'
  633. + ' cmd: Z\n',
  634. 'result': False,
  635. 'changes': False,
  636. }
  637. }
  638. ret = self.run_function('state.sls', mods='requisites.require')
  639. result = self.normalize_ret(ret)
  640. self.assertReturnNonEmptySaltType(ret)
  641. self.assertEqual(expected_result, result)
  642. ret = self.run_function('state.sls', mods='requisites.require_error1')
  643. self.assertEqual(ret, [
  644. "Cannot extend ID 'W' in 'base:requisites.require_error1'. It is not part of the high state.\nThis is likely due to a missing include statement or an incorrectly typed ID.\nEnsure that a state with an ID of 'W' is available\nin environment 'base' and to SLS 'requisites.require_error1'"
  645. ])
  646. # issue #8235
  647. # FIXME: Why is require enforcing list syntax while require_in does not?
  648. # And why preventing it?
  649. # Currently this state fails, should return C/B/A
  650. result = {}
  651. ret = self.run_function('state.sls', mods='requisites.require_simple_nolist')
  652. self.assertEqual(ret, [
  653. 'The require statement in state \'B\' in SLS '
  654. + '\'requisites.require_simple_nolist\' needs to be formed as a list'
  655. ])
  656. # commented until a fix is made for issue #8772
  657. # TODO: this test actually fails
  658. #ret = self.run_function('state.sls', mods='requisites.require_error2')
  659. #self.assertEqual(ret, [
  660. # 'Cannot extend state foobar for ID A in "base:requisites.require_error2".'
  661. # + ' It is not part of the high state.'
  662. #])
  663. ret = self.run_function('state.sls', mods='requisites.require_recursion_error1')
  664. self.assertEqual(
  665. ret,
  666. ['A recursive requisite was found, SLS "requisites.require_recursion_error1" ID "B" ID "A"']
  667. )
  668. def test_requisites_require_any(self):
  669. '''
  670. Call sls file containing several require_in and require.
  671. Ensure that some of them are failing and that the order is right.
  672. '''
  673. expected_result = {
  674. 'cmd_|-A_|-echo A_|-run': {
  675. '__run_num__': 3,
  676. 'comment': 'Command "echo A" run',
  677. 'result': True,
  678. 'changes': True,
  679. },
  680. 'cmd_|-B_|-echo B_|-run': {
  681. '__run_num__': 0,
  682. 'comment': 'Command "echo B" run',
  683. 'result': True,
  684. 'changes': True,
  685. },
  686. 'cmd_|-C_|-$(which false)_|-run': {
  687. '__run_num__': 1,
  688. 'comment': 'Command "$(which false)" run',
  689. 'result': False,
  690. 'changes': True,
  691. },
  692. 'cmd_|-D_|-echo D_|-run': {
  693. '__run_num__': 2,
  694. 'comment': 'Command "echo D" run',
  695. 'result': True,
  696. 'changes': True,
  697. },
  698. }
  699. ret = self.run_function('state.sls', mods='requisites.require_any')
  700. result = self.normalize_ret(ret)
  701. self.assertReturnNonEmptySaltType(ret)
  702. self.assertEqual(expected_result, result)
  703. def test_requisites_require_any_fail(self):
  704. '''
  705. Call sls file containing several require_in and require.
  706. Ensure that some of them are failing and that the order is right.
  707. '''
  708. ret = self.run_function('state.sls', mods='requisites.require_any_fail')
  709. result = self.normalize_ret(ret)
  710. self.assertReturnNonEmptySaltType(ret)
  711. self.assertIn('One or more requisite failed',
  712. result['cmd_|-D_|-echo D_|-run']['comment'])
  713. def test_requisites_watch_any(self):
  714. '''
  715. Call sls file containing several require_in and require.
  716. Ensure that some of them are failing and that the order is right.
  717. '''
  718. if salt.utils.platform.is_windows():
  719. cmd_true = 'exit'
  720. cmd_false = 'exit /B 1'
  721. else:
  722. cmd_true = 'true'
  723. cmd_false = 'false'
  724. expected_result = {
  725. 'cmd_|-A_|-{0}_|-wait'.format(cmd_true): {
  726. '__run_num__': 4,
  727. 'comment': 'Command "{0}" run'.format(cmd_true),
  728. 'result': True,
  729. 'changes': True,
  730. },
  731. 'cmd_|-B_|-{0}_|-run'.format(cmd_true): {
  732. '__run_num__': 0,
  733. 'comment': 'Command "{0}" run'.format(cmd_true),
  734. 'result': True,
  735. 'changes': True,
  736. },
  737. 'cmd_|-C_|-{0}_|-run'.format(cmd_false): {
  738. '__run_num__': 1,
  739. 'comment': 'Command "{0}" run'.format(cmd_false),
  740. 'result': False,
  741. 'changes': True,
  742. },
  743. 'cmd_|-D_|-{0}_|-run'.format(cmd_true): {
  744. '__run_num__': 2,
  745. 'comment': 'Command "{0}" run'.format(cmd_true),
  746. 'result': True,
  747. 'changes': True,
  748. },
  749. 'cmd_|-E_|-{0}_|-wait'.format(cmd_true): {
  750. '__run_num__': 9,
  751. 'comment': 'Command "{0}" run'.format(cmd_true),
  752. 'result': True,
  753. 'changes': True,
  754. },
  755. 'cmd_|-F_|-{0}_|-run'.format(cmd_true): {
  756. '__run_num__': 5,
  757. 'comment': 'Command "{0}" run'.format(cmd_true),
  758. 'result': True,
  759. 'changes': True,
  760. },
  761. 'cmd_|-G_|-{0}_|-run'.format(cmd_false): {
  762. '__run_num__': 6,
  763. 'comment': 'Command "{0}" run'.format(cmd_false),
  764. 'result': False,
  765. 'changes': True,
  766. },
  767. 'cmd_|-H_|-{0}_|-run'.format(cmd_false): {
  768. '__run_num__': 7,
  769. 'comment': 'Command "{0}" run'.format(cmd_false),
  770. 'result': False,
  771. 'changes': True,
  772. },
  773. }
  774. ret = self.run_function('state.sls', mods='requisites.watch_any')
  775. result = self.normalize_ret(ret)
  776. self.assertReturnNonEmptySaltType(ret)
  777. self.assertEqual(expected_result, result)
  778. def test_requisites_watch_any_fail(self):
  779. '''
  780. Call sls file containing several require_in and require.
  781. Ensure that some of them are failing and that the order is right.
  782. '''
  783. ret = self.run_function('state.sls', mods='requisites.watch_any_fail')
  784. result = self.normalize_ret(ret)
  785. self.assertReturnNonEmptySaltType(ret)
  786. self.assertIn('One or more requisite failed',
  787. result['cmd_|-A_|-true_|-wait']['comment'])
  788. def test_requisites_onchanges_any(self):
  789. '''
  790. Call sls file containing several require_in and require.
  791. Ensure that some of them are failing and that the order is right.
  792. '''
  793. expected_result = {
  794. 'cmd_|-another_changing_state_|-echo "Changed!"_|-run': {
  795. '__run_num__': 1,
  796. 'changes': True,
  797. 'comment': 'Command "echo "Changed!"" run',
  798. 'result': True
  799. },
  800. 'cmd_|-changing_state_|-echo "Changed!"_|-run': {
  801. '__run_num__': 0,
  802. 'changes': True,
  803. 'comment': 'Command "echo "Changed!"" run',
  804. 'result': True
  805. },
  806. 'cmd_|-test_one_changing_states_|-echo "Success!"_|-run': {
  807. '__run_num__': 4,
  808. 'changes': True,
  809. 'comment': 'Command "echo "Success!"" run',
  810. 'result': True
  811. },
  812. 'cmd_|-test_two_non_changing_states_|-echo "Should not run"_|-run': {
  813. '__run_num__': 5,
  814. 'changes': False,
  815. 'comment': 'State was not run because none of the onchanges reqs changed',
  816. 'result': True
  817. },
  818. 'pip_|-another_non_changing_state_|-mock_|-installed': {
  819. '__run_num__': 3,
  820. 'changes': False,
  821. 'comment': 'Python package mock was already installed\nAll specified packages are already installed',
  822. 'result': True
  823. },
  824. 'pip_|-non_changing_state_|-mock_|-installed': {
  825. '__run_num__': 2,
  826. 'changes': False,
  827. 'comment': 'Python package mock was already installed\nAll specified packages are already installed',
  828. 'result': True
  829. }
  830. }
  831. ret = self.run_function('state.sls', mods='requisites.onchanges_any')
  832. result = self.normalize_ret(ret)
  833. self.assertReturnNonEmptySaltType(ret)
  834. self.assertEqual(expected_result, result)
  835. def test_requisites_onfail_any(self):
  836. '''
  837. Call sls file containing several require_in and require.
  838. Ensure that some of them are failing and that the order is right.
  839. '''
  840. expected_result = {
  841. 'cmd_|-a_|-exit 0_|-run': {
  842. '__run_num__': 0,
  843. 'changes': True,
  844. 'comment': 'Command "exit 0" run',
  845. 'result': True
  846. },
  847. 'cmd_|-b_|-exit 1_|-run': {
  848. '__run_num__': 1,
  849. 'changes': True,
  850. 'comment': 'Command "exit 1" run',
  851. 'result': False
  852. },
  853. 'cmd_|-c_|-exit 0_|-run': {
  854. '__run_num__': 2,
  855. 'changes': True,
  856. 'comment': 'Command "exit 0" run',
  857. 'result': True
  858. },
  859. 'cmd_|-d_|-echo itworked_|-run': {
  860. '__run_num__': 3,
  861. 'changes': True,
  862. 'comment': 'Command "echo itworked" run',
  863. 'result': True},
  864. 'cmd_|-e_|-exit 0_|-run': {
  865. '__run_num__': 4,
  866. 'changes': True,
  867. 'comment': 'Command "exit 0" run',
  868. 'result': True
  869. },
  870. 'cmd_|-f_|-exit 0_|-run': {
  871. '__run_num__': 5,
  872. 'changes': True,
  873. 'comment': 'Command "exit 0" run',
  874. 'result': True
  875. },
  876. 'cmd_|-g_|-exit 0_|-run': {
  877. '__run_num__': 6,
  878. 'changes': True,
  879. 'comment': 'Command "exit 0" run',
  880. 'result': True
  881. },
  882. 'cmd_|-h_|-echo itworked_|-run': {
  883. '__run_num__': 7,
  884. 'changes': False,
  885. 'comment': 'State was not run because onfail req did not change',
  886. 'result': True
  887. }
  888. }
  889. ret = self.run_function('state.sls', mods='requisites.onfail_any')
  890. result = self.normalize_ret(ret)
  891. self.assertReturnNonEmptySaltType(ret)
  892. self.assertEqual(expected_result, result)
  893. def test_requisites_full_sls(self):
  894. '''
  895. Teste the sls special command in requisites
  896. '''
  897. expected_result = {
  898. 'cmd_|-A_|-echo A_|-run': {
  899. '__run_num__': 2,
  900. 'comment': 'Command "echo A" run',
  901. 'result': True,
  902. 'changes': True},
  903. 'cmd_|-B_|-echo B_|-run': {
  904. '__run_num__': 0,
  905. 'comment': 'Command "echo B" run',
  906. 'result': True,
  907. 'changes': True},
  908. 'cmd_|-C_|-echo C_|-run': {
  909. '__run_num__': 1,
  910. 'comment': 'Command "echo C" run',
  911. 'result': True,
  912. 'changes': True},
  913. }
  914. ret = self.run_function('state.sls', mods='requisites.fullsls_require')
  915. self.assertReturnNonEmptySaltType(ret)
  916. result = self.normalize_ret(ret)
  917. self.assertEqual(expected_result, result)
  918. # issue #8233: traceback on prereq sls
  919. # TODO: not done
  920. #ret = self.run_function('state.sls', mods='requisites.fullsls_prereq')
  921. #self.assertEqual(['sls command can only be used with require requisite'], ret)
  922. def test_requisites_require_no_state_module(self):
  923. '''
  924. Call sls file containing several require_in and require.
  925. Ensure that some of them are failing and that the order is right.
  926. '''
  927. expected_result = {
  928. 'cmd_|-A_|-echo A fifth_|-run': {
  929. '__run_num__': 4,
  930. 'comment': 'Command "echo A fifth" run',
  931. 'result': True,
  932. 'changes': True,
  933. },
  934. 'cmd_|-B_|-echo B second_|-run': {
  935. '__run_num__': 1,
  936. 'comment': 'Command "echo B second" run',
  937. 'result': True,
  938. 'changes': True,
  939. },
  940. 'cmd_|-C_|-echo C third_|-run': {
  941. '__run_num__': 2,
  942. 'comment': 'Command "echo C third" run',
  943. 'result': True,
  944. 'changes': True,
  945. },
  946. 'cmd_|-D_|-echo D first_|-run': {
  947. '__run_num__': 0,
  948. 'comment': 'Command "echo D first" run',
  949. 'result': True,
  950. 'changes': True,
  951. },
  952. 'cmd_|-E_|-echo E fourth_|-run': {
  953. '__run_num__': 3,
  954. 'comment': 'Command "echo E fourth" run',
  955. 'result': True,
  956. 'changes': True,
  957. },
  958. 'cmd_|-G_|-echo G_|-run': {
  959. '__run_num__': 5,
  960. 'comment': 'The following requisites were not found:\n'
  961. + ' require:\n'
  962. + ' id: Z\n',
  963. 'result': False,
  964. 'changes': False,
  965. },
  966. 'cmd_|-H_|-echo H_|-run': {
  967. '__run_num__': 6,
  968. 'comment': 'The following requisites were not found:\n'
  969. + ' require:\n'
  970. + ' id: Z\n',
  971. 'result': False,
  972. 'changes': False,
  973. }
  974. }
  975. ret = self.run_function('state.sls', mods='requisites.require_no_state_module')
  976. result = self.normalize_ret(ret)
  977. self.assertReturnNonEmptySaltType(ret)
  978. self.assertEqual(expected_result, result)
  979. def test_requisites_prereq_simple_ordering_and_errors(self):
  980. '''
  981. Call sls file containing several prereq_in and prereq.
  982. Ensure that some of them are failing and that the order is right.
  983. '''
  984. expected_result_simple = {
  985. 'cmd_|-A_|-echo A third_|-run': {
  986. '__run_num__': 2,
  987. 'comment': 'Command "echo A third" run',
  988. 'result': True,
  989. 'changes': True},
  990. 'cmd_|-B_|-echo B first_|-run': {
  991. '__run_num__': 0,
  992. 'comment': 'Command "echo B first" run',
  993. 'result': True,
  994. 'changes': True},
  995. 'cmd_|-C_|-echo C second_|-run': {
  996. '__run_num__': 1,
  997. 'comment': 'Command "echo C second" run',
  998. 'result': True,
  999. 'changes': True},
  1000. 'cmd_|-I_|-echo I_|-run': {
  1001. '__run_num__': 3,
  1002. 'comment': 'The following requisites were not found:\n'
  1003. + ' prereq:\n'
  1004. + ' cmd: Z\n',
  1005. 'result': False,
  1006. 'changes': False},
  1007. 'cmd_|-J_|-echo J_|-run': {
  1008. '__run_num__': 4,
  1009. 'comment': 'The following requisites were not found:\n'
  1010. + ' prereq:\n'
  1011. + ' foobar: A\n',
  1012. 'result': False,
  1013. 'changes': False}
  1014. }
  1015. expected_result_simple_no_state_module = {
  1016. 'cmd_|-A_|-echo A third_|-run': {
  1017. '__run_num__': 2,
  1018. 'comment': 'Command "echo A third" run',
  1019. 'result': True,
  1020. 'changes': True},
  1021. 'cmd_|-B_|-echo B first_|-run': {
  1022. '__run_num__': 0,
  1023. 'comment': 'Command "echo B first" run',
  1024. 'result': True,
  1025. 'changes': True},
  1026. 'cmd_|-C_|-echo C second_|-run': {
  1027. '__run_num__': 1,
  1028. 'comment': 'Command "echo C second" run',
  1029. 'result': True,
  1030. 'changes': True},
  1031. 'cmd_|-I_|-echo I_|-run': {
  1032. '__run_num__': 3,
  1033. 'comment': 'The following requisites were not found:\n'
  1034. + ' prereq:\n'
  1035. + ' id: Z\n',
  1036. 'result': False,
  1037. 'changes': False}
  1038. }
  1039. expected_result_simple2 = {
  1040. 'cmd_|-A_|-echo A_|-run': {
  1041. '__run_num__': 1,
  1042. 'comment': 'Command "echo A" run',
  1043. 'result': True,
  1044. 'changes': True},
  1045. 'cmd_|-B_|-echo B_|-run': {
  1046. '__run_num__': 2,
  1047. 'comment': 'Command "echo B" run',
  1048. 'result': True,
  1049. 'changes': True},
  1050. 'cmd_|-C_|-echo C_|-run': {
  1051. '__run_num__': 0,
  1052. 'comment': 'Command "echo C" run',
  1053. 'result': True,
  1054. 'changes': True},
  1055. 'cmd_|-D_|-echo D_|-run': {
  1056. '__run_num__': 3,
  1057. 'comment': 'Command "echo D" run',
  1058. 'result': True,
  1059. 'changes': True},
  1060. 'cmd_|-E_|-echo E_|-run': {
  1061. '__run_num__': 4,
  1062. 'comment': 'Command "echo E" run',
  1063. 'result': True,
  1064. 'changes': True}
  1065. }
  1066. expected_result_simple3 = {
  1067. 'cmd_|-A_|-echo A first_|-run': {
  1068. '__run_num__': 0,
  1069. 'comment': 'Command "echo A first" run',
  1070. 'result': True,
  1071. 'changes': True,
  1072. },
  1073. 'cmd_|-B_|-echo B second_|-run': {
  1074. '__run_num__': 1,
  1075. 'comment': 'Command "echo B second" run',
  1076. 'result': True,
  1077. 'changes': True,
  1078. },
  1079. 'cmd_|-C_|-echo C third_|-wait': {
  1080. '__run_num__': 2,
  1081. 'comment': '',
  1082. 'result': True,
  1083. 'changes': False,
  1084. }
  1085. }
  1086. expected_result_complex = {
  1087. 'cmd_|-A_|-echo A fourth_|-run': {
  1088. '__run_num__': 3,
  1089. 'comment': 'Command "echo A fourth" run',
  1090. 'result': True,
  1091. 'changes': True},
  1092. 'cmd_|-B_|-echo B first_|-run': {
  1093. '__run_num__': 0,
  1094. 'comment': 'Command "echo B first" run',
  1095. 'result': True,
  1096. 'changes': True},
  1097. 'cmd_|-C_|-echo C second_|-run': {
  1098. '__run_num__': 1,
  1099. 'comment': 'Command "echo C second" run',
  1100. 'result': True,
  1101. 'changes': True},
  1102. 'cmd_|-D_|-echo D third_|-run': {
  1103. '__run_num__': 2,
  1104. 'comment': 'Command "echo D third" run',
  1105. 'result': True,
  1106. 'changes': True},
  1107. }
  1108. ret = self.run_function('state.sls', mods='requisites.prereq_simple')
  1109. self.assertReturnNonEmptySaltType(ret)
  1110. result = self.normalize_ret(ret)
  1111. self.assertEqual(expected_result_simple, result)
  1112. # same test, but not using lists in yaml syntax
  1113. # TODO: issue #8235, prereq ignored when not used in list syntax
  1114. # Currently fails badly with :
  1115. # TypeError encountered executing state.sls: string indices must be integers, not str.
  1116. #expected_result_simple.pop('cmd_|-I_|-echo I_|-run')
  1117. #expected_result_simple.pop('cmd_|-J_|-echo J_|-run')
  1118. #ret = self.run_function('state.sls', mods='requisites.prereq_simple_nolist')
  1119. #result = self.normalize_ret(ret)
  1120. #self.assertEqual(expected_result_simple, result)
  1121. ret = self.run_function('state.sls', mods='requisites.prereq_simple2')
  1122. result = self.normalize_ret(ret)
  1123. self.assertReturnNonEmptySaltType(ret)
  1124. self.assertEqual(expected_result_simple2, result)
  1125. ret = self.run_function('state.sls', mods='requisites.prereq_simple3')
  1126. result = self.normalize_ret(ret)
  1127. self.assertReturnNonEmptySaltType(ret)
  1128. self.assertEqual(expected_result_simple3, result)
  1129. #ret = self.run_function('state.sls', mods='requisites.prereq_error_nolist')
  1130. #self.assertEqual(
  1131. # ret,
  1132. # ['Cannot extend ID Z in "base:requisites.prereq_error_nolist".'
  1133. # + ' It is not part of the high state.']
  1134. #)
  1135. ret = self.run_function('state.sls', mods='requisites.prereq_compile_error1')
  1136. self.assertReturnNonEmptySaltType(ret)
  1137. self.assertEqual(
  1138. ret['cmd_|-B_|-echo B_|-run']['comment'],
  1139. 'The following requisites were not found:\n'
  1140. + ' prereq:\n'
  1141. + ' foobar: A\n'
  1142. )
  1143. ret = self.run_function('state.sls', mods='requisites.prereq_compile_error2')
  1144. self.assertReturnNonEmptySaltType(ret)
  1145. self.assertEqual(
  1146. ret['cmd_|-B_|-echo B_|-run']['comment'],
  1147. 'The following requisites were not found:\n'
  1148. + ' prereq:\n'
  1149. + ' foobar: C\n'
  1150. )
  1151. ret = self.run_function('state.sls', mods='requisites.prereq_complex')
  1152. result = self.normalize_ret(ret)
  1153. self.assertEqual(expected_result_complex, result)
  1154. # issue #8210 : prereq recursion undetected
  1155. # TODO: this test fails
  1156. #ret = self.run_function('state.sls', mods='requisites.prereq_recursion_error')
  1157. #self.assertEqual(
  1158. # ret,
  1159. # ['A recursive requisite was found, SLS "requisites.prereq_recursion_error" ID "B" ID "A"']
  1160. #)
  1161. ret = self.run_function('state.sls', mods='requisites.prereq_simple_no_state_module')
  1162. result = self.normalize_ret(ret)
  1163. self.assertEqual(expected_result_simple_no_state_module, result)
  1164. def test_infinite_recursion_sls_prereq(self):
  1165. ret = self.run_function('state.sls', mods='requisites.prereq_sls_infinite_recursion')
  1166. self.assertSaltTrueReturn(ret)
  1167. def test_requisites_use(self):
  1168. '''
  1169. Call sls file containing several use_in and use.
  1170. '''
  1171. # TODO issue #8235 & #8774 some examples are still commented in the test file
  1172. ret = self.run_function('state.sls', mods='requisites.use')
  1173. self.assertReturnNonEmptySaltType(ret)
  1174. for item, descr in six.iteritems(ret):
  1175. self.assertEqual(descr['comment'], 'onlyif condition is false')
  1176. # TODO: issue #8802 : use recursions undetected
  1177. # issue is closed as use does not actually inherit requisites
  1178. # if chain-use is added after #8774 resolution theses tests would maybe become useful
  1179. #ret = self.run_function('state.sls', mods='requisites.use_recursion')
  1180. #self.assertEqual(ret, [
  1181. # 'A recursive requisite was found, SLS "requisites.use_recursion"'
  1182. # + ' ID "B" ID "A"'
  1183. #])
  1184. #ret = self.run_function('state.sls', mods='requisites.use_recursion2')
  1185. #self.assertEqual(ret, [
  1186. # 'A recursive requisite was found, SLS "requisites.use_recursion2"'
  1187. # + ' ID "C" ID "A"'
  1188. #])
  1189. #ret = self.run_function('state.sls', mods='requisites.use_auto_recursion')
  1190. #self.assertEqual(ret, [
  1191. # 'A recursive requisite was found, SLS "requisites.use_recursion"'
  1192. # + ' ID "A" ID "A"'
  1193. #])
  1194. def test_requisites_use_no_state_module(self):
  1195. '''
  1196. Call sls file containing several use_in and use.
  1197. '''
  1198. ret = self.run_function('state.sls', mods='requisites.use_no_state_module')
  1199. self.assertReturnNonEmptySaltType(ret)
  1200. for item, descr in six.iteritems(ret):
  1201. self.assertEqual(descr['comment'], 'onlyif condition is false')
  1202. def test_get_file_from_env_in_top_match(self):
  1203. tgt = os.path.join(TMP, 'prod-cheese-file')
  1204. try:
  1205. ret = self.run_function(
  1206. 'state.highstate', minion_tgt='sub_minion'
  1207. )
  1208. self.assertSaltTrueReturn(ret)
  1209. self.assertTrue(os.path.isfile(tgt))
  1210. with salt.utils.files.fopen(tgt, 'r') as cheese:
  1211. data = salt.utils.stringutils.to_unicode(cheese.read())
  1212. self.assertIn('Gromit', data)
  1213. self.assertIn('Comte', data)
  1214. finally:
  1215. if os.path.islink(tgt):
  1216. os.unlink(tgt)
  1217. # onchanges tests
  1218. def test_onchanges_requisite(self):
  1219. '''
  1220. Tests a simple state using the onchanges requisite
  1221. '''
  1222. # Only run the state once and keep the return data
  1223. state_run = self.run_function('state.sls', mods='requisites.onchanges_simple')
  1224. # First, test the result of the state run when changes are expected to happen
  1225. test_data = state_run['cmd_|-test_changing_state_|-echo "Success!"_|-run']['comment']
  1226. expected_result = 'Command "echo "Success!"" run'
  1227. self.assertIn(expected_result, test_data)
  1228. # Then, test the result of the state run when changes are not expected to happen
  1229. test_data = state_run['cmd_|-test_non_changing_state_|-echo "Should not run"_|-run']['comment']
  1230. expected_result = 'State was not run because none of the onchanges reqs changed'
  1231. self.assertIn(expected_result, test_data)
  1232. def test_onchanges_requisite_multiple(self):
  1233. '''
  1234. Tests a simple state using the onchanges requisite
  1235. '''
  1236. # Only run the state once and keep the return data
  1237. state_run = self.run_function('state.sls',
  1238. mods='requisites.onchanges_multiple')
  1239. # First, test the result of the state run when two changes are expected to happen
  1240. test_data = state_run['cmd_|-test_two_changing_states_|-echo "Success!"_|-run']['comment']
  1241. expected_result = 'Command "echo "Success!"" run'
  1242. self.assertIn(expected_result, test_data)
  1243. # Then, test the result of the state run when two changes are not expected to happen
  1244. test_data = state_run['cmd_|-test_two_non_changing_states_|-echo "Should not run"_|-run']['comment']
  1245. expected_result = 'State was not run because none of the onchanges reqs changed'
  1246. self.assertIn(expected_result, test_data)
  1247. # Finally, test the result of the state run when only one of the onchanges requisites changes.
  1248. test_data = state_run['cmd_|-test_one_changing_state_|-echo "Success!"_|-run']['comment']
  1249. expected_result = 'Command "echo "Success!"" run'
  1250. self.assertIn(expected_result, test_data)
  1251. def test_onchanges_in_requisite(self):
  1252. '''
  1253. Tests a simple state using the onchanges_in requisite
  1254. '''
  1255. # Only run the state once and keep the return data
  1256. state_run = self.run_function('state.sls', mods='requisites.onchanges_in_simple')
  1257. # First, test the result of the state run of when changes are expected to happen
  1258. test_data = state_run['cmd_|-test_changes_expected_|-echo "Success!"_|-run']['comment']
  1259. expected_result = 'Command "echo "Success!"" run'
  1260. self.assertIn(expected_result, test_data)
  1261. # Then, test the result of the state run when changes are not expected to happen
  1262. test_data = state_run['cmd_|-test_changes_not_expected_|-echo "Should not run"_|-run']['comment']
  1263. expected_result = 'State was not run because none of the onchanges reqs changed'
  1264. self.assertIn(expected_result, test_data)
  1265. def test_onchanges_requisite_no_state_module(self):
  1266. '''
  1267. Tests a simple state using the onchanges requisite without state modules
  1268. '''
  1269. # Only run the state once and keep the return data
  1270. state_run = self.run_function('state.sls', mods='requisites.onchanges_simple_no_state_module')
  1271. test_data = state_run['cmd_|-test_changing_state_|-echo "Success!"_|-run']['comment']
  1272. expected_result = 'Command "echo "Success!"" run'
  1273. self.assertIn(expected_result, test_data)
  1274. def test_onchanges_requisite_with_duration(self):
  1275. '''
  1276. Tests a simple state using the onchanges requisite
  1277. the state will not run but results will include duration
  1278. '''
  1279. # Only run the state once and keep the return data
  1280. state_run = self.run_function('state.sls', mods='requisites.onchanges_simple')
  1281. # Then, test the result of the state run when changes are not expected to happen
  1282. # and ensure duration is included in the results
  1283. test_data = state_run['cmd_|-test_non_changing_state_|-echo "Should not run"_|-run']
  1284. self.assertIn('duration', test_data)
  1285. # onfail tests
  1286. def test_onfail_requisite(self):
  1287. '''
  1288. Tests a simple state using the onfail requisite
  1289. '''
  1290. # Only run the state once and keep the return data
  1291. state_run = self.run_function('state.sls', mods='requisites.onfail_simple')
  1292. # First, test the result of the state run when a failure is expected to happen
  1293. test_data = state_run['cmd_|-test_failing_state_|-echo "Success!"_|-run']['comment']
  1294. expected_result = 'Command "echo "Success!"" run'
  1295. self.assertIn(expected_result, test_data)
  1296. # Then, test the result of the state run when a failure is not expected to happen
  1297. test_data = state_run['cmd_|-test_non_failing_state_|-echo "Should not run"_|-run']['comment']
  1298. expected_result = 'State was not run because onfail req did not change'
  1299. self.assertIn(expected_result, test_data)
  1300. def test_multiple_onfail_requisite(self):
  1301. '''
  1302. test to ensure state is run even if only one
  1303. of the onfails fails. This is a test for the issue:
  1304. https://github.com/saltstack/salt/issues/22370
  1305. '''
  1306. state_run = self.run_function('state.sls', mods='requisites.onfail_multiple')
  1307. retcode = state_run['cmd_|-c_|-echo itworked_|-run']['changes']['retcode']
  1308. self.assertEqual(retcode, 0)
  1309. stdout = state_run['cmd_|-c_|-echo itworked_|-run']['changes']['stdout']
  1310. self.assertEqual(stdout, 'itworked')
  1311. def test_onfail_in_requisite(self):
  1312. '''
  1313. Tests a simple state using the onfail_in requisite
  1314. '''
  1315. # Only run the state once and keep the return data
  1316. state_run = self.run_function('state.sls', mods='requisites.onfail_in_simple')
  1317. # First, test the result of the state run when a failure is expected to happen
  1318. test_data = state_run['cmd_|-test_failing_state_|-echo "Success!"_|-run']['comment']
  1319. expected_result = 'Command "echo "Success!"" run'
  1320. self.assertIn(expected_result, test_data)
  1321. # Then, test the result of the state run when a failure is not expected to happen
  1322. test_data = state_run['cmd_|-test_non_failing_state_|-echo "Should not run"_|-run']['comment']
  1323. expected_result = 'State was not run because onfail req did not change'
  1324. self.assertIn(expected_result, test_data)
  1325. def test_onfail_requisite_no_state_module(self):
  1326. '''
  1327. Tests a simple state using the onfail requisite
  1328. '''
  1329. # Only run the state once and keep the return data
  1330. state_run = self.run_function('state.sls', mods='requisites.onfail_simple_no_state_module')
  1331. # First, test the result of the state run when a failure is expected to happen
  1332. test_data = state_run['cmd_|-test_failing_state_|-echo "Success!"_|-run']['comment']
  1333. expected_result = 'Command "echo "Success!"" run'
  1334. self.assertIn(expected_result, test_data)
  1335. # Then, test the result of the state run when a failure is not expected to happen
  1336. test_data = state_run['cmd_|-test_non_failing_state_|-echo "Should not run"_|-run']['comment']
  1337. expected_result = 'State was not run because onfail req did not change'
  1338. self.assertIn(expected_result, test_data)
  1339. def test_onfail_requisite_with_duration(self):
  1340. '''
  1341. Tests a simple state using the onfail requisite
  1342. '''
  1343. # Only run the state once and keep the return data
  1344. state_run = self.run_function('state.sls', mods='requisites.onfail_simple')
  1345. # Then, test the result of the state run when a failure is not expected to happen
  1346. test_data = state_run['cmd_|-test_non_failing_state_|-echo "Should not run"_|-run']
  1347. self.assertIn('duration', test_data)
  1348. def test_multiple_onfail_requisite_with_required(self):
  1349. '''
  1350. test to ensure multiple states are run
  1351. when specified as onfails for a single state.
  1352. This is a test for the issue:
  1353. https://github.com/saltstack/salt/issues/46552
  1354. '''
  1355. state_run = self.run_function('state.sls', mods='requisites.onfail_multiple_required')
  1356. retcode = state_run['cmd_|-b_|-echo b_|-run']['changes']['retcode']
  1357. self.assertEqual(retcode, 0)
  1358. retcode = state_run['cmd_|-c_|-echo c_|-run']['changes']['retcode']
  1359. self.assertEqual(retcode, 0)
  1360. retcode = state_run['cmd_|-d_|-echo d_|-run']['changes']['retcode']
  1361. self.assertEqual(retcode, 0)
  1362. stdout = state_run['cmd_|-b_|-echo b_|-run']['changes']['stdout']
  1363. self.assertEqual(stdout, 'b')
  1364. stdout = state_run['cmd_|-c_|-echo c_|-run']['changes']['stdout']
  1365. self.assertEqual(stdout, 'c')
  1366. stdout = state_run['cmd_|-d_|-echo d_|-run']['changes']['stdout']
  1367. self.assertEqual(stdout, 'd')
  1368. def test_multiple_onfail_requisite_with_required_no_run(self):
  1369. '''
  1370. test to ensure multiple states are not run
  1371. when specified as onfails for a single state
  1372. which fails.
  1373. This is a test for the issue:
  1374. https://github.com/saltstack/salt/issues/46552
  1375. '''
  1376. state_run = self.run_function('state.sls', mods='requisites.onfail_multiple_required_no_run')
  1377. expected = 'State was not run because onfail req did not change'
  1378. stdout = state_run['cmd_|-b_|-echo b_|-run']['comment']
  1379. self.assertEqual(stdout, expected)
  1380. stdout = state_run['cmd_|-c_|-echo c_|-run']['comment']
  1381. self.assertEqual(stdout, expected)
  1382. stdout = state_run['cmd_|-d_|-echo d_|-run']['comment']
  1383. self.assertEqual(stdout, expected)
  1384. # listen tests
  1385. def test_listen_requisite(self):
  1386. '''
  1387. Tests a simple state using the listen requisite
  1388. '''
  1389. # Only run the state once and keep the return data
  1390. state_run = self.run_function('state.sls', mods='requisites.listen_simple')
  1391. # First, test the result of the state run when a listener is expected to trigger
  1392. listener_state = 'cmd_|-listener_test_listening_change_state_|-echo "Listening State"_|-mod_watch'
  1393. self.assertIn(listener_state, state_run)
  1394. # Then, test the result of the state run when a listener should not trigger
  1395. absent_state = 'cmd_|-listener_test_listening_non_changing_state_|-echo "Only run once"_|-mod_watch'
  1396. self.assertNotIn(absent_state, state_run)
  1397. def test_listen_in_requisite(self):
  1398. '''
  1399. Tests a simple state using the listen_in requisite
  1400. '''
  1401. # Only run the state once and keep the return data
  1402. state_run = self.run_function('state.sls', mods='requisites.listen_in_simple')
  1403. # First, test the result of the state run when a listener is expected to trigger
  1404. listener_state = 'cmd_|-listener_test_listening_change_state_|-echo "Listening State"_|-mod_watch'
  1405. self.assertIn(listener_state, state_run)
  1406. # Then, test the result of the state run when a listener should not trigger
  1407. absent_state = 'cmd_|-listener_test_listening_non_changing_state_|-echo "Only run once"_|-mod_watch'
  1408. self.assertNotIn(absent_state, state_run)
  1409. def test_listen_in_requisite_resolution(self):
  1410. '''
  1411. Verify listen_in requisite lookups use ID declaration to check for changes
  1412. '''
  1413. # Only run the state once and keep the return data
  1414. state_run = self.run_function('state.sls', mods='requisites.listen_in_simple')
  1415. # Test the result of the state run when a listener is expected to trigger
  1416. listener_state = 'cmd_|-listener_test_listen_in_resolution_|-echo "Successful listen_in resolution"_|-mod_watch'
  1417. self.assertIn(listener_state, state_run)
  1418. def test_listen_requisite_resolution(self):
  1419. '''
  1420. Verify listen requisite lookups use ID declaration to check for changes
  1421. '''
  1422. # Only run the state once and keep the return data
  1423. state_run = self.run_function('state.sls', mods='requisites.listen_simple')
  1424. # Both listeners are expected to trigger
  1425. listener_state = 'cmd_|-listener_test_listening_resolution_one_|-echo "Successful listen resolution"_|-mod_watch'
  1426. self.assertIn(listener_state, state_run)
  1427. listener_state = 'cmd_|-listener_test_listening_resolution_two_|-echo "Successful listen resolution"_|-mod_watch'
  1428. self.assertIn(listener_state, state_run)
  1429. def test_listen_requisite_no_state_module(self):
  1430. '''
  1431. Tests a simple state using the listen requisite
  1432. '''
  1433. # Only run the state once and keep the return data
  1434. state_run = self.run_function('state.sls', mods='requisites.listen_simple_no_state_module')
  1435. # First, test the result of the state run when a listener is expected to trigger
  1436. listener_state = 'cmd_|-listener_test_listening_change_state_|-echo "Listening State"_|-mod_watch'
  1437. self.assertIn(listener_state, state_run)
  1438. # Then, test the result of the state run when a listener should not trigger
  1439. absent_state = 'cmd_|-listener_test_listening_non_changing_state_|-echo "Only run once"_|-mod_watch'
  1440. self.assertNotIn(absent_state, state_run)
  1441. def test_listen_in_requisite_resolution_names(self):
  1442. '''
  1443. Verify listen_in requisite lookups use ID declaration to check for changes
  1444. and resolves magic names state variable
  1445. '''
  1446. # Only run the state once and keep the return data
  1447. state_run = self.run_function('state.sls', mods='requisites.listen_in_names')
  1448. self.assertIn('test_|-listener_service_|-nginx_|-mod_watch', state_run)
  1449. self.assertIn('test_|-listener_service_|-crond_|-mod_watch', state_run)
  1450. def test_listen_requisite_resolution_names(self):
  1451. '''
  1452. Verify listen requisite lookups use ID declaration to check for changes
  1453. and resolves magic names state variable
  1454. '''
  1455. # Only run the state once and keep the return data
  1456. state_run = self.run_function('state.sls', mods='requisites.listen_names')
  1457. self.assertIn('test_|-listener_service_|-nginx_|-mod_watch', state_run)
  1458. self.assertIn('test_|-listener_service_|-crond_|-mod_watch', state_run)
  1459. def test_issue_30820_requisite_in_match_by_name(self):
  1460. '''
  1461. This tests the case where a requisite_in matches by name instead of ID
  1462. See https://github.com/saltstack/salt/issues/30820 for more info
  1463. '''
  1464. state_run = self.run_function(
  1465. 'state.sls',
  1466. mods='requisites.requisite_in_match_by_name'
  1467. )
  1468. bar_state = 'cmd_|-bar state_|-echo bar_|-wait'
  1469. self.assertIn(bar_state, state_run)
  1470. self.assertEqual(state_run[bar_state]['comment'],
  1471. 'Command "echo bar" run')
  1472. def test_retry_option_defaults(self):
  1473. '''
  1474. test the retry option on a simple state with defaults
  1475. ensure comment is as expected
  1476. ensure state duration is greater than default retry_interval (30 seconds)
  1477. '''
  1478. state_run = self.run_function(
  1479. 'state.sls',
  1480. mods='retry.retry_defaults'
  1481. )
  1482. retry_state = 'file_|-file_test_|-/path/to/a/non-existent/file.txt_|-exists'
  1483. expected_comment = ('Attempt 1: Returned a result of "False", with the following '
  1484. 'comment: "Specified path /path/to/a/non-existent/file.txt does not exist"\n'
  1485. 'Specified path /path/to/a/non-existent/file.txt does not exist')
  1486. self.assertEqual(state_run[retry_state]['comment'], expected_comment)
  1487. self.assertTrue(state_run[retry_state]['duration'] > 30)
  1488. self.assertEqual(state_run[retry_state]['result'], False)
  1489. def test_retry_option_custom(self):
  1490. '''
  1491. test the retry option on a simple state with custom retry values
  1492. ensure comment is as expected
  1493. ensure state duration is greater than custom defined interval * (retries - 1)
  1494. '''
  1495. state_run = self.run_function(
  1496. 'state.sls',
  1497. mods='retry.retry_custom'
  1498. )
  1499. retry_state = 'file_|-file_test_|-/path/to/a/non-existent/file.txt_|-exists'
  1500. expected_comment = ('Attempt 1: Returned a result of "False", with the following '
  1501. 'comment: "Specified path /path/to/a/non-existent/file.txt does not exist"\n'
  1502. 'Attempt 2: Returned a result of "False", with the following comment: "Specified'
  1503. ' path /path/to/a/non-existent/file.txt does not exist"\nAttempt 3: Returned'
  1504. ' a result of "False", with the following comment: "Specified path'
  1505. ' /path/to/a/non-existent/file.txt does not exist"\nAttempt 4: Returned a'
  1506. ' result of "False", with the following comment: "Specified path'
  1507. ' /path/to/a/non-existent/file.txt does not exist"\nSpecified path'
  1508. ' /path/to/a/non-existent/file.txt does not exist')
  1509. self.assertEqual(state_run[retry_state]['comment'], expected_comment)
  1510. self.assertTrue(state_run[retry_state]['duration'] > 40)
  1511. self.assertEqual(state_run[retry_state]['result'], False)
  1512. def test_retry_option_success(self):
  1513. '''
  1514. test a state with the retry option that should return True immedietly (i.e. no retries)
  1515. '''
  1516. testfile = os.path.join(TMP, 'retry_file')
  1517. state_run = self.run_function(
  1518. 'state.sls',
  1519. mods='retry.retry_success'
  1520. )
  1521. os.unlink(testfile)
  1522. retry_state = 'file_|-file_test_|-{0}_|-exists'.format(testfile)
  1523. self.assertNotIn('Attempt', state_run[retry_state]['comment'])
  1524. def run_create(self):
  1525. '''
  1526. helper function to wait 30 seconds and then create the temp retry file
  1527. '''
  1528. testfile = os.path.join(TMP, 'retry_file')
  1529. time.sleep(30)
  1530. with salt.utils.files.fopen(testfile, 'a'):
  1531. pass
  1532. def test_retry_option_eventual_success(self):
  1533. '''
  1534. test a state with the retry option that should return True after at least 4 retry attmempt
  1535. but never run 15 attempts
  1536. '''
  1537. testfile = os.path.join(TMP, 'retry_file')
  1538. create_thread = threading.Thread(target=self.run_create)
  1539. create_thread.start()
  1540. state_run = self.run_function(
  1541. 'state.sls',
  1542. mods='retry.retry_success2'
  1543. )
  1544. retry_state = 'file_|-file_test_|-{0}_|-exists'.format(testfile)
  1545. self.assertIn('Attempt 1:', state_run[retry_state]['comment'])
  1546. self.assertIn('Attempt 2:', state_run[retry_state]['comment'])
  1547. self.assertIn('Attempt 3:', state_run[retry_state]['comment'])
  1548. self.assertIn('Attempt 4:', state_run[retry_state]['comment'])
  1549. self.assertNotIn('Attempt 15:', state_run[retry_state]['comment'])
  1550. self.assertEqual(state_run[retry_state]['result'], True)
  1551. def test_issue_38683_require_order_failhard_combination(self):
  1552. '''
  1553. This tests the case where require, order, and failhard are all used together in a state definition.
  1554. Previously, the order option, which used in tandem with require and failhard, would cause the state
  1555. compiler to stacktrace. This exposed a logic error in the ``check_failhard`` function of the state
  1556. compiler. With the logic error resolved, this test should now pass.
  1557. See https://github.com/saltstack/salt/issues/38683 for more information.
  1558. '''
  1559. state_run = self.run_function(
  1560. 'state.sls',
  1561. mods='requisites.require_order_failhard_combo'
  1562. )
  1563. state_id = 'test_|-b_|-b_|-fail_with_changes'
  1564. self.assertIn(state_id, state_run)
  1565. self.assertEqual(state_run[state_id]['comment'], 'Failure!')
  1566. self.assertFalse(state_run[state_id]['result'])
  1567. def test_issue_46762_prereqs_on_a_state_with_unfulfilled_requirements(self):
  1568. '''
  1569. This tests the case where state C requires state A, which fails.
  1570. State C is a pre-required state for State B.
  1571. Since state A fails, state C will not run because the requisite failed,
  1572. therefore state B will not run because state C failed to run.
  1573. See https://github.com/saltstack/salt/issues/46762 for
  1574. more information.
  1575. '''
  1576. state_run = self.run_function(
  1577. 'state.sls',
  1578. mods='issue-46762'
  1579. )
  1580. state_id = 'test_|-a_|-a_|-fail_without_changes'
  1581. self.assertIn(state_id, state_run)
  1582. self.assertEqual(state_run[state_id]['comment'],
  1583. 'Failure!')
  1584. self.assertFalse(state_run[state_id]['result'])
  1585. state_id = 'test_|-b_|-b_|-nop'
  1586. self.assertIn(state_id, state_run)
  1587. self.assertEqual(state_run[state_id]['comment'],
  1588. 'One or more requisite failed: issue-46762.c')
  1589. self.assertFalse(state_run[state_id]['result'])
  1590. state_id = 'test_|-c_|-c_|-nop'
  1591. self.assertIn(state_id, state_run)
  1592. self.assertEqual(state_run[state_id]['comment'],
  1593. 'One or more requisite failed: issue-46762.a')
  1594. self.assertFalse(state_run[state_id]['result'])
  1595. def test_state_nonbase_environment(self):
  1596. '''
  1597. test state.sls with saltenv using a nonbase environment
  1598. with a salt source
  1599. '''
  1600. filename = os.path.join(TMP, 'nonbase_env')
  1601. try:
  1602. ret = self.run_function(
  1603. 'state.sls',
  1604. mods='non-base-env',
  1605. saltenv='prod'
  1606. )
  1607. ret = ret[next(iter(ret))]
  1608. assert ret['result']
  1609. assert ret['comment'] == 'File {0} updated'.format(filename)
  1610. assert os.path.isfile(filename)
  1611. finally:
  1612. try:
  1613. os.remove(filename)
  1614. except OSError:
  1615. pass
  1616. @skipIf(sys.platform.startswith('win'), 'Skipped until parallel states can be fixed on Windows')
  1617. def test_parallel_state_with_long_tag(self):
  1618. '''
  1619. This tests the case where the state being executed has a long ID dec or
  1620. name and states are being run in parallel. The filenames used for the
  1621. parallel state cache were previously based on the tag for each chunk,
  1622. and longer ID decs or name params can cause the cache file to be longer
  1623. than the operating system's max file name length. To counter this we
  1624. instead generate a SHA1 hash of the chunk's tag to use as the cache
  1625. filename. This test will ensure that long tags don't cause caching
  1626. failures.
  1627. See https://github.com/saltstack/salt/issues/49738 for more info.
  1628. '''
  1629. short_command = 'helloworld'
  1630. long_command = short_command * 25
  1631. ret = self.run_function(
  1632. 'state.sls',
  1633. mods='issue-49738',
  1634. pillar={'short_command': short_command,
  1635. 'long_command': long_command}
  1636. )
  1637. comments = sorted([x['comment'] for x in six.itervalues(ret)])
  1638. expected = sorted(['Command "{0}" run'.format(x)
  1639. for x in (short_command, long_command)])
  1640. assert comments == expected, '{0} != {1}'.format(comments, expected)
  1641. def _add_runtime_pillar(self, pillar):
  1642. '''
  1643. helper class to add pillar data at runtime
  1644. '''
  1645. import salt.utils.yaml
  1646. with salt.utils.files.fopen(os.path.join(TMP_PILLAR_TREE,
  1647. 'pillar.sls'), 'w') as fp:
  1648. salt.utils.yaml.safe_dump(pillar, fp)
  1649. with salt.utils.files.fopen(os.path.join(TMP_PILLAR_TREE, 'top.sls'), 'w') as fp:
  1650. fp.write(textwrap.dedent('''\
  1651. base:
  1652. '*':
  1653. - pillar
  1654. '''))
  1655. self.run_function('saltutil.refresh_pillar')
  1656. self.run_function('test.sleep', [5])
  1657. def test_state_sls_id_test(self):
  1658. '''
  1659. test state.sls_id when test is set
  1660. to true in pillar data
  1661. '''
  1662. self._add_runtime_pillar(pillar={'test': True})
  1663. testfile = os.path.join(TMP, 'testfile')
  1664. comment = 'The file {0} is set to be changed'.format(testfile)
  1665. ret = self.run_function('state.sls', ['core'])
  1666. for key, val in ret.items():
  1667. self.assertEqual(val['comment'], comment)
  1668. self.assertEqual(val['changes'], {'newfile': testfile})
  1669. def test_state_sls_id_test_state_test_post_run(self):
  1670. '''
  1671. test state.sls_id when test is set to
  1672. true post the state already being run previously
  1673. '''
  1674. file_name = os.path.join(TMP, 'testfile')
  1675. ret = self.run_function('state.sls', ['core'])
  1676. for key, val in ret.items():
  1677. self.assertEqual(val['comment'],
  1678. 'File {0} updated'.format(file_name))
  1679. self.assertEqual(val['changes']['diff'], 'New file')
  1680. self._add_runtime_pillar(pillar={'test': True})
  1681. ret = self.run_function('state.sls', ['core'])
  1682. for key, val in ret.items():
  1683. self.assertEqual(
  1684. val['comment'],
  1685. 'The file {0} is in the correct state'.format(file_name))
  1686. self.assertEqual(val['changes'], {})
  1687. def test_state_sls_id_test_true(self):
  1688. '''
  1689. test state.sls_id when test=True is passed as arg
  1690. '''
  1691. file_name = os.path.join(TMP, 'testfile')
  1692. ret = self.run_function('state.sls', ['core'], test=True)
  1693. for key, val in ret.items():
  1694. self.assertEqual(
  1695. val['comment'],
  1696. 'The file {0} is set to be changed'.format(file_name))
  1697. self.assertEqual(val['changes'], {'newfile': file_name})
  1698. def test_state_sls_id_test_true_post_run(self):
  1699. '''
  1700. test state.sls_id when test is set to true as an
  1701. arg post the state already being run previously
  1702. '''
  1703. file_name = os.path.join(TMP, 'testfile')
  1704. ret = self.run_function('state.sls', ['core'])
  1705. for key, val in ret.items():
  1706. self.assertEqual(val['comment'],
  1707. 'File {0} updated'.format(file_name))
  1708. self.assertEqual(val['changes']['diff'], 'New file')
  1709. ret = self.run_function('state.sls', ['core'], test=True)
  1710. for key, val in ret.items():
  1711. self.assertEqual(
  1712. val['comment'],
  1713. 'The file {0} is in the correct state'.format(file_name))
  1714. self.assertEqual(val['changes'], {})
  1715. def test_state_sls_id_test_false_pillar_true(self):
  1716. '''
  1717. test state.sls_id when test is set to false as an
  1718. arg and minion_state_test is set to True. Should
  1719. return test=False.
  1720. '''
  1721. file_name = os.path.join(TMP, 'testfile')
  1722. self._add_runtime_pillar(pillar={'test': True})
  1723. ret = self.run_function('state.sls', ['core'], test=False)
  1724. for key, val in ret.items():
  1725. self.assertEqual(val['comment'],
  1726. 'File {0} updated'.format(file_name))
  1727. self.assertEqual(val['changes']['diff'], 'New file')
  1728. @skipIf(six.PY3 and salt.utils.platform.is_darwin(), 'Test is broken on macosx and PY3')
  1729. def test_state_sls_unicode_characters(self):
  1730. '''
  1731. test state.sls when state file contains non-ascii characters
  1732. '''
  1733. ret = self.run_function('state.sls', ['issue-46672'])
  1734. log.debug('== ret %s ==', type(ret))
  1735. _expected = "cmd_|-echo1_|-echo 'This is Æ test!'_|-run"
  1736. self.assertIn(_expected, ret)
  1737. @skipIf(six.PY3 and salt.utils.platform.is_darwin(), 'Test is broken on macosx and PY3')
  1738. def test_state_sls_unicode_characters_cmd_output(self):
  1739. '''
  1740. test the output from running and echo command with non-ascii
  1741. characters.
  1742. '''
  1743. ret = self.run_function('state.sls', ['issue-46672-a'])
  1744. key = list(ret.keys())[0]
  1745. log.debug('== ret %s ==', type(ret))
  1746. _expected = 'This is Æ test!'
  1747. if salt.utils.platform.is_windows():
  1748. # Windows cmd.exe will mangle the output using cmd's codepage.
  1749. if six.PY2:
  1750. _expected = "'This is A+ test!'"
  1751. else:
  1752. _expected = "'This is ’ test!'"
  1753. self.assertEqual(_expected, ret[key]['changes']['stdout'])
  1754. def tearDown(self):
  1755. nonbase_file = os.path.join(TMP, 'nonbase_env')
  1756. if os.path.isfile(nonbase_file):
  1757. os.remove(nonbase_file)
  1758. # remove old pillar data
  1759. for filename in os.listdir(TMP_PILLAR_TREE):
  1760. os.remove(os.path.join(TMP_PILLAR_TREE, filename))
  1761. self.run_function('saltutil.refresh_pillar')
  1762. self.run_function('test.sleep', [5])
  1763. # remove testfile added in core.sls state file
  1764. state_file = os.path.join(TMP, 'testfile')
  1765. if os.path.isfile(state_file):
  1766. os.remove(state_file)
  1767. def test_state_sls_integer_name(self):
  1768. '''
  1769. This tests the case where the state file is named
  1770. only with integers
  1771. '''
  1772. state_run = self.run_function(
  1773. 'state.sls',
  1774. mods='12345'
  1775. )
  1776. state_id = 'test_|-always-passes_|-always-passes_|-succeed_without_changes'
  1777. self.assertIn(state_id, state_run)
  1778. self.assertEqual(state_run[state_id]['comment'],
  1779. 'Success!')
  1780. self.assertTrue(state_run[state_id]['result'])