test_state.py 95 KB

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