test_state.py 84 KB

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