test_state.py 98 KB

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