1
0

test_state.py 96 KB

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