test_file.py 191 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191
  1. # -*- coding: utf-8 -*-
  2. """
  3. Tests for the file state
  4. """
  5. from __future__ import absolute_import, print_function, unicode_literals
  6. import errno
  7. import filecmp
  8. import logging
  9. import os
  10. import re
  11. import shutil
  12. import stat
  13. import sys
  14. import tempfile
  15. import textwrap
  16. import pytest
  17. import salt.serializers.configparser
  18. import salt.utils.data
  19. import salt.utils.files
  20. import salt.utils.json
  21. import salt.utils.path
  22. import salt.utils.platform
  23. import salt.utils.stringutils
  24. from salt.ext import six
  25. from salt.ext.six.moves import range
  26. from salt.utils.versions import LooseVersion as _LooseVersion
  27. from tests.support.case import ModuleCase
  28. from tests.support.helpers import (
  29. Webserver,
  30. dedent,
  31. with_system_user_and_group,
  32. with_tempdir,
  33. with_tempfile,
  34. )
  35. from tests.support.mixins import SaltReturnAssertsMixin
  36. from tests.support.runtests import RUNTIME_VARS
  37. from tests.support.unit import skipIf
  38. log = logging.getLogger(__name__)
  39. HAS_PWD = True
  40. try:
  41. import pwd
  42. except ImportError:
  43. HAS_PWD = False
  44. HAS_GRP = True
  45. try:
  46. import grp
  47. except ImportError:
  48. HAS_GRP = False
  49. IS_WINDOWS = salt.utils.platform.is_windows()
  50. BINARY_FILE = b"GIF89a\x01\x00\x01\x00\x80\x00\x00\x05\x04\x04\x00\x00\x00,\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02D\x01\x00;"
  51. TEST_SYSTEM_USER = "test_system_user"
  52. TEST_SYSTEM_GROUP = "test_system_group"
  53. def _test_managed_file_mode_keep_helper(testcase, local=False):
  54. """
  55. DRY helper function to run the same test with a local or remote path
  56. """
  57. name = os.path.join(RUNTIME_VARS.TMP, "scene33")
  58. grail_fs_path = os.path.join(RUNTIME_VARS.BASE_FILES, "grail", "scene33")
  59. grail = "salt://grail/scene33" if not local else grail_fs_path
  60. # Get the current mode so that we can put the file back the way we
  61. # found it when we're done.
  62. grail_fs_mode = int(testcase.run_function("file.get_mode", [grail_fs_path]), 8)
  63. initial_mode = 0o770
  64. new_mode_1 = 0o600
  65. new_mode_2 = 0o644
  66. # Set the initial mode, so we can be assured that when we set the mode
  67. # to "keep", we're actually changing the permissions of the file to the
  68. # new mode.
  69. ret = testcase.run_state(
  70. "file.managed", name=name, mode=oct(initial_mode), source=grail,
  71. )
  72. if IS_WINDOWS:
  73. testcase.assertSaltFalseReturn(ret)
  74. return
  75. testcase.assertSaltTrueReturn(ret)
  76. try:
  77. # Update the mode on the fileserver (pass 1)
  78. os.chmod(grail_fs_path, new_mode_1)
  79. ret = testcase.run_state("file.managed", name=name, mode="keep", source=grail,)
  80. testcase.assertSaltTrueReturn(ret)
  81. managed_mode = stat.S_IMODE(os.stat(name).st_mode)
  82. testcase.assertEqual(oct(managed_mode), oct(new_mode_1))
  83. # Update the mode on the fileserver (pass 2)
  84. # This assures us that if the file in file_roots was originally set
  85. # to the same mode as new_mode_1, we definitely get an updated mode
  86. # this time.
  87. os.chmod(grail_fs_path, new_mode_2)
  88. ret = testcase.run_state("file.managed", name=name, mode="keep", source=grail,)
  89. testcase.assertSaltTrueReturn(ret)
  90. managed_mode = stat.S_IMODE(os.stat(name).st_mode)
  91. testcase.assertEqual(oct(managed_mode), oct(new_mode_2))
  92. finally:
  93. # Set the mode of the file in the file_roots back to what it
  94. # originally was.
  95. os.chmod(grail_fs_path, grail_fs_mode)
  96. @pytest.mark.windows_whitelisted
  97. class FileTest(ModuleCase, SaltReturnAssertsMixin):
  98. """
  99. Validate the file state
  100. """
  101. def _delete_file(self, path):
  102. try:
  103. os.remove(path)
  104. except OSError as exc:
  105. if exc.errno != errno.ENOENT:
  106. log.error("Failed to remove %s: %s", path, exc)
  107. def tearDown(self):
  108. """
  109. remove files created in previous tests
  110. """
  111. user = "salt"
  112. if user in str(self.run_function("user.list_users")):
  113. self.run_function("user.delete", [user])
  114. @pytest.mark.slow_test(seconds=60) # Test takes >30 and <=60 seconds
  115. def test_symlink(self):
  116. """
  117. file.symlink
  118. """
  119. name = os.path.join(RUNTIME_VARS.TMP, "symlink")
  120. tgt = os.path.join(RUNTIME_VARS.TMP, "target")
  121. # Windows must have a source directory to link to
  122. if IS_WINDOWS and not os.path.isdir(tgt):
  123. os.mkdir(tgt)
  124. # Windows cannot create a symlink if it already exists
  125. if IS_WINDOWS and self.run_function("file.is_link", [name]):
  126. self.run_function("file.remove", [name])
  127. ret = self.run_state("file.symlink", name=name, target=tgt)
  128. self.assertSaltTrueReturn(ret)
  129. @pytest.mark.slow_test(seconds=30) # Test takes >10 and <=30 seconds
  130. def test_test_symlink(self):
  131. """
  132. file.symlink test interface
  133. """
  134. name = os.path.join(RUNTIME_VARS.TMP, "symlink2")
  135. tgt = os.path.join(RUNTIME_VARS.TMP, "target")
  136. ret = self.run_state("file.symlink", test=True, name=name, target=tgt)
  137. self.assertSaltNoneReturn(ret)
  138. @pytest.mark.slow_test(seconds=30) # Test takes >10 and <=30 seconds
  139. def test_absent_file(self):
  140. """
  141. file.absent
  142. """
  143. name = os.path.join(RUNTIME_VARS.TMP, "file_to_kill")
  144. with salt.utils.files.fopen(name, "w+") as fp_:
  145. fp_.write("killme")
  146. ret = self.run_state("file.absent", name=name)
  147. self.assertSaltTrueReturn(ret)
  148. self.assertFalse(os.path.isfile(name))
  149. @pytest.mark.slow_test(seconds=30) # Test takes >10 and <=30 seconds
  150. def test_absent_dir(self):
  151. """
  152. file.absent
  153. """
  154. name = os.path.join(RUNTIME_VARS.TMP, "dir_to_kill")
  155. if not os.path.isdir(name):
  156. # left behind... Don't fail because of this!
  157. os.makedirs(name)
  158. ret = self.run_state("file.absent", name=name)
  159. self.assertSaltTrueReturn(ret)
  160. self.assertFalse(os.path.isdir(name))
  161. @pytest.mark.slow_test(seconds=120) # Test takes >60 and <=120 seconds
  162. def test_absent_link(self):
  163. """
  164. file.absent
  165. """
  166. name = os.path.join(RUNTIME_VARS.TMP, "link_to_kill")
  167. tgt = "{0}.tgt".format(name)
  168. # Windows must have a source directory to link to
  169. if IS_WINDOWS and not os.path.isdir(tgt):
  170. os.mkdir(tgt)
  171. if not self.run_function("file.is_link", [name]):
  172. self.run_function("file.symlink", [tgt, name])
  173. ret = self.run_state("file.absent", name=name)
  174. try:
  175. self.assertSaltTrueReturn(ret)
  176. self.assertFalse(self.run_function("file.is_link", [name]))
  177. finally:
  178. if self.run_function("file.is_link", [name]):
  179. self.run_function("file.remove", [name])
  180. @with_tempfile()
  181. @pytest.mark.slow_test(seconds=30) # Test takes >10 and <=30 seconds
  182. def test_test_absent(self, name):
  183. """
  184. file.absent test interface
  185. """
  186. with salt.utils.files.fopen(name, "w+") as fp_:
  187. fp_.write("killme")
  188. ret = self.run_state("file.absent", test=True, name=name)
  189. self.assertSaltNoneReturn(ret)
  190. self.assertTrue(os.path.isfile(name))
  191. @pytest.mark.slow_test(seconds=30) # Test takes >10 and <=30 seconds
  192. def test_managed(self):
  193. """
  194. file.managed
  195. """
  196. name = os.path.join(RUNTIME_VARS.TMP, "grail_scene33")
  197. ret = self.run_state("file.managed", name=name, source="salt://grail/scene33")
  198. src = os.path.join(RUNTIME_VARS.BASE_FILES, "grail", "scene33")
  199. with salt.utils.files.fopen(src, "r") as fp_:
  200. master_data = fp_.read()
  201. with salt.utils.files.fopen(name, "r") as fp_:
  202. minion_data = fp_.read()
  203. self.assertEqual(master_data, minion_data)
  204. self.assertSaltTrueReturn(ret)
  205. @pytest.mark.slow_test(seconds=30) # Test takes >10 and <=30 seconds
  206. def test_managed_file_mode(self):
  207. """
  208. file.managed, correct file permissions
  209. """
  210. desired_mode = 504 # 0770 octal
  211. name = os.path.join(RUNTIME_VARS.TMP, "grail_scene33")
  212. ret = self.run_state(
  213. "file.managed", name=name, mode="0770", source="salt://grail/scene33"
  214. )
  215. if IS_WINDOWS:
  216. expected = "The 'mode' option is not supported on Windows"
  217. self.assertEqual(ret[list(ret)[0]]["comment"], expected)
  218. self.assertSaltFalseReturn(ret)
  219. return
  220. resulting_mode = stat.S_IMODE(os.stat(name).st_mode)
  221. self.assertEqual(oct(desired_mode), oct(resulting_mode))
  222. self.assertSaltTrueReturn(ret)
  223. @skipIf(IS_WINDOWS, "Windows does not report any file modes. Skipping.")
  224. @pytest.mark.slow_test(seconds=5) # Test takes >1 and <=5 seconds
  225. def test_managed_file_mode_keep(self):
  226. """
  227. Test using "mode: keep" in a file.managed state
  228. """
  229. _test_managed_file_mode_keep_helper(self, local=False)
  230. @skipIf(IS_WINDOWS, "Windows does not report any file modes. Skipping.")
  231. @pytest.mark.slow_test(seconds=5) # Test takes >1 and <=5 seconds
  232. def test_managed_file_mode_keep_local_source(self):
  233. """
  234. Test using "mode: keep" in a file.managed state, with a local file path
  235. as the source.
  236. """
  237. _test_managed_file_mode_keep_helper(self, local=True)
  238. @pytest.mark.slow_test(seconds=30) # Test takes >10 and <=30 seconds
  239. def test_managed_file_mode_file_exists_replace(self):
  240. """
  241. file.managed, existing file with replace=True, change permissions
  242. """
  243. initial_mode = 504 # 0770 octal
  244. desired_mode = 384 # 0600 octal
  245. name = os.path.join(RUNTIME_VARS.TMP, "grail_scene33")
  246. ret = self.run_state(
  247. "file.managed",
  248. name=name,
  249. mode=oct(initial_mode),
  250. source="salt://grail/scene33",
  251. )
  252. if IS_WINDOWS:
  253. expected = "The 'mode' option is not supported on Windows"
  254. self.assertEqual(ret[list(ret)[0]]["comment"], expected)
  255. self.assertSaltFalseReturn(ret)
  256. return
  257. resulting_mode = stat.S_IMODE(os.stat(name).st_mode)
  258. self.assertEqual(oct(initial_mode), oct(resulting_mode))
  259. name = os.path.join(RUNTIME_VARS.TMP, "grail_scene33")
  260. ret = self.run_state(
  261. "file.managed",
  262. name=name,
  263. replace=True,
  264. mode=oct(desired_mode),
  265. source="salt://grail/scene33",
  266. )
  267. resulting_mode = stat.S_IMODE(os.stat(name).st_mode)
  268. self.assertEqual(oct(desired_mode), oct(resulting_mode))
  269. self.assertSaltTrueReturn(ret)
  270. @pytest.mark.slow_test(seconds=30) # Test takes >10 and <=30 seconds
  271. def test_managed_file_mode_file_exists_noreplace(self):
  272. """
  273. file.managed, existing file with replace=False, change permissions
  274. """
  275. initial_mode = 504 # 0770 octal
  276. desired_mode = 384 # 0600 octal
  277. name = os.path.join(RUNTIME_VARS.TMP, "grail_scene33")
  278. ret = self.run_state(
  279. "file.managed",
  280. name=name,
  281. replace=True,
  282. mode=oct(initial_mode),
  283. source="salt://grail/scene33",
  284. )
  285. if IS_WINDOWS:
  286. expected = "The 'mode' option is not supported on Windows"
  287. self.assertEqual(ret[list(ret)[0]]["comment"], expected)
  288. self.assertSaltFalseReturn(ret)
  289. return
  290. ret = self.run_state(
  291. "file.managed",
  292. name=name,
  293. replace=False,
  294. mode=oct(desired_mode),
  295. source="salt://grail/scene33",
  296. )
  297. resulting_mode = stat.S_IMODE(os.stat(name).st_mode)
  298. self.assertEqual(oct(desired_mode), oct(resulting_mode))
  299. self.assertSaltTrueReturn(ret)
  300. @pytest.mark.slow_test(seconds=30) # Test takes >10 and <=30 seconds
  301. def test_managed_file_with_grains_data(self):
  302. """
  303. Test to ensure we can render grains data into a managed
  304. file.
  305. """
  306. grain_path = os.path.join(RUNTIME_VARS.TMP, "file-grain-test")
  307. state_file = "file-grainget"
  308. self.run_function("state.sls", [state_file], pillar={"grain_path": grain_path})
  309. self.assertTrue(os.path.exists(grain_path))
  310. with salt.utils.files.fopen(grain_path, "r") as fp_:
  311. file_contents = fp_.readlines()
  312. if IS_WINDOWS:
  313. match = "^minion\r\n"
  314. else:
  315. match = "^minion\n"
  316. self.assertTrue(re.match(match, file_contents[0]))
  317. @pytest.mark.slow_test(seconds=60) # Test takes >30 and <=60 seconds
  318. def test_managed_file_with_pillar_sls(self):
  319. """
  320. Test to ensure pillar data in sls file
  321. is rendered properly and file is created.
  322. """
  323. file_pillar = os.path.join(RUNTIME_VARS.TMP, "filepillar-python")
  324. self.addCleanup(self._delete_file, file_pillar)
  325. state_name = "file-pillarget"
  326. log.warning("File Path: %s", file_pillar)
  327. ret = self.run_function("state.sls", [state_name])
  328. self.assertSaltTrueReturn(ret)
  329. # Check to make sure the file was created
  330. check_file = self.run_function("file.file_exists", [file_pillar])
  331. self.assertTrue(check_file)
  332. @pytest.mark.slow_test(seconds=60) # Test takes >30 and <=60 seconds
  333. def test_managed_file_with_pillardefault_sls(self):
  334. """
  335. Test to ensure when pillar data is not available
  336. in sls file with pillar.get it uses the default
  337. value.
  338. """
  339. file_pillar_def = os.path.join(RUNTIME_VARS.TMP, "filepillar-defaultvalue")
  340. self.addCleanup(self._delete_file, file_pillar_def)
  341. state_name = "file-pillardefaultget"
  342. log.warning("File Path: %s", file_pillar_def)
  343. ret = self.run_function("state.sls", [state_name])
  344. self.assertSaltTrueReturn(ret)
  345. # Check to make sure the file was created
  346. check_file = self.run_function("file.file_exists", [file_pillar_def])
  347. self.assertTrue(check_file)
  348. @pytest.mark.skip_if_not_root
  349. @pytest.mark.slow_test(seconds=30) # Test takes >10 and <=30 seconds
  350. def test_managed_dir_mode(self):
  351. """
  352. Tests to ensure that file.managed creates directories with the
  353. permissions requested with the dir_mode argument
  354. """
  355. desired_mode = 511 # 0777 in octal
  356. name = os.path.join(RUNTIME_VARS.TMP, "a", "managed_dir_mode_test_file")
  357. desired_owner = "nobody"
  358. ret = self.run_state(
  359. "file.managed",
  360. name=name,
  361. source="salt://grail/scene33",
  362. mode=600,
  363. makedirs=True,
  364. user=desired_owner,
  365. dir_mode=oct(desired_mode), # 0777
  366. )
  367. if IS_WINDOWS:
  368. expected = "The 'mode' option is not supported on Windows"
  369. self.assertEqual(ret[list(ret)[0]]["comment"], expected)
  370. self.assertSaltFalseReturn(ret)
  371. return
  372. resulting_mode = stat.S_IMODE(
  373. os.stat(os.path.join(RUNTIME_VARS.TMP, "a")).st_mode
  374. )
  375. resulting_owner = pwd.getpwuid(
  376. os.stat(os.path.join(RUNTIME_VARS.TMP, "a")).st_uid
  377. ).pw_name
  378. self.assertEqual(oct(desired_mode), oct(resulting_mode))
  379. self.assertSaltTrueReturn(ret)
  380. self.assertEqual(desired_owner, resulting_owner)
  381. @pytest.mark.slow_test(seconds=30) # Test takes >10 and <=30 seconds
  382. def test_test_managed(self):
  383. """
  384. file.managed test interface
  385. """
  386. name = os.path.join(RUNTIME_VARS.TMP, "grail_not_not_scene33")
  387. ret = self.run_state(
  388. "file.managed", test=True, name=name, source="salt://grail/scene33"
  389. )
  390. self.assertSaltNoneReturn(ret)
  391. self.assertFalse(os.path.isfile(name))
  392. @pytest.mark.slow_test(seconds=30) # Test takes >10 and <=30 seconds
  393. def test_managed_show_changes_false(self):
  394. """
  395. file.managed test interface
  396. """
  397. name = os.path.join(RUNTIME_VARS.TMP, "grail_not_scene33")
  398. with salt.utils.files.fopen(name, "wb") as fp_:
  399. fp_.write(b"test_managed_show_changes_false\n")
  400. ret = self.run_state(
  401. "file.managed", name=name, source="salt://grail/scene33", show_changes=False
  402. )
  403. changes = next(six.itervalues(ret))["changes"]
  404. self.assertEqual("<show_changes=False>", changes["diff"])
  405. @pytest.mark.slow_test(seconds=30) # Test takes >10 and <=30 seconds
  406. def test_managed_show_changes_true(self):
  407. """
  408. file.managed test interface
  409. """
  410. name = os.path.join(RUNTIME_VARS.TMP, "grail_not_scene33")
  411. with salt.utils.files.fopen(name, "wb") as fp_:
  412. fp_.write(b"test_managed_show_changes_false\n")
  413. ret = self.run_state("file.managed", name=name, source="salt://grail/scene33",)
  414. changes = next(six.itervalues(ret))["changes"]
  415. self.assertIn("diff", changes)
  416. @skipIf(IS_WINDOWS, "Don't know how to fix for Windows")
  417. @pytest.mark.slow_test(seconds=5) # Test takes >1 and <=5 seconds
  418. def test_managed_escaped_file_path(self):
  419. """
  420. file.managed test that 'salt://|' protects unusual characters in file path
  421. """
  422. funny_file = salt.utils.files.mkstemp(
  423. prefix="?f!le? n@=3&", suffix=".file type"
  424. )
  425. funny_file_name = os.path.split(funny_file)[1]
  426. funny_url = "salt://|" + funny_file_name
  427. funny_url_path = os.path.join(RUNTIME_VARS.BASE_FILES, funny_file_name)
  428. state_name = "funny_file"
  429. state_file_name = state_name + ".sls"
  430. state_file = os.path.join(RUNTIME_VARS.BASE_FILES, state_file_name)
  431. state_key = "file_|-{0}_|-{0}_|-managed".format(funny_file)
  432. self.addCleanup(os.remove, state_file)
  433. self.addCleanup(os.remove, funny_file)
  434. self.addCleanup(os.remove, funny_url_path)
  435. with salt.utils.files.fopen(funny_url_path, "w"):
  436. pass
  437. with salt.utils.files.fopen(state_file, "w") as fp_:
  438. fp_.write(
  439. textwrap.dedent(
  440. """\
  441. {0}:
  442. file.managed:
  443. - source: {1}
  444. - makedirs: True
  445. """.format(
  446. funny_file, funny_url
  447. )
  448. )
  449. )
  450. ret = self.run_function("state.sls", [state_name])
  451. self.assertTrue(ret[state_key]["result"])
  452. @pytest.mark.slow_test(seconds=30) # Test takes >10 and <=30 seconds
  453. def test_managed_contents(self):
  454. """
  455. test file.managed with contents that is a boolean, string, integer,
  456. float, list, and dictionary
  457. """
  458. state_name = "file-FileTest-test_managed_contents"
  459. state_filename = state_name + ".sls"
  460. state_file = os.path.join(RUNTIME_VARS.BASE_FILES, state_filename)
  461. managed_files = {}
  462. state_keys = {}
  463. for typ in ("bool", "str", "int", "float", "list", "dict"):
  464. managed_files[typ] = salt.utils.files.mkstemp()
  465. state_keys[typ] = "file_|-{0} file_|-{1}_|-managed".format(
  466. typ, managed_files[typ]
  467. )
  468. try:
  469. with salt.utils.files.fopen(state_file, "w") as fd_:
  470. fd_.write(
  471. textwrap.dedent(
  472. """\
  473. bool file:
  474. file.managed:
  475. - name: {bool}
  476. - contents: True
  477. str file:
  478. file.managed:
  479. - name: {str}
  480. - contents: Salt was here.
  481. int file:
  482. file.managed:
  483. - name: {int}
  484. - contents: 340282366920938463463374607431768211456
  485. float file:
  486. file.managed:
  487. - name: {float}
  488. - contents: 1.7518e-45 # gravitational coupling constant
  489. list file:
  490. file.managed:
  491. - name: {list}
  492. - contents: [1, 1, 2, 3, 5, 8, 13]
  493. dict file:
  494. file.managed:
  495. - name: {dict}
  496. - contents:
  497. C: charge
  498. P: parity
  499. T: time
  500. """.format(
  501. **managed_files
  502. )
  503. )
  504. )
  505. ret = self.run_function("state.sls", [state_name])
  506. self.assertSaltTrueReturn(ret)
  507. for typ in state_keys:
  508. self.assertTrue(ret[state_keys[typ]]["result"])
  509. self.assertIn("diff", ret[state_keys[typ]]["changes"])
  510. finally:
  511. if os.path.exists(state_file):
  512. os.remove(state_file)
  513. for typ in managed_files:
  514. if os.path.exists(managed_files[typ]):
  515. os.remove(managed_files[typ])
  516. @pytest.mark.slow_test(seconds=30) # Test takes >10 and <=30 seconds
  517. def test_managed_contents_with_contents_newline(self):
  518. """
  519. test file.managed with contents by using the default content_newline
  520. flag.
  521. """
  522. contents = "test_managed_contents_with_newline_one"
  523. name = os.path.join(RUNTIME_VARS.TMP, "foo")
  524. # Create a file named foo with contents as above but with a \n at EOF
  525. self.run_state(
  526. "file.managed", name=name, contents=contents, contents_newline=True
  527. )
  528. with salt.utils.files.fopen(name, "r") as fp_:
  529. last_line = fp_.read()
  530. self.assertEqual((contents + os.linesep), last_line)
  531. @pytest.mark.slow_test(seconds=30) # Test takes >10 and <=30 seconds
  532. def test_managed_contents_with_contents_newline_false(self):
  533. """
  534. test file.managed with contents by using the non default content_newline
  535. flag.
  536. """
  537. contents = "test_managed_contents_with_newline_one"
  538. name = os.path.join(RUNTIME_VARS.TMP, "bar")
  539. # Create a file named foo with contents as above but with a \n at EOF
  540. self.run_state(
  541. "file.managed", name=name, contents=contents, contents_newline=False
  542. )
  543. with salt.utils.files.fopen(name, "r") as fp_:
  544. last_line = fp_.read()
  545. self.assertEqual(contents, last_line)
  546. @pytest.mark.slow_test(seconds=30) # Test takes >10 and <=30 seconds
  547. def test_managed_multiline_contents_with_contents_newline(self):
  548. """
  549. test file.managed with contents by using the non default content_newline
  550. flag.
  551. """
  552. contents = "this is a cookie{}this is another cookie".format(os.linesep)
  553. name = os.path.join(RUNTIME_VARS.TMP, "bar")
  554. # Create a file named foo with contents as above but with a \n at EOF
  555. self.run_state(
  556. "file.managed", name=name, contents=contents, contents_newline=True
  557. )
  558. with salt.utils.files.fopen(name, "r") as fp_:
  559. last_line = fp_.read()
  560. self.assertEqual((contents + os.linesep), last_line)
  561. @pytest.mark.slow_test(seconds=30) # Test takes >10 and <=30 seconds
  562. def test_managed_multiline_contents_with_contents_newline_false(self):
  563. """
  564. test file.managed with contents by using the non default content_newline
  565. flag.
  566. """
  567. contents = "this is a cookie{}this is another cookie".format(os.linesep)
  568. name = os.path.join(RUNTIME_VARS.TMP, "bar")
  569. # Create a file named foo with contents as above but with a \n at EOF
  570. self.run_state(
  571. "file.managed", name=name, contents=contents, contents_newline=False
  572. )
  573. with salt.utils.files.fopen(name, "r") as fp_:
  574. last_line = fp_.read()
  575. self.assertEqual(contents, last_line)
  576. @pytest.mark.skip_if_not_root
  577. @skipIf(IS_WINDOWS, 'Windows does not support "mode" kwarg. Skipping.')
  578. @skipIf(not salt.utils.path.which("visudo"), "sudo is missing")
  579. @pytest.mark.slow_test(seconds=5) # Test takes >1 and <=5 seconds
  580. def test_managed_check_cmd(self):
  581. """
  582. Test file.managed passing a basic check_cmd kwarg. See Issue #38111.
  583. """
  584. r_group = "root"
  585. if salt.utils.platform.is_darwin():
  586. r_group = "wheel"
  587. try:
  588. ret = self.run_state(
  589. "file.managed",
  590. name="/tmp/sudoers",
  591. user="root",
  592. group=r_group,
  593. mode=440,
  594. check_cmd="visudo -c -s -f",
  595. )
  596. self.assertSaltTrueReturn(ret)
  597. self.assertInSaltComment("Empty file", ret)
  598. self.assertEqual(
  599. ret["file_|-/tmp/sudoers_|-/tmp/sudoers_|-managed"]["changes"],
  600. {"new": "file /tmp/sudoers created", "mode": "0440"},
  601. )
  602. finally:
  603. # Clean Up File
  604. if os.path.exists("/tmp/sudoers"):
  605. os.remove("/tmp/sudoers")
  606. @pytest.mark.slow_test(seconds=120) # Test takes >60 and <=120 seconds
  607. def test_managed_local_source_with_source_hash(self):
  608. """
  609. Make sure that we enforce the source_hash even with local files
  610. """
  611. name = os.path.join(RUNTIME_VARS.TMP, "local_source_with_source_hash")
  612. local_path = os.path.join(RUNTIME_VARS.BASE_FILES, "grail", "scene33")
  613. actual_hash = "567fd840bf1548edc35c48eb66cdd78bfdfcccff"
  614. if IS_WINDOWS:
  615. # CRLF vs LF causes a different hash on windows
  616. actual_hash = "f658a0ec121d9c17088795afcc6ff3c43cb9842a"
  617. # Reverse the actual hash
  618. bad_hash = actual_hash[::-1]
  619. def remove_file():
  620. try:
  621. os.remove(name)
  622. except OSError as exc:
  623. if exc.errno != errno.ENOENT:
  624. raise
  625. def do_test(clean=False):
  626. for proto in ("file://", ""):
  627. source = proto + local_path
  628. log.debug("Trying source %s", source)
  629. try:
  630. ret = self.run_state(
  631. "file.managed",
  632. name=name,
  633. source=source,
  634. source_hash="sha1={0}".format(bad_hash),
  635. )
  636. self.assertSaltFalseReturn(ret)
  637. ret = ret[next(iter(ret))]
  638. # Shouldn't be any changes
  639. self.assertFalse(ret["changes"])
  640. # Check that we identified a hash mismatch
  641. self.assertIn("does not match actual checksum", ret["comment"])
  642. ret = self.run_state(
  643. "file.managed",
  644. name=name,
  645. source=source,
  646. source_hash="sha1={0}".format(actual_hash),
  647. )
  648. self.assertSaltTrueReturn(ret)
  649. finally:
  650. if clean:
  651. remove_file()
  652. remove_file()
  653. log.debug("Trying with nonexistant destination file")
  654. do_test()
  655. log.debug("Trying with destination file already present")
  656. with salt.utils.files.fopen(name, "w"):
  657. pass
  658. try:
  659. do_test(clean=False)
  660. finally:
  661. remove_file()
  662. @pytest.mark.slow_test(seconds=60) # Test takes >30 and <=60 seconds
  663. def test_managed_local_source_does_not_exist(self):
  664. """
  665. Make sure that we exit gracefully when a local source doesn't exist
  666. """
  667. name = os.path.join(RUNTIME_VARS.TMP, "local_source_does_not_exist")
  668. local_path = os.path.join(RUNTIME_VARS.BASE_FILES, "grail", "scene99")
  669. for proto in ("file://", ""):
  670. source = proto + local_path
  671. log.debug("Trying source %s", source)
  672. ret = self.run_state("file.managed", name=name, source=source)
  673. self.assertSaltFalseReturn(ret)
  674. ret = ret[next(iter(ret))]
  675. # Shouldn't be any changes
  676. self.assertFalse(ret["changes"])
  677. # Check that we identified a hash mismatch
  678. self.assertIn("does not exist", ret["comment"])
  679. @pytest.mark.slow_test(seconds=30) # Test takes >10 and <=30 seconds
  680. def test_managed_unicode_jinja_with_tojson_filter(self):
  681. """
  682. Using {{ varname }} with a list or dictionary which contains unicode
  683. types on Python 2 will result in Jinja rendering the "u" prefix on each
  684. string. This tests that using the "tojson" jinja filter will dump them
  685. to a format which can be successfully loaded by our YAML loader.
  686. The two lines that should end up being rendered are meant to test two
  687. issues that would trip up PyYAML if the "tojson" filter were not used:
  688. 1. A unicode string type would be loaded as a unicode literal with the
  689. leading "u" as well as the quotes, rather than simply being loaded
  690. as the proper unicode type which matches the content of the string
  691. literal. In other words, u'foo' would be loaded literally as
  692. u"u'foo'". This test includes actual non-ascii unicode in one of the
  693. strings to confirm that this also handles these international
  694. characters properly.
  695. 2. Any unicode string type (such as a URL) which contains a colon would
  696. cause a ScannerError in PyYAML, as it would be assumed to delimit a
  697. mapping node.
  698. Dumping the data structure to JSON using the "tojson" jinja filter
  699. should produce an inline data structure which is valid YAML and will be
  700. loaded properly by our YAML loader.
  701. """
  702. test_file = os.path.join(RUNTIME_VARS.TMP, "test-tojson.txt")
  703. ret = self.run_function(
  704. "state.apply", mods="tojson", pillar={"tojson-file": test_file}
  705. )
  706. ret = ret[next(iter(ret))]
  707. assert ret["result"], ret
  708. with salt.utils.files.fopen(test_file, mode="rb") as fp_:
  709. managed = salt.utils.stringutils.to_unicode(fp_.read())
  710. expected = dedent(
  711. """\
  712. Die Webseite ist https://saltstack.com.
  713. Der Zucker ist süß.
  714. """
  715. )
  716. assert managed == expected, "{0!r} != {1!r}".format(managed, expected)
  717. @pytest.mark.slow_test(seconds=60) # Test takes >30 and <=60 seconds
  718. def test_managed_source_hash_indifferent_case(self):
  719. """
  720. Test passing a source_hash as an uppercase hash.
  721. This is a regression test for Issue #38914 and Issue #48230 (test=true use).
  722. """
  723. name = os.path.join(RUNTIME_VARS.TMP, "source_hash_indifferent_case")
  724. state_name = "file_|-{0}_|" "-{0}_|-managed".format(name)
  725. local_path = os.path.join(RUNTIME_VARS.BASE_FILES, "hello_world.txt")
  726. actual_hash = "c98c24b677eff44860afea6f493bbaec5bb1c4cbb209c6fc2bbb47f66ff2ad31"
  727. if IS_WINDOWS:
  728. # CRLF vs LF causes a differnt hash on windows
  729. actual_hash = (
  730. "92b772380a3f8e27a93e57e6deeca6c01da07f5aadce78bb2fbb20de10a66925"
  731. )
  732. uppercase_hash = actual_hash.upper()
  733. try:
  734. # Lay down tmp file to test against
  735. self.run_state(
  736. "file.managed", name=name, source=local_path, source_hash=actual_hash
  737. )
  738. # Test uppercase source_hash: should return True with no changes
  739. ret = self.run_state(
  740. "file.managed", name=name, source=local_path, source_hash=uppercase_hash
  741. )
  742. assert ret[state_name]["result"] is True
  743. assert ret[state_name]["changes"] == {}
  744. # Test uppercase source_hash using test=true
  745. # Should return True with no changes
  746. ret = self.run_state(
  747. "file.managed",
  748. name=name,
  749. source=local_path,
  750. source_hash=uppercase_hash,
  751. test=True,
  752. )
  753. assert ret[state_name]["result"] is True
  754. assert ret[state_name]["changes"] == {}
  755. finally:
  756. # Clean Up File
  757. if os.path.exists(name):
  758. os.remove(name)
  759. @with_tempfile(create=False)
  760. @pytest.mark.slow_test(seconds=60) # Test takes >30 and <=60 seconds
  761. def test_managed_latin1_diff(self, name):
  762. """
  763. Tests that latin-1 file contents are represented properly in the diff
  764. """
  765. # Lay down the initial file
  766. ret = self.run_state(
  767. "file.managed", name=name, source="salt://issue-48777/old.html"
  768. )
  769. ret = ret[next(iter(ret))]
  770. assert ret["result"] is True, ret
  771. # Replace it with the new file and check the diff
  772. ret = self.run_state(
  773. "file.managed", name=name, source="salt://issue-48777/new.html"
  774. )
  775. ret = ret[next(iter(ret))]
  776. assert ret["result"] is True, ret
  777. diff_lines = ret["changes"]["diff"].split(os.linesep)
  778. assert "+räksmörgås" in diff_lines, diff_lines
  779. @with_tempfile()
  780. @pytest.mark.slow_test(seconds=60) # Test takes >30 and <=60 seconds
  781. def test_managed_keep_source_false_salt(self, name):
  782. """
  783. This test ensures that we properly clean the cached file if keep_source
  784. is set to False, for source files using a salt:// URL
  785. """
  786. source = "salt://grail/scene33"
  787. saltenv = "base"
  788. # Run the state
  789. ret = self.run_state(
  790. "file.managed", name=name, source=source, saltenv=saltenv, keep_source=False
  791. )
  792. ret = ret[next(iter(ret))]
  793. assert ret["result"] is True
  794. # Now make sure that the file is not cached
  795. result = self.run_function("cp.is_cached", [source, saltenv])
  796. assert result == "", "File is still cached at {0}".format(result)
  797. @with_tempfile(create=False)
  798. @with_tempfile(create=False)
  799. @pytest.mark.slow_test(seconds=60) # Test takes >30 and <=60 seconds
  800. def test_file_managed_onchanges(self, file1, file2):
  801. """
  802. Test file.managed state with onchanges
  803. """
  804. pillar = {
  805. "file1": file1,
  806. "file2": file2,
  807. "source": "salt://testfile",
  808. "req": "onchanges",
  809. }
  810. # Lay down the file used in the below SLS to ensure that when it is
  811. # run, there are no changes.
  812. self.run_state("file.managed", name=pillar["file2"], source=pillar["source"])
  813. ret = self.repack_state_returns(
  814. self.run_function(
  815. "state.apply", mods="onchanges_prereq", pillar=pillar, test=True,
  816. )
  817. )
  818. # The file states should both exit with None
  819. assert ret["one"]["result"] is None, ret["one"]["result"]
  820. assert ret["three"]["result"] is True, ret["three"]["result"]
  821. # The first file state should have changes, since a new file was
  822. # created. The other one should not, since we already created that file
  823. # before applying the SLS file.
  824. assert ret["one"]["changes"]
  825. assert not ret["three"]["changes"], ret["three"]["changes"]
  826. # The state watching 'one' should have been run due to changes
  827. assert ret["two"]["comment"] == "Success!", ret["two"]["comment"]
  828. # The state watching 'three' should not have been run
  829. assert (
  830. ret["four"]["comment"]
  831. == "State was not run because none of the onchanges reqs changed"
  832. ), ret["four"]["comment"]
  833. @with_tempfile(create=False)
  834. @with_tempfile(create=False)
  835. @pytest.mark.slow_test(seconds=60) # Test takes >30 and <=60 seconds
  836. def test_file_managed_prereq(self, file1, file2):
  837. """
  838. Test file.managed state with prereq
  839. """
  840. pillar = {
  841. "file1": file1,
  842. "file2": file2,
  843. "source": "salt://testfile",
  844. "req": "prereq",
  845. }
  846. # Lay down the file used in the below SLS to ensure that when it is
  847. # run, there are no changes.
  848. self.run_state("file.managed", name=pillar["file2"], source=pillar["source"])
  849. ret = self.repack_state_returns(
  850. self.run_function(
  851. "state.apply", mods="onchanges_prereq", pillar=pillar, test=True,
  852. )
  853. )
  854. # The file states should both exit with None
  855. assert ret["one"]["result"] is None, ret["one"]["result"]
  856. assert ret["three"]["result"] is True, ret["three"]["result"]
  857. # The first file state should have changes, since a new file was
  858. # created. The other one should not, since we already created that file
  859. # before applying the SLS file.
  860. assert ret["one"]["changes"]
  861. assert not ret["three"]["changes"], ret["three"]["changes"]
  862. # The state watching 'one' should have been run due to changes
  863. assert ret["two"]["comment"] == "Success!", ret["two"]["comment"]
  864. # The state watching 'three' should not have been run
  865. assert ret["four"]["comment"] == "No changes detected", ret["four"]["comment"]
  866. @pytest.mark.slow_test(seconds=30) # Test takes >10 and <=30 seconds
  867. def test_directory(self):
  868. """
  869. file.directory
  870. """
  871. name = os.path.join(RUNTIME_VARS.TMP, "a_new_dir")
  872. ret = self.run_state("file.directory", name=name)
  873. self.assertSaltTrueReturn(ret)
  874. self.assertTrue(os.path.isdir(name))
  875. @pytest.mark.slow_test(seconds=60) # Test takes >30 and <=60 seconds
  876. def test_directory_symlink_dry_run(self):
  877. """
  878. Ensure that symlinks are followed when file.directory is run with
  879. test=True
  880. """
  881. try:
  882. tmp_dir = os.path.join(RUNTIME_VARS.TMP, "pgdata")
  883. sym_dir = os.path.join(RUNTIME_VARS.TMP, "pg_data")
  884. os.mkdir(tmp_dir, 0o700)
  885. self.run_function("file.symlink", [tmp_dir, sym_dir])
  886. if IS_WINDOWS:
  887. ret = self.run_state(
  888. "file.directory",
  889. test=True,
  890. name=sym_dir,
  891. follow_symlinks=True,
  892. win_owner="Administrators",
  893. )
  894. else:
  895. ret = self.run_state(
  896. "file.directory",
  897. test=True,
  898. name=sym_dir,
  899. follow_symlinks=True,
  900. mode=700,
  901. )
  902. self.assertSaltTrueReturn(ret)
  903. finally:
  904. if os.path.isdir(tmp_dir):
  905. self.run_function("file.remove", [tmp_dir])
  906. if os.path.islink(sym_dir):
  907. self.run_function("file.remove", [sym_dir])
  908. @pytest.mark.skip_if_not_root
  909. @skipIf(IS_WINDOWS, "Mode not available in Windows")
  910. @pytest.mark.slow_test(seconds=5) # Test takes >1 and <=5 seconds
  911. def test_directory_max_depth(self):
  912. """
  913. file.directory
  914. Test the max_depth option by iteratively increasing the depth and
  915. checking that no changes deeper than max_depth have been attempted
  916. """
  917. def _get_oct_mode(name):
  918. """
  919. Return a string octal representation of the permissions for name
  920. """
  921. return salt.utils.files.normalize_mode(oct(os.stat(name).st_mode & 0o777))
  922. top = os.path.join(RUNTIME_VARS.TMP, "top_dir")
  923. sub = os.path.join(top, "sub_dir")
  924. subsub = os.path.join(sub, "sub_sub_dir")
  925. dirs = [top, sub, subsub]
  926. initial_mode = "0111"
  927. changed_mode = "0555"
  928. initial_modes = {
  929. 0: {sub: "0755", subsub: "0111"},
  930. 1: {sub: "0111", subsub: "0111"},
  931. 2: {sub: "0111", subsub: "0111"},
  932. }
  933. if not os.path.isdir(subsub):
  934. os.makedirs(subsub, int(initial_mode, 8))
  935. try:
  936. for depth in range(0, 3):
  937. ret = self.run_state(
  938. "file.directory",
  939. name=top,
  940. max_depth=depth,
  941. dir_mode=changed_mode,
  942. recurse=["mode"],
  943. )
  944. self.assertSaltTrueReturn(ret)
  945. for changed_dir in dirs[0 : depth + 1]:
  946. self.assertEqual(changed_mode, _get_oct_mode(changed_dir))
  947. for untouched_dir in dirs[depth + 1 :]:
  948. # Beginning in Python 3.7, os.makedirs no longer sets
  949. # the mode of intermediate directories to the mode that
  950. # is passed.
  951. if sys.version_info >= (3, 7):
  952. _mode = initial_modes[depth][untouched_dir]
  953. self.assertEqual(_mode, _get_oct_mode(untouched_dir))
  954. else:
  955. self.assertEqual(initial_mode, _get_oct_mode(untouched_dir))
  956. finally:
  957. shutil.rmtree(top)
  958. @pytest.mark.slow_test(seconds=30) # Test takes >10 and <=30 seconds
  959. def test_test_directory(self):
  960. """
  961. file.directory
  962. """
  963. name = os.path.join(RUNTIME_VARS.TMP, "a_not_dir")
  964. ret = self.run_state("file.directory", test=True, name=name)
  965. self.assertSaltNoneReturn(ret)
  966. self.assertFalse(os.path.isdir(name))
  967. @with_tempdir()
  968. @pytest.mark.slow_test(seconds=30) # Test takes >10 and <=30 seconds
  969. def test_directory_clean(self, base_dir):
  970. """
  971. file.directory with clean=True
  972. """
  973. name = os.path.join(base_dir, "directory_clean_dir")
  974. os.mkdir(name)
  975. strayfile = os.path.join(name, "strayfile")
  976. with salt.utils.files.fopen(strayfile, "w"):
  977. pass
  978. straydir = os.path.join(name, "straydir")
  979. if not os.path.isdir(straydir):
  980. os.makedirs(straydir)
  981. with salt.utils.files.fopen(os.path.join(straydir, "strayfile2"), "w"):
  982. pass
  983. ret = self.run_state("file.directory", name=name, clean=True)
  984. self.assertSaltTrueReturn(ret)
  985. self.assertFalse(os.path.exists(strayfile))
  986. self.assertFalse(os.path.exists(straydir))
  987. self.assertTrue(os.path.isdir(name))
  988. @pytest.mark.slow_test(seconds=60) # Test takes >30 and <=60 seconds
  989. def test_directory_is_idempotent(self):
  990. """
  991. Ensure the file.directory state produces no changes when rerun.
  992. """
  993. name = os.path.join(RUNTIME_VARS.TMP, "a_dir_twice")
  994. if IS_WINDOWS:
  995. username = os.environ.get("USERNAME", "Administrators")
  996. domain = os.environ.get("USERDOMAIN", "")
  997. fullname = "{0}\\{1}".format(domain, username)
  998. ret = self.run_state("file.directory", name=name, win_owner=fullname)
  999. else:
  1000. ret = self.run_state("file.directory", name=name)
  1001. self.assertSaltTrueReturn(ret)
  1002. if IS_WINDOWS:
  1003. ret = self.run_state("file.directory", name=name, win_owner=username)
  1004. else:
  1005. ret = self.run_state("file.directory", name=name)
  1006. self.assertSaltTrueReturn(ret)
  1007. self.assertSaltStateChangesEqual(ret, {})
  1008. @with_tempdir()
  1009. @pytest.mark.slow_test(seconds=30) # Test takes >10 and <=30 seconds
  1010. def test_directory_clean_exclude(self, base_dir):
  1011. """
  1012. file.directory with clean=True and exclude_pat set
  1013. """
  1014. name = os.path.join(base_dir, "directory_clean_dir")
  1015. if not os.path.isdir(name):
  1016. os.makedirs(name)
  1017. strayfile = os.path.join(name, "strayfile")
  1018. with salt.utils.files.fopen(strayfile, "w"):
  1019. pass
  1020. straydir = os.path.join(name, "straydir")
  1021. if not os.path.isdir(straydir):
  1022. os.makedirs(straydir)
  1023. strayfile2 = os.path.join(straydir, "strayfile2")
  1024. with salt.utils.files.fopen(strayfile2, "w"):
  1025. pass
  1026. keepfile = os.path.join(straydir, "keepfile")
  1027. with salt.utils.files.fopen(keepfile, "w"):
  1028. pass
  1029. exclude_pat = "E@^straydir(|/keepfile)$"
  1030. if IS_WINDOWS:
  1031. exclude_pat = "E@^straydir(|\\\\keepfile)$"
  1032. ret = self.run_state(
  1033. "file.directory", name=name, clean=True, exclude_pat=exclude_pat
  1034. )
  1035. self.assertSaltTrueReturn(ret)
  1036. self.assertFalse(os.path.exists(strayfile))
  1037. self.assertFalse(os.path.exists(strayfile2))
  1038. self.assertTrue(os.path.exists(keepfile))
  1039. @skipIf(IS_WINDOWS, "Skip on windows")
  1040. @with_tempdir()
  1041. @pytest.mark.slow_test(seconds=5) # Test takes >1 and <=5 seconds
  1042. def test_test_directory_clean_exclude(self, base_dir):
  1043. """
  1044. file.directory with test=True, clean=True and exclude_pat set
  1045. Skipped on windows because clean and exclude_pat not supported by
  1046. salt.sates.file._check_directory_win
  1047. """
  1048. name = os.path.join(base_dir, "directory_clean_dir")
  1049. os.mkdir(name)
  1050. strayfile = os.path.join(name, "strayfile")
  1051. with salt.utils.files.fopen(strayfile, "w"):
  1052. pass
  1053. straydir = os.path.join(name, "straydir")
  1054. if not os.path.isdir(straydir):
  1055. os.makedirs(straydir)
  1056. strayfile2 = os.path.join(straydir, "strayfile2")
  1057. with salt.utils.files.fopen(strayfile2, "w"):
  1058. pass
  1059. keepfile = os.path.join(straydir, "keepfile")
  1060. with salt.utils.files.fopen(keepfile, "w"):
  1061. pass
  1062. exclude_pat = "E@^straydir(|/keepfile)$"
  1063. if IS_WINDOWS:
  1064. exclude_pat = "E@^straydir(|\\\\keepfile)$"
  1065. ret = self.run_state(
  1066. "file.directory", test=True, name=name, clean=True, exclude_pat=exclude_pat
  1067. )
  1068. comment = next(six.itervalues(ret))["comment"]
  1069. self.assertSaltNoneReturn(ret)
  1070. self.assertTrue(os.path.exists(strayfile))
  1071. self.assertTrue(os.path.exists(strayfile2))
  1072. self.assertTrue(os.path.exists(keepfile))
  1073. self.assertIn(strayfile, comment)
  1074. self.assertIn(strayfile2, comment)
  1075. self.assertNotIn(keepfile, comment)
  1076. @with_tempdir()
  1077. @pytest.mark.slow_test(seconds=30) # Test takes >10 and <=30 seconds
  1078. def test_directory_clean_require_in(self, name):
  1079. """
  1080. file.directory test with clean=True and require_in file
  1081. """
  1082. state_name = "file-FileTest-test_directory_clean_require_in"
  1083. state_filename = state_name + ".sls"
  1084. state_file = os.path.join(RUNTIME_VARS.BASE_FILES, state_filename)
  1085. wrong_file = os.path.join(name, "wrong")
  1086. with salt.utils.files.fopen(wrong_file, "w") as fp:
  1087. fp.write("foo")
  1088. good_file = os.path.join(name, "bar")
  1089. with salt.utils.files.fopen(state_file, "w") as fp:
  1090. self.addCleanup(lambda: os.remove(state_file))
  1091. fp.write(
  1092. textwrap.dedent(
  1093. """\
  1094. some_dir:
  1095. file.directory:
  1096. - name: {name}
  1097. - clean: true
  1098. {good_file}:
  1099. file.managed:
  1100. - require_in:
  1101. - file: some_dir
  1102. """.format(
  1103. name=name, good_file=good_file
  1104. )
  1105. )
  1106. )
  1107. ret = self.run_function("state.sls", [state_name])
  1108. self.assertTrue(os.path.exists(good_file))
  1109. self.assertFalse(os.path.exists(wrong_file))
  1110. @with_tempdir()
  1111. @pytest.mark.slow_test(seconds=30) # Test takes >10 and <=30 seconds
  1112. def test_directory_clean_require_in_with_id(self, name):
  1113. """
  1114. file.directory test with clean=True and require_in file with an ID
  1115. different from the file name
  1116. """
  1117. state_name = "file-FileTest-test_directory_clean_require_in_with_id"
  1118. state_filename = state_name + ".sls"
  1119. state_file = os.path.join(RUNTIME_VARS.BASE_FILES, state_filename)
  1120. wrong_file = os.path.join(name, "wrong")
  1121. with salt.utils.files.fopen(wrong_file, "w") as fp:
  1122. fp.write("foo")
  1123. good_file = os.path.join(name, "bar")
  1124. with salt.utils.files.fopen(state_file, "w") as fp:
  1125. self.addCleanup(lambda: os.remove(state_file))
  1126. fp.write(
  1127. textwrap.dedent(
  1128. """\
  1129. some_dir:
  1130. file.directory:
  1131. - name: {name}
  1132. - clean: true
  1133. some_file:
  1134. file.managed:
  1135. - name: {good_file}
  1136. - require_in:
  1137. - file: some_dir
  1138. """.format(
  1139. name=name, good_file=good_file
  1140. )
  1141. )
  1142. )
  1143. ret = self.run_function("state.sls", [state_name])
  1144. self.assertTrue(os.path.exists(good_file))
  1145. self.assertFalse(os.path.exists(wrong_file))
  1146. @skipIf(
  1147. salt.utils.platform.is_darwin(),
  1148. "WAR ROOM TEMPORARY SKIP, Test is flaky on macosx",
  1149. )
  1150. @with_tempdir()
  1151. @pytest.mark.slow_test(seconds=30) # Test takes >10 and <=30 seconds
  1152. def test_directory_clean_require_with_name(self, name):
  1153. """
  1154. file.directory test with clean=True and require with a file state
  1155. relatively to the state's name, not its ID.
  1156. """
  1157. state_name = "file-FileTest-test_directory_clean_require_in_with_id"
  1158. state_filename = state_name + ".sls"
  1159. state_file = os.path.join(RUNTIME_VARS.BASE_FILES, state_filename)
  1160. wrong_file = os.path.join(name, "wrong")
  1161. with salt.utils.files.fopen(wrong_file, "w") as fp:
  1162. fp.write("foo")
  1163. good_file = os.path.join(name, "bar")
  1164. with salt.utils.files.fopen(state_file, "w") as fp:
  1165. self.addCleanup(lambda: os.remove(state_file))
  1166. fp.write(
  1167. textwrap.dedent(
  1168. """\
  1169. some_dir:
  1170. file.directory:
  1171. - name: {name}
  1172. - clean: true
  1173. - require:
  1174. # This requirement refers to the name of the following
  1175. # state, not its ID.
  1176. - file: {good_file}
  1177. some_file:
  1178. file.managed:
  1179. - name: {good_file}
  1180. """.format(
  1181. name=name, good_file=good_file
  1182. )
  1183. )
  1184. )
  1185. ret = self.run_function("state.sls", [state_name])
  1186. self.assertTrue(os.path.exists(good_file))
  1187. self.assertFalse(os.path.exists(wrong_file))
  1188. @pytest.mark.slow_test(seconds=60) # Test takes >30 and <=60 seconds
  1189. def test_directory_broken_symlink(self):
  1190. """
  1191. Ensure that file.directory works even if a directory
  1192. contains broken symbolic link
  1193. """
  1194. try:
  1195. tmp_dir = os.path.join(RUNTIME_VARS.TMP, "foo")
  1196. null_file = "{0}/null".format(tmp_dir)
  1197. broken_link = "{0}/broken".format(tmp_dir)
  1198. os.mkdir(tmp_dir, 0o700)
  1199. self.run_function("file.symlink", [null_file, broken_link])
  1200. if IS_WINDOWS:
  1201. ret = self.run_state(
  1202. "file.directory",
  1203. name=tmp_dir,
  1204. recurse=["mode"],
  1205. follow_symlinks=True,
  1206. win_owner="Administrators",
  1207. )
  1208. else:
  1209. ret = self.run_state(
  1210. "file.directory",
  1211. name=tmp_dir,
  1212. recurse=["mode"],
  1213. file_mode=644,
  1214. dir_mode=755,
  1215. )
  1216. self.assertSaltTrueReturn(ret)
  1217. finally:
  1218. if os.path.isdir(tmp_dir):
  1219. self.run_function("file.remove", [tmp_dir])
  1220. @with_tempdir(create=False)
  1221. @pytest.mark.slow_test(seconds=30) # Test takes >10 and <=30 seconds
  1222. def test_recurse(self, name):
  1223. """
  1224. file.recurse
  1225. """
  1226. ret = self.run_state("file.recurse", name=name, source="salt://grail")
  1227. self.assertSaltTrueReturn(ret)
  1228. self.assertTrue(os.path.isfile(os.path.join(name, "36", "scene")))
  1229. @with_tempdir(create=False)
  1230. @with_tempdir(create=False)
  1231. @pytest.mark.slow_test(seconds=60) # Test takes >30 and <=60 seconds
  1232. def test_recurse_specific_env(self, dir1, dir2):
  1233. """
  1234. file.recurse passing __env__
  1235. """
  1236. ret = self.run_state(
  1237. "file.recurse", name=dir1, source="salt://holy", __env__="prod"
  1238. )
  1239. self.assertSaltTrueReturn(ret)
  1240. self.assertTrue(os.path.isfile(os.path.join(dir1, "32", "scene")))
  1241. ret = self.run_state(
  1242. "file.recurse", name=dir2, source="salt://holy", saltenv="prod"
  1243. )
  1244. self.assertSaltTrueReturn(ret)
  1245. self.assertTrue(os.path.isfile(os.path.join(dir2, "32", "scene")))
  1246. @with_tempdir(create=False)
  1247. @with_tempdir(create=False)
  1248. @pytest.mark.slow_test(seconds=60) # Test takes >30 and <=60 seconds
  1249. def test_recurse_specific_env_in_url(self, dir1, dir2):
  1250. """
  1251. file.recurse passing __env__
  1252. """
  1253. ret = self.run_state(
  1254. "file.recurse", name=dir1, source="salt://holy?saltenv=prod"
  1255. )
  1256. self.assertSaltTrueReturn(ret)
  1257. self.assertTrue(os.path.isfile(os.path.join(dir1, "32", "scene")))
  1258. ret = self.run_state(
  1259. "file.recurse", name=dir2, source="salt://holy?saltenv=prod"
  1260. )
  1261. self.assertSaltTrueReturn(ret)
  1262. self.assertTrue(os.path.isfile(os.path.join(dir2, "32", "scene")))
  1263. @with_tempdir(create=False)
  1264. @pytest.mark.slow_test(seconds=30) # Test takes >10 and <=30 seconds
  1265. def test_test_recurse(self, name):
  1266. """
  1267. file.recurse test interface
  1268. """
  1269. ret = self.run_state(
  1270. "file.recurse", test=True, name=name, source="salt://grail",
  1271. )
  1272. self.assertSaltNoneReturn(ret)
  1273. self.assertFalse(os.path.isfile(os.path.join(name, "36", "scene")))
  1274. self.assertFalse(os.path.exists(name))
  1275. @with_tempdir(create=False)
  1276. @with_tempdir(create=False)
  1277. @pytest.mark.slow_test(seconds=60) # Test takes >30 and <=60 seconds
  1278. def test_test_recurse_specific_env(self, dir1, dir2):
  1279. """
  1280. file.recurse test interface
  1281. """
  1282. ret = self.run_state(
  1283. "file.recurse", test=True, name=dir1, source="salt://holy", __env__="prod"
  1284. )
  1285. self.assertSaltNoneReturn(ret)
  1286. self.assertFalse(os.path.isfile(os.path.join(dir1, "32", "scene")))
  1287. self.assertFalse(os.path.exists(dir1))
  1288. ret = self.run_state(
  1289. "file.recurse", test=True, name=dir2, source="salt://holy", saltenv="prod"
  1290. )
  1291. self.assertSaltNoneReturn(ret)
  1292. self.assertFalse(os.path.isfile(os.path.join(dir2, "32", "scene")))
  1293. self.assertFalse(os.path.exists(dir2))
  1294. @with_tempdir(create=False)
  1295. @pytest.mark.slow_test(seconds=30) # Test takes >10 and <=30 seconds
  1296. def test_recurse_template(self, name):
  1297. """
  1298. file.recurse with jinja template enabled
  1299. """
  1300. _ts = "TEMPLATE TEST STRING"
  1301. ret = self.run_state(
  1302. "file.recurse",
  1303. name=name,
  1304. source="salt://grail",
  1305. template="jinja",
  1306. defaults={"spam": _ts},
  1307. )
  1308. self.assertSaltTrueReturn(ret)
  1309. with salt.utils.files.fopen(os.path.join(name, "scene33"), "r") as fp_:
  1310. contents = fp_.read()
  1311. self.assertIn(_ts, contents)
  1312. @with_tempdir()
  1313. @pytest.mark.slow_test(seconds=30) # Test takes >10 and <=30 seconds
  1314. def test_recurse_clean(self, name):
  1315. """
  1316. file.recurse with clean=True
  1317. """
  1318. strayfile = os.path.join(name, "strayfile")
  1319. with salt.utils.files.fopen(strayfile, "w"):
  1320. pass
  1321. # Corner cases: replacing file with a directory and vice versa
  1322. with salt.utils.files.fopen(os.path.join(name, "36"), "w"):
  1323. pass
  1324. os.makedirs(os.path.join(name, "scene33"))
  1325. ret = self.run_state(
  1326. "file.recurse", name=name, source="salt://grail", clean=True
  1327. )
  1328. self.assertSaltTrueReturn(ret)
  1329. self.assertFalse(os.path.exists(strayfile))
  1330. self.assertTrue(os.path.isfile(os.path.join(name, "36", "scene")))
  1331. self.assertTrue(os.path.isfile(os.path.join(name, "scene33")))
  1332. @with_tempdir()
  1333. @pytest.mark.slow_test(seconds=30) # Test takes >10 and <=30 seconds
  1334. def test_recurse_clean_specific_env(self, name):
  1335. """
  1336. file.recurse with clean=True and __env__=prod
  1337. """
  1338. strayfile = os.path.join(name, "strayfile")
  1339. with salt.utils.files.fopen(strayfile, "w"):
  1340. pass
  1341. # Corner cases: replacing file with a directory and vice versa
  1342. with salt.utils.files.fopen(os.path.join(name, "32"), "w"):
  1343. pass
  1344. os.makedirs(os.path.join(name, "scene34"))
  1345. ret = self.run_state(
  1346. "file.recurse", name=name, source="salt://holy", clean=True, __env__="prod"
  1347. )
  1348. self.assertSaltTrueReturn(ret)
  1349. self.assertFalse(os.path.exists(strayfile))
  1350. self.assertTrue(os.path.isfile(os.path.join(name, "32", "scene")))
  1351. self.assertTrue(os.path.isfile(os.path.join(name, "scene34")))
  1352. @skipIf(IS_WINDOWS, "Skip on windows")
  1353. @with_tempdir()
  1354. @pytest.mark.slow_test(seconds=5) # Test takes >1 and <=5 seconds
  1355. def test_recurse_issue_34945(self, base_dir):
  1356. """
  1357. This tests the case where the source dir for the file.recurse state
  1358. does not contain any files (only subdirectories), and the dir_mode is
  1359. being managed. For a long time, this corner case resulted in the top
  1360. level of the destination directory being created with the wrong initial
  1361. permissions, a problem that would be corrected later on in the
  1362. file.recurse state via running state.directory. However, the
  1363. file.directory state only gets called when there are files to be
  1364. managed in that directory, and when the source directory contains only
  1365. subdirectories, the incorrectly-set initial perms would not be
  1366. repaired.
  1367. This was fixed in https://github.com/saltstack/salt/pull/35309
  1368. Skipped on windows because dir_mode is not supported.
  1369. """
  1370. dir_mode = "2775"
  1371. issue_dir = "issue-34945"
  1372. name = os.path.join(base_dir, issue_dir)
  1373. ret = self.run_state(
  1374. "file.recurse", name=name, source="salt://" + issue_dir, dir_mode=dir_mode
  1375. )
  1376. self.assertSaltTrueReturn(ret)
  1377. actual_dir_mode = oct(stat.S_IMODE(os.stat(name).st_mode))[-4:]
  1378. self.assertEqual(dir_mode, actual_dir_mode)
  1379. @with_tempdir(create=False)
  1380. @pytest.mark.slow_test(seconds=30) # Test takes >10 and <=30 seconds
  1381. def test_recurse_issue_40578(self, name):
  1382. """
  1383. This ensures that the state doesn't raise an exception when it
  1384. encounters a file with a unicode filename in the process of invoking
  1385. file.source_list.
  1386. """
  1387. ret = self.run_state("file.recurse", name=name, source="salt://соль")
  1388. self.assertSaltTrueReturn(ret)
  1389. if six.PY2 and IS_WINDOWS:
  1390. # Providing unicode to os.listdir so that we avoid having listdir
  1391. # try to decode the filenames using the systemencoding on windows
  1392. # python 2.
  1393. files = os.listdir(name.decode("utf-8"))
  1394. else:
  1395. files = salt.utils.data.decode(os.listdir(name), normalize=True)
  1396. self.assertEqual(
  1397. sorted(files), sorted(["foo.txt", "спам.txt", "яйца.txt"]),
  1398. )
  1399. @with_tempfile()
  1400. @pytest.mark.slow_test(seconds=30) # Test takes >10 and <=30 seconds
  1401. def test_replace(self, name):
  1402. """
  1403. file.replace
  1404. """
  1405. with salt.utils.files.fopen(name, "w+") as fp_:
  1406. fp_.write("change_me")
  1407. ret = self.run_state(
  1408. "file.replace", name=name, pattern="change", repl="salt", backup=False
  1409. )
  1410. with salt.utils.files.fopen(name, "r") as fp_:
  1411. self.assertIn("salt", fp_.read())
  1412. self.assertSaltTrueReturn(ret)
  1413. @with_tempdir()
  1414. @pytest.mark.slow_test(seconds=60) # Test takes >30 and <=60 seconds
  1415. def test_replace_issue_18612(self, base_dir):
  1416. """
  1417. Test the (mis-)behaviour of file.replace as described in #18612:
  1418. Using 'prepend_if_not_found' or 'append_if_not_found' resulted in
  1419. an infinitely growing file as 'file.replace' didn't check beforehand
  1420. whether the changes had already been done to the file
  1421. # Case description:
  1422. The tested file contains one commented line
  1423. The commented line should be uncommented in the end, nothing else should change
  1424. """
  1425. test_name = "test_replace_issue_18612"
  1426. path_test = os.path.join(base_dir, test_name)
  1427. with salt.utils.files.fopen(path_test, "w+") as fp_test_:
  1428. fp_test_.write("# en_US.UTF-8")
  1429. ret = []
  1430. for x in range(0, 3):
  1431. ret.append(
  1432. self.run_state(
  1433. "file.replace",
  1434. name=path_test,
  1435. pattern="^# en_US.UTF-8$",
  1436. repl="en_US.UTF-8",
  1437. append_if_not_found=True,
  1438. )
  1439. )
  1440. # ensure, the number of lines didn't change, even after invoking 'file.replace' 3 times
  1441. with salt.utils.files.fopen(path_test, "r") as fp_test_:
  1442. self.assertTrue((sum(1 for _ in fp_test_) == 1))
  1443. # ensure, the replacement succeeded
  1444. with salt.utils.files.fopen(path_test, "r") as fp_test_:
  1445. self.assertTrue(fp_test_.read().startswith("en_US.UTF-8"))
  1446. # ensure, all runs of 'file.replace' reported success
  1447. for item in ret:
  1448. self.assertSaltTrueReturn(item)
  1449. @with_tempdir()
  1450. @pytest.mark.slow_test(seconds=60) # Test takes >30 and <=60 seconds
  1451. def test_replace_issue_18612_prepend(self, base_dir):
  1452. """
  1453. Test the (mis-)behaviour of file.replace as described in #18612:
  1454. Using 'prepend_if_not_found' or 'append_if_not_found' resulted in
  1455. an infinitely growing file as 'file.replace' didn't check beforehand
  1456. whether the changes had already been done to the file
  1457. # Case description:
  1458. The tested multifile contains multiple lines not matching the pattern or replacement in any way
  1459. The replacement pattern should be prepended to the file
  1460. """
  1461. test_name = "test_replace_issue_18612_prepend"
  1462. path_in = os.path.join(
  1463. RUNTIME_VARS.FILES, "file.replace", "{0}.in".format(test_name)
  1464. )
  1465. path_out = os.path.join(
  1466. RUNTIME_VARS.FILES, "file.replace", "{0}.out".format(test_name)
  1467. )
  1468. path_test = os.path.join(base_dir, test_name)
  1469. # create test file based on initial template
  1470. shutil.copyfile(path_in, path_test)
  1471. ret = []
  1472. for x in range(0, 3):
  1473. ret.append(
  1474. self.run_state(
  1475. "file.replace",
  1476. name=path_test,
  1477. pattern="^# en_US.UTF-8$",
  1478. repl="en_US.UTF-8",
  1479. prepend_if_not_found=True,
  1480. )
  1481. )
  1482. # ensure, the resulting file contains the expected lines
  1483. self.assertTrue(filecmp.cmp(path_test, path_out))
  1484. # ensure the initial file was properly backed up
  1485. self.assertTrue(filecmp.cmp(path_test + ".bak", path_in))
  1486. # ensure, all runs of 'file.replace' reported success
  1487. for item in ret:
  1488. self.assertSaltTrueReturn(item)
  1489. @with_tempdir()
  1490. @pytest.mark.slow_test(seconds=60) # Test takes >30 and <=60 seconds
  1491. def test_replace_issue_18612_append(self, base_dir):
  1492. """
  1493. Test the (mis-)behaviour of file.replace as described in #18612:
  1494. Using 'prepend_if_not_found' or 'append_if_not_found' resulted in
  1495. an infinitely growing file as 'file.replace' didn't check beforehand
  1496. whether the changes had already been done to the file
  1497. # Case description:
  1498. The tested multifile contains multiple lines not matching the pattern or replacement in any way
  1499. The replacement pattern should be appended to the file
  1500. """
  1501. test_name = "test_replace_issue_18612_append"
  1502. path_in = os.path.join(
  1503. RUNTIME_VARS.FILES, "file.replace", "{0}.in".format(test_name)
  1504. )
  1505. path_out = os.path.join(
  1506. RUNTIME_VARS.FILES, "file.replace", "{0}.out".format(test_name)
  1507. )
  1508. path_test = os.path.join(base_dir, test_name)
  1509. # create test file based on initial template
  1510. shutil.copyfile(path_in, path_test)
  1511. ret = []
  1512. for x in range(0, 3):
  1513. ret.append(
  1514. self.run_state(
  1515. "file.replace",
  1516. name=path_test,
  1517. pattern="^# en_US.UTF-8$",
  1518. repl="en_US.UTF-8",
  1519. append_if_not_found=True,
  1520. )
  1521. )
  1522. # ensure, the resulting file contains the expected lines
  1523. self.assertTrue(filecmp.cmp(path_test, path_out))
  1524. # ensure the initial file was properly backed up
  1525. self.assertTrue(filecmp.cmp(path_test + ".bak", path_in))
  1526. # ensure, all runs of 'file.replace' reported success
  1527. for item in ret:
  1528. self.assertSaltTrueReturn(item)
  1529. @with_tempdir()
  1530. @pytest.mark.slow_test(seconds=60) # Test takes >30 and <=60 seconds
  1531. def test_replace_issue_18612_append_not_found_content(self, base_dir):
  1532. """
  1533. Test the (mis-)behaviour of file.replace as described in #18612:
  1534. Using 'prepend_if_not_found' or 'append_if_not_found' resulted in
  1535. an infinitely growing file as 'file.replace' didn't check beforehand
  1536. whether the changes had already been done to the file
  1537. # Case description:
  1538. The tested multifile contains multiple lines not matching the pattern or replacement in any way
  1539. The 'not_found_content' value should be appended to the file
  1540. """
  1541. test_name = "test_replace_issue_18612_append_not_found_content"
  1542. path_in = os.path.join(
  1543. RUNTIME_VARS.FILES, "file.replace", "{0}.in".format(test_name)
  1544. )
  1545. path_out = os.path.join(
  1546. RUNTIME_VARS.FILES, "file.replace", "{0}.out".format(test_name)
  1547. )
  1548. path_test = os.path.join(base_dir, test_name)
  1549. # create test file based on initial template
  1550. shutil.copyfile(path_in, path_test)
  1551. ret = []
  1552. for x in range(0, 3):
  1553. ret.append(
  1554. self.run_state(
  1555. "file.replace",
  1556. name=path_test,
  1557. pattern="^# en_US.UTF-8$",
  1558. repl="en_US.UTF-8",
  1559. append_if_not_found=True,
  1560. not_found_content="THIS LINE WASN'T FOUND! SO WE'RE APPENDING IT HERE!",
  1561. )
  1562. )
  1563. # ensure, the resulting file contains the expected lines
  1564. self.assertTrue(filecmp.cmp(path_test, path_out))
  1565. # ensure the initial file was properly backed up
  1566. self.assertTrue(filecmp.cmp(path_test + ".bak", path_in))
  1567. # ensure, all runs of 'file.replace' reported success
  1568. for item in ret:
  1569. self.assertSaltTrueReturn(item)
  1570. @with_tempdir()
  1571. @pytest.mark.slow_test(seconds=60) # Test takes >30 and <=60 seconds
  1572. def test_replace_issue_18612_change_mid_line_with_comment(self, base_dir):
  1573. """
  1574. Test the (mis-)behaviour of file.replace as described in #18612:
  1575. Using 'prepend_if_not_found' or 'append_if_not_found' resulted in
  1576. an infinitely growing file as 'file.replace' didn't check beforehand
  1577. whether the changes had already been done to the file
  1578. # Case description:
  1579. The tested file contains 5 key=value pairs
  1580. The commented key=value pair #foo=bar should be changed to foo=salt
  1581. The comment char (#) in front of foo=bar should be removed
  1582. """
  1583. test_name = "test_replace_issue_18612_change_mid_line_with_comment"
  1584. path_in = os.path.join(
  1585. RUNTIME_VARS.FILES, "file.replace", "{0}.in".format(test_name)
  1586. )
  1587. path_out = os.path.join(
  1588. RUNTIME_VARS.FILES, "file.replace", "{0}.out".format(test_name)
  1589. )
  1590. path_test = os.path.join(base_dir, test_name)
  1591. # create test file based on initial template
  1592. shutil.copyfile(path_in, path_test)
  1593. ret = []
  1594. for x in range(0, 3):
  1595. ret.append(
  1596. self.run_state(
  1597. "file.replace",
  1598. name=path_test,
  1599. pattern="^#foo=bar($|(?=\r\n))",
  1600. repl="foo=salt",
  1601. append_if_not_found=True,
  1602. )
  1603. )
  1604. # ensure, the resulting file contains the expected lines
  1605. self.assertTrue(filecmp.cmp(path_test, path_out))
  1606. # ensure the initial file was properly backed up
  1607. self.assertTrue(filecmp.cmp(path_test + ".bak", path_in))
  1608. # ensure, all 'file.replace' runs reported success
  1609. for item in ret:
  1610. self.assertSaltTrueReturn(item)
  1611. @with_tempdir()
  1612. @pytest.mark.slow_test(seconds=30) # Test takes >10 and <=30 seconds
  1613. def test_replace_issue_18841_no_changes(self, base_dir):
  1614. """
  1615. Test the (mis-)behaviour of file.replace as described in #18841:
  1616. Using file.replace in a way which shouldn't modify the file at all
  1617. results in changed mtime of the original file and a backup file being created.
  1618. # Case description
  1619. The tested file contains multiple lines
  1620. The tested file contains a line already matching the replacement (no change needed)
  1621. The tested file's content shouldn't change at all
  1622. The tested file's mtime shouldn't change at all
  1623. No backup file should be created
  1624. """
  1625. test_name = "test_replace_issue_18841_no_changes"
  1626. path_in = os.path.join(
  1627. RUNTIME_VARS.FILES, "file.replace", "{0}.in".format(test_name)
  1628. )
  1629. path_test = os.path.join(base_dir, test_name)
  1630. # create test file based on initial template
  1631. shutil.copyfile(path_in, path_test)
  1632. # get (m|a)time of file
  1633. fstats_orig = os.stat(path_test)
  1634. # define how far we predate the file
  1635. age = 5 * 24 * 60 * 60
  1636. # set (m|a)time of file 5 days into the past
  1637. os.utime(path_test, (fstats_orig.st_mtime - age, fstats_orig.st_atime - age))
  1638. ret = self.run_state(
  1639. "file.replace",
  1640. name=path_test,
  1641. pattern="^hello world$",
  1642. repl="goodbye world",
  1643. show_changes=True,
  1644. flags=["IGNORECASE"],
  1645. backup=False,
  1646. )
  1647. # get (m|a)time of file
  1648. fstats_post = os.stat(path_test)
  1649. # ensure, the file content didn't change
  1650. self.assertTrue(filecmp.cmp(path_in, path_test))
  1651. # ensure no backup file was created
  1652. self.assertFalse(os.path.exists(path_test + ".bak"))
  1653. # ensure the file's mtime didn't change
  1654. self.assertTrue(fstats_post.st_mtime, fstats_orig.st_mtime - age)
  1655. # ensure, all 'file.replace' runs reported success
  1656. self.assertSaltTrueReturn(ret)
  1657. @pytest.mark.slow_test(seconds=30) # Test takes >10 and <=30 seconds
  1658. def test_serialize(self):
  1659. """
  1660. Test to ensure that file.serialize returns a data structure that's
  1661. both serialized and formatted properly
  1662. """
  1663. path_test = os.path.join(RUNTIME_VARS.TMP, "test_serialize")
  1664. ret = self.run_state(
  1665. "file.serialize",
  1666. name=path_test,
  1667. dataset={
  1668. "name": "naive",
  1669. "description": "A basic test",
  1670. "a_list": ["first_element", "second_element"],
  1671. "finally": "the last item",
  1672. },
  1673. formatter="json",
  1674. )
  1675. with salt.utils.files.fopen(path_test, "rb") as fp_:
  1676. serialized_file = salt.utils.stringutils.to_unicode(fp_.read())
  1677. # The JSON serializer uses LF even on OSes where os.sep is CRLF.
  1678. expected_file = "\n".join(
  1679. [
  1680. "{",
  1681. ' "a_list": [',
  1682. ' "first_element",',
  1683. ' "second_element"',
  1684. " ],",
  1685. ' "description": "A basic test",',
  1686. ' "finally": "the last item",',
  1687. ' "name": "naive"',
  1688. "}",
  1689. "",
  1690. ]
  1691. )
  1692. self.assertEqual(serialized_file, expected_file)
  1693. @with_tempfile(create=False)
  1694. @pytest.mark.slow_test(seconds=60) # Test takes >30 and <=60 seconds
  1695. def test_serializer_deserializer_opts(self, name):
  1696. """
  1697. Test the serializer_opts and deserializer_opts options
  1698. """
  1699. data1 = {"foo": {"bar": "%(x)s"}}
  1700. data2 = {"foo": {"abc": 123}}
  1701. merged = {"foo": {"y": "not_used", "x": "baz", "abc": 123, "bar": "baz"}}
  1702. ret = self.run_state(
  1703. "file.serialize",
  1704. name=name,
  1705. dataset=data1,
  1706. formatter="configparser",
  1707. deserializer_opts=[{"defaults": {"y": "not_used"}}],
  1708. )
  1709. ret = ret[next(iter(ret))]
  1710. assert ret["result"], ret
  1711. # We should have warned about deserializer_opts being used when
  1712. # merge_if_exists was not set to True.
  1713. assert "warnings" in ret
  1714. # Run with merge_if_exists, as well as serializer and deserializer opts
  1715. # deserializer opts will be used for string interpolation of the %(x)s
  1716. # that was written to the file with data1 (i.e. bar should become baz)
  1717. ret = self.run_state(
  1718. "file.serialize",
  1719. name=name,
  1720. dataset=data2,
  1721. formatter="configparser",
  1722. merge_if_exists=True,
  1723. serializer_opts=[{"defaults": {"y": "not_used"}}],
  1724. deserializer_opts=[{"defaults": {"x": "baz"}}],
  1725. )
  1726. ret = ret[next(iter(ret))]
  1727. assert ret["result"], ret
  1728. with salt.utils.files.fopen(name) as fp_:
  1729. serialized_data = salt.serializers.configparser.deserialize(fp_)
  1730. # If this test fails, this debug logging will help tell us how the
  1731. # serialized data differs from what was serialized.
  1732. log.debug("serialized_data = %r", serialized_data)
  1733. log.debug("merged = %r", merged)
  1734. # serializing with a default of 'y' will add y = not_used into foo
  1735. assert serialized_data["foo"]["y"] == merged["foo"]["y"]
  1736. # deserializing with default of x = baz will perform interpolation on %(x)s
  1737. # and bar will then = baz
  1738. assert serialized_data["foo"]["bar"] == merged["foo"]["bar"]
  1739. @with_tempdir()
  1740. @pytest.mark.slow_test(seconds=30) # Test takes >10 and <=30 seconds
  1741. def test_replace_issue_18841_omit_backup(self, base_dir):
  1742. """
  1743. Test the (mis-)behaviour of file.replace as described in #18841:
  1744. Using file.replace in a way which shouldn't modify the file at all
  1745. results in changed mtime of the original file and a backup file being created.
  1746. # Case description
  1747. The tested file contains multiple lines
  1748. The tested file contains a line already matching the replacement (no change needed)
  1749. The tested file's content shouldn't change at all
  1750. The tested file's mtime shouldn't change at all
  1751. No backup file should be created, although backup=False isn't explicitly defined
  1752. """
  1753. test_name = "test_replace_issue_18841_omit_backup"
  1754. path_in = os.path.join(
  1755. RUNTIME_VARS.FILES, "file.replace", "{0}.in".format(test_name)
  1756. )
  1757. path_test = os.path.join(base_dir, test_name)
  1758. # create test file based on initial template
  1759. shutil.copyfile(path_in, path_test)
  1760. # get (m|a)time of file
  1761. fstats_orig = os.stat(path_test)
  1762. # define how far we predate the file
  1763. age = 5 * 24 * 60 * 60
  1764. # set (m|a)time of file 5 days into the past
  1765. os.utime(path_test, (fstats_orig.st_mtime - age, fstats_orig.st_atime - age))
  1766. ret = self.run_state(
  1767. "file.replace",
  1768. name=path_test,
  1769. pattern="^hello world$",
  1770. repl="goodbye world",
  1771. show_changes=True,
  1772. flags=["IGNORECASE"],
  1773. )
  1774. # get (m|a)time of file
  1775. fstats_post = os.stat(path_test)
  1776. # ensure, the file content didn't change
  1777. self.assertTrue(filecmp.cmp(path_in, path_test))
  1778. # ensure no backup file was created
  1779. self.assertFalse(os.path.exists(path_test + ".bak"))
  1780. # ensure the file's mtime didn't change
  1781. self.assertTrue(fstats_post.st_mtime, fstats_orig.st_mtime - age)
  1782. # ensure, all 'file.replace' runs reported success
  1783. self.assertSaltTrueReturn(ret)
  1784. @with_tempfile()
  1785. @pytest.mark.slow_test(seconds=60) # Test takes >30 and <=60 seconds
  1786. def test_comment(self, name):
  1787. """
  1788. file.comment
  1789. """
  1790. # write a line to file
  1791. with salt.utils.files.fopen(name, "w+") as fp_:
  1792. fp_.write("comment_me")
  1793. # Look for changes with test=True: return should be "None" at the first run
  1794. ret = self.run_state("file.comment", test=True, name=name, regex="^comment")
  1795. self.assertSaltNoneReturn(ret)
  1796. # comment once
  1797. ret = self.run_state("file.comment", name=name, regex="^comment")
  1798. # result is positive
  1799. self.assertSaltTrueReturn(ret)
  1800. # line is commented
  1801. with salt.utils.files.fopen(name, "r") as fp_:
  1802. self.assertTrue(fp_.read().startswith("#comment"))
  1803. # comment twice
  1804. ret = self.run_state("file.comment", name=name, regex="^comment")
  1805. # result is still positive
  1806. self.assertSaltTrueReturn(ret)
  1807. # line is still commented
  1808. with salt.utils.files.fopen(name, "r") as fp_:
  1809. self.assertTrue(fp_.read().startswith("#comment"))
  1810. # Test previously commented file returns "True" now and not "None" with test=True
  1811. ret = self.run_state("file.comment", test=True, name=name, regex="^comment")
  1812. self.assertSaltTrueReturn(ret)
  1813. @with_tempfile()
  1814. @pytest.mark.slow_test(seconds=30) # Test takes >10 and <=30 seconds
  1815. def test_test_comment(self, name):
  1816. """
  1817. file.comment test interface
  1818. """
  1819. with salt.utils.files.fopen(name, "w+") as fp_:
  1820. fp_.write("comment_me")
  1821. ret = self.run_state("file.comment", test=True, name=name, regex=".*comment.*",)
  1822. with salt.utils.files.fopen(name, "r") as fp_:
  1823. self.assertNotIn("#comment", fp_.read())
  1824. self.assertSaltNoneReturn(ret)
  1825. @with_tempfile()
  1826. @pytest.mark.slow_test(seconds=30) # Test takes >10 and <=30 seconds
  1827. def test_uncomment(self, name):
  1828. """
  1829. file.uncomment
  1830. """
  1831. with salt.utils.files.fopen(name, "w+") as fp_:
  1832. fp_.write("#comment_me")
  1833. ret = self.run_state("file.uncomment", name=name, regex="^comment")
  1834. with salt.utils.files.fopen(name, "r") as fp_:
  1835. self.assertNotIn("#comment", fp_.read())
  1836. self.assertSaltTrueReturn(ret)
  1837. @with_tempfile()
  1838. @pytest.mark.slow_test(seconds=30) # Test takes >10 and <=30 seconds
  1839. def test_test_uncomment(self, name):
  1840. """
  1841. file.comment test interface
  1842. """
  1843. with salt.utils.files.fopen(name, "w+") as fp_:
  1844. fp_.write("#comment_me")
  1845. ret = self.run_state("file.uncomment", test=True, name=name, regex="^comment.*")
  1846. with salt.utils.files.fopen(name, "r") as fp_:
  1847. self.assertIn("#comment", fp_.read())
  1848. self.assertSaltNoneReturn(ret)
  1849. @with_tempfile()
  1850. @pytest.mark.slow_test(seconds=30) # Test takes >10 and <=30 seconds
  1851. def test_append(self, name):
  1852. """
  1853. file.append
  1854. """
  1855. with salt.utils.files.fopen(name, "w+") as fp_:
  1856. fp_.write("#salty!")
  1857. ret = self.run_state("file.append", name=name, text="cheese")
  1858. with salt.utils.files.fopen(name, "r") as fp_:
  1859. self.assertIn("cheese", fp_.read())
  1860. self.assertSaltTrueReturn(ret)
  1861. @with_tempfile()
  1862. @pytest.mark.slow_test(seconds=30) # Test takes >10 and <=30 seconds
  1863. def test_test_append(self, name):
  1864. """
  1865. file.append test interface
  1866. """
  1867. with salt.utils.files.fopen(name, "w+") as fp_:
  1868. fp_.write("#salty!")
  1869. ret = self.run_state("file.append", test=True, name=name, text="cheese")
  1870. with salt.utils.files.fopen(name, "r") as fp_:
  1871. self.assertNotIn("cheese", fp_.read())
  1872. self.assertSaltNoneReturn(ret)
  1873. @with_tempdir()
  1874. @pytest.mark.slow_test(seconds=60) # Test takes >30 and <=60 seconds
  1875. def test_append_issue_1864_makedirs(self, base_dir):
  1876. """
  1877. file.append but create directories if needed as an option, and create
  1878. the file if it doesn't exist
  1879. """
  1880. fname = "append_issue_1864_makedirs"
  1881. name = os.path.join(base_dir, fname)
  1882. # Non existing file get's touched
  1883. ret = self.run_state("file.append", name=name, text="cheese", makedirs=True)
  1884. self.assertSaltTrueReturn(ret)
  1885. # Nested directory and file get's touched
  1886. name = os.path.join(base_dir, "issue_1864", fname)
  1887. ret = self.run_state("file.append", name=name, text="cheese", makedirs=True)
  1888. self.assertSaltTrueReturn(ret)
  1889. # Parent directory exists but file does not and makedirs is False
  1890. name = os.path.join(base_dir, "issue_1864", fname + "2")
  1891. ret = self.run_state("file.append", name=name, text="cheese")
  1892. self.assertSaltTrueReturn(ret)
  1893. self.assertTrue(os.path.isfile(name))
  1894. @with_tempdir()
  1895. @pytest.mark.slow_test(seconds=60) # Test takes >30 and <=60 seconds
  1896. def test_prepend_issue_27401_makedirs(self, base_dir):
  1897. """
  1898. file.prepend but create directories if needed as an option, and create
  1899. the file if it doesn't exist
  1900. """
  1901. fname = "prepend_issue_27401"
  1902. name = os.path.join(base_dir, fname)
  1903. # Non existing file get's touched
  1904. ret = self.run_state("file.prepend", name=name, text="cheese", makedirs=True)
  1905. self.assertSaltTrueReturn(ret)
  1906. # Nested directory and file get's touched
  1907. name = os.path.join(base_dir, "issue_27401", fname)
  1908. ret = self.run_state("file.prepend", name=name, text="cheese", makedirs=True)
  1909. self.assertSaltTrueReturn(ret)
  1910. # Parent directory exists but file does not and makedirs is False
  1911. name = os.path.join(base_dir, "issue_27401", fname + "2")
  1912. ret = self.run_state("file.prepend", name=name, text="cheese")
  1913. self.assertSaltTrueReturn(ret)
  1914. self.assertTrue(os.path.isfile(name))
  1915. @with_tempfile()
  1916. @pytest.mark.slow_test(seconds=30) # Test takes >10 and <=30 seconds
  1917. def test_touch(self, name):
  1918. """
  1919. file.touch
  1920. """
  1921. ret = self.run_state("file.touch", name=name)
  1922. self.assertTrue(os.path.isfile(name))
  1923. self.assertSaltTrueReturn(ret)
  1924. @with_tempfile(create=False)
  1925. @pytest.mark.slow_test(seconds=30) # Test takes >10 and <=30 seconds
  1926. def test_test_touch(self, name):
  1927. """
  1928. file.touch test interface
  1929. """
  1930. ret = self.run_state("file.touch", test=True, name=name)
  1931. self.assertFalse(os.path.isfile(name))
  1932. self.assertSaltNoneReturn(ret)
  1933. @with_tempdir()
  1934. @pytest.mark.slow_test(seconds=30) # Test takes >10 and <=30 seconds
  1935. def test_touch_directory(self, base_dir):
  1936. """
  1937. file.touch a directory
  1938. """
  1939. name = os.path.join(base_dir, "touch_test_dir")
  1940. os.mkdir(name)
  1941. ret = self.run_state("file.touch", name=name)
  1942. self.assertSaltTrueReturn(ret)
  1943. self.assertTrue(os.path.isdir(name))
  1944. @with_tempdir()
  1945. @pytest.mark.slow_test(seconds=120) # Test takes >60 and <=120 seconds
  1946. def test_issue_2227_file_append(self, base_dir):
  1947. """
  1948. Text to append includes a percent symbol
  1949. """
  1950. # let's make use of existing state to create a file with contents to
  1951. # test against
  1952. tmp_file_append = os.path.join(base_dir, "test.append")
  1953. self.run_state("file.touch", name=tmp_file_append)
  1954. self.run_state(
  1955. "file.append", name=tmp_file_append, source="salt://testappend/firstif"
  1956. )
  1957. self.run_state(
  1958. "file.append", name=tmp_file_append, source="salt://testappend/secondif"
  1959. )
  1960. # Now our real test
  1961. try:
  1962. ret = self.run_state(
  1963. "file.append", name=tmp_file_append, text="HISTTIMEFORMAT='%F %T '"
  1964. )
  1965. self.assertSaltTrueReturn(ret)
  1966. with salt.utils.files.fopen(tmp_file_append, "r") as fp_:
  1967. contents_pre = fp_.read()
  1968. # It should not append text again
  1969. ret = self.run_state(
  1970. "file.append", name=tmp_file_append, text="HISTTIMEFORMAT='%F %T '"
  1971. )
  1972. self.assertSaltTrueReturn(ret)
  1973. with salt.utils.files.fopen(tmp_file_append, "r") as fp_:
  1974. contents_post = fp_.read()
  1975. self.assertEqual(contents_pre, contents_post)
  1976. except AssertionError:
  1977. if os.path.exists(tmp_file_append):
  1978. shutil.copy(tmp_file_append, tmp_file_append + ".bak")
  1979. raise
  1980. @with_tempdir()
  1981. @pytest.mark.slow_test(seconds=60) # Test takes >30 and <=60 seconds
  1982. def test_issue_2401_file_comment(self, base_dir):
  1983. # Get a path to the temporary file
  1984. tmp_file = os.path.join(base_dir, "issue-2041-comment.txt")
  1985. # Write some data to it
  1986. with salt.utils.files.fopen(tmp_file, "w") as fp_:
  1987. fp_.write("hello\nworld\n")
  1988. # create the sls template
  1989. template_lines = [
  1990. "{0}:".format(tmp_file),
  1991. " file.comment:",
  1992. " - regex: ^world",
  1993. ]
  1994. template = "\n".join(template_lines)
  1995. try:
  1996. ret = self.run_function("state.template_str", [template], timeout=120)
  1997. self.assertSaltTrueReturn(ret)
  1998. self.assertNotInSaltComment("Pattern already commented", ret)
  1999. self.assertInSaltComment("Commented lines successfully", ret)
  2000. # This next time, it is already commented.
  2001. ret = self.run_function("state.template_str", [template], timeout=120)
  2002. self.assertSaltTrueReturn(ret)
  2003. self.assertInSaltComment("Pattern already commented", ret)
  2004. except AssertionError:
  2005. shutil.copy(tmp_file, tmp_file + ".bak")
  2006. raise
  2007. @with_tempdir()
  2008. @pytest.mark.slow_test(seconds=30) # Test takes >10 and <=30 seconds
  2009. def test_issue_2379_file_append(self, base_dir):
  2010. # Get a path to the temporary file
  2011. tmp_file = os.path.join(base_dir, "issue-2379-file-append.txt")
  2012. # Write some data to it
  2013. with salt.utils.files.fopen(tmp_file, "w") as fp_:
  2014. fp_.write(
  2015. "hello\nworld\n" # Some junk
  2016. "#PermitRootLogin yes\n" # Commented text
  2017. "# PermitRootLogin yes\n" # Commented text with space
  2018. )
  2019. # create the sls template
  2020. template_lines = [
  2021. "{0}:".format(tmp_file),
  2022. " file.append:",
  2023. " - text: PermitRootLogin yes",
  2024. ]
  2025. template = "\n".join(template_lines)
  2026. try:
  2027. ret = self.run_function("state.template_str", [template])
  2028. self.assertSaltTrueReturn(ret)
  2029. self.assertInSaltComment("Appended 1 lines", ret)
  2030. except AssertionError:
  2031. shutil.copy(tmp_file, tmp_file + ".bak")
  2032. raise
  2033. @skipIf(IS_WINDOWS, "Mode not available in Windows")
  2034. @with_tempdir(create=False)
  2035. @with_tempdir(create=False)
  2036. @pytest.mark.slow_test(seconds=5) # Test takes >1 and <=5 seconds
  2037. def test_issue_2726_mode_kwarg(self, dir1, dir2):
  2038. # Let's test for the wrong usage approach
  2039. bad_mode_kwarg_testfile = os.path.join(dir1, "bad_mode_kwarg", "testfile")
  2040. bad_template = [
  2041. "{0}:".format(bad_mode_kwarg_testfile),
  2042. " file.recurse:",
  2043. " - source: salt://testfile",
  2044. " - mode: 644",
  2045. ]
  2046. ret = self.run_function("state.template_str", [os.linesep.join(bad_template)])
  2047. self.assertSaltFalseReturn(ret)
  2048. self.assertInSaltComment(
  2049. "'mode' is not allowed in 'file.recurse'. Please use "
  2050. "'file_mode' and 'dir_mode'.",
  2051. ret,
  2052. )
  2053. self.assertNotInSaltComment(
  2054. "TypeError: managed() got multiple values for keyword " "argument 'mode'",
  2055. ret,
  2056. )
  2057. # Now, the correct usage approach
  2058. good_mode_kwargs_testfile = os.path.join(dir2, "good_mode_kwargs", "testappend")
  2059. good_template = [
  2060. "{0}:".format(good_mode_kwargs_testfile),
  2061. " file.recurse:",
  2062. " - source: salt://testappend",
  2063. " - dir_mode: 744",
  2064. " - file_mode: 644",
  2065. ]
  2066. ret = self.run_function("state.template_str", [os.linesep.join(good_template)])
  2067. self.assertSaltTrueReturn(ret)
  2068. @with_tempdir()
  2069. @pytest.mark.slow_test(seconds=30) # Test takes >10 and <=30 seconds
  2070. def test_issue_8343_accumulated_require_in(self, base_dir):
  2071. template_path = os.path.join(RUNTIME_VARS.TMP_STATE_TREE, "issue-8343.sls")
  2072. testcase_filedest = os.path.join(base_dir, "issue-8343.txt")
  2073. if os.path.exists(template_path):
  2074. os.remove(template_path)
  2075. if os.path.exists(testcase_filedest):
  2076. os.remove(testcase_filedest)
  2077. sls_template = [
  2078. "{0}:",
  2079. " file.managed:",
  2080. " - contents: |",
  2081. " #",
  2082. "",
  2083. "prepend-foo-accumulator-from-pillar:",
  2084. " file.accumulated:",
  2085. " - require_in:",
  2086. " - file: prepend-foo-management",
  2087. " - filename: {0}",
  2088. " - text: |",
  2089. " foo",
  2090. "",
  2091. "append-foo-accumulator-from-pillar:",
  2092. " file.accumulated:",
  2093. " - require_in:",
  2094. " - file: append-foo-management",
  2095. " - filename: {0}",
  2096. " - text: |",
  2097. " bar",
  2098. "",
  2099. "prepend-foo-management:",
  2100. " file.blockreplace:",
  2101. " - name: {0}",
  2102. ' - marker_start: "#-- start salt managed zonestart -- PLEASE, DO NOT EDIT"',
  2103. ' - marker_end: "#-- end salt managed zonestart --"',
  2104. " - content: ''",
  2105. " - prepend_if_not_found: True",
  2106. " - backup: '.bak'",
  2107. " - show_changes: True",
  2108. "",
  2109. "append-foo-management:",
  2110. " file.blockreplace:",
  2111. " - name: {0}",
  2112. ' - marker_start: "#-- start salt managed zoneend -- PLEASE, DO NOT EDIT"',
  2113. ' - marker_end: "#-- end salt managed zoneend --"',
  2114. " - content: ''",
  2115. " - append_if_not_found: True",
  2116. " - backup: '.bak2'",
  2117. " - show_changes: True",
  2118. "",
  2119. ]
  2120. with salt.utils.files.fopen(template_path, "w") as fp_:
  2121. fp_.write(os.linesep.join(sls_template).format(testcase_filedest))
  2122. ret = self.run_function("state.sls", mods="issue-8343")
  2123. for name, step in six.iteritems(ret):
  2124. self.assertSaltTrueReturn({name: step})
  2125. with salt.utils.files.fopen(testcase_filedest) as fp_:
  2126. contents = fp_.read().split(os.linesep)
  2127. expected = [
  2128. "#-- start salt managed zonestart -- PLEASE, DO NOT EDIT",
  2129. "foo",
  2130. "#-- end salt managed zonestart --",
  2131. "#",
  2132. "#-- start salt managed zoneend -- PLEASE, DO NOT EDIT",
  2133. "bar",
  2134. "#-- end salt managed zoneend --",
  2135. "",
  2136. ]
  2137. self.assertEqual(
  2138. [salt.utils.stringutils.to_str(line) for line in expected], contents
  2139. )
  2140. @with_tempdir()
  2141. @skipIf(
  2142. salt.utils.platform.is_darwin() and six.PY2, "This test hangs on OS X on Py2"
  2143. )
  2144. @pytest.mark.slow_test(seconds=60) # Test takes >30 and <=60 seconds
  2145. def test_issue_11003_immutable_lazy_proxy_sum(self, base_dir):
  2146. # causes the Import-Module ServerManager error on Windows
  2147. template_path = os.path.join(RUNTIME_VARS.TMP_STATE_TREE, "issue-11003.sls")
  2148. testcase_filedest = os.path.join(base_dir, "issue-11003.txt")
  2149. sls_template = [
  2150. "a{0}:",
  2151. " file.absent:",
  2152. " - name: {0}",
  2153. "",
  2154. "{0}:",
  2155. " file.managed:",
  2156. " - contents: |",
  2157. " #",
  2158. "",
  2159. "test-acc1:",
  2160. " file.accumulated:",
  2161. " - require_in:",
  2162. " - file: final",
  2163. " - filename: {0}",
  2164. " - text: |",
  2165. " bar",
  2166. "",
  2167. "test-acc2:",
  2168. " file.accumulated:",
  2169. " - watch_in:",
  2170. " - file: final",
  2171. " - filename: {0}",
  2172. " - text: |",
  2173. " baz",
  2174. "",
  2175. "final:",
  2176. " file.blockreplace:",
  2177. " - name: {0}",
  2178. ' - marker_start: "#-- start managed zone PLEASE, DO NOT EDIT"',
  2179. ' - marker_end: "#-- end managed zone"',
  2180. " - content: ''",
  2181. " - append_if_not_found: True",
  2182. " - show_changes: True",
  2183. ]
  2184. with salt.utils.files.fopen(template_path, "w") as fp_:
  2185. fp_.write(os.linesep.join(sls_template).format(testcase_filedest))
  2186. ret = self.run_function("state.sls", mods="issue-11003", timeout=600)
  2187. for name, step in six.iteritems(ret):
  2188. self.assertSaltTrueReturn({name: step})
  2189. with salt.utils.files.fopen(testcase_filedest) as fp_:
  2190. contents = fp_.read().split(os.linesep)
  2191. begin = contents.index("#-- start managed zone PLEASE, DO NOT EDIT") + 1
  2192. end = contents.index("#-- end managed zone")
  2193. block_contents = contents[begin:end]
  2194. for item in ("", "bar", "baz"):
  2195. block_contents.remove(item)
  2196. self.assertEqual(block_contents, [])
  2197. @with_tempdir()
  2198. @pytest.mark.slow_test(seconds=30) # Test takes >10 and <=30 seconds
  2199. def test_issue_8947_utf8_sls(self, base_dir):
  2200. """
  2201. Test some file operation with utf-8 characters on the sls
  2202. This is more generic than just a file test. Feel free to move
  2203. """
  2204. self.maxDiff = None
  2205. korean_1 = "한국어 시험"
  2206. korean_2 = "첫 번째 행"
  2207. korean_3 = "마지막 행"
  2208. test_file = os.path.join(base_dir, "{0}.txt".format(korean_1))
  2209. test_file_encoded = test_file
  2210. template_path = os.path.join(RUNTIME_VARS.TMP_STATE_TREE, "issue-8947.sls")
  2211. # create the sls template
  2212. template = textwrap.dedent(
  2213. """\
  2214. some-utf8-file-create:
  2215. file.managed:
  2216. - name: {test_file}
  2217. - contents: {korean_1}
  2218. - makedirs: True
  2219. - replace: True
  2220. - show_diff: True
  2221. some-utf8-file-create2:
  2222. file.managed:
  2223. - name: {test_file}
  2224. - contents: |
  2225. {korean_2}
  2226. {korean_1}
  2227. {korean_3}
  2228. - replace: True
  2229. - show_diff: True
  2230. """.format(
  2231. **locals()
  2232. )
  2233. )
  2234. if not salt.utils.platform.is_windows():
  2235. template += textwrap.dedent(
  2236. """\
  2237. some-utf8-file-content-test:
  2238. cmd.run:
  2239. - name: 'cat "{test_file}"'
  2240. - require:
  2241. - file: some-utf8-file-create2
  2242. """.format(
  2243. **locals()
  2244. )
  2245. )
  2246. # Save template file
  2247. with salt.utils.files.fopen(template_path, "wb") as fp_:
  2248. fp_.write(salt.utils.stringutils.to_bytes(template))
  2249. try:
  2250. result = self.run_function("state.sls", mods="issue-8947")
  2251. if not isinstance(result, dict):
  2252. raise AssertionError(
  2253. (
  2254. "Something went really wrong while testing this sls:" " {0}"
  2255. ).format(repr(result))
  2256. )
  2257. # difflib produces different output on python 2.6 than on >=2.7
  2258. if sys.version_info < (2, 7):
  2259. diff = "--- \n+++ \n@@ -1,1 +1,3 @@\n"
  2260. else:
  2261. diff = "--- \n+++ \n@@ -1 +1,3 @@\n"
  2262. diff += ("+첫 번째 행{0}" " 한국어 시험{0}" "+마지막 행{0}").format(os.linesep)
  2263. ret = {x.split("_|-")[1]: y for x, y in six.iteritems(result)}
  2264. # Confirm initial creation of file
  2265. self.assertEqual(
  2266. ret["some-utf8-file-create"]["comment"],
  2267. "File {0} updated".format(test_file_encoded),
  2268. )
  2269. self.assertEqual(
  2270. ret["some-utf8-file-create"]["changes"], {"diff": "New file"}
  2271. )
  2272. # Confirm file was modified and that the diff was as expected
  2273. self.assertEqual(
  2274. ret["some-utf8-file-create2"]["comment"],
  2275. "File {0} updated".format(test_file_encoded),
  2276. )
  2277. self.assertEqual(ret["some-utf8-file-create2"]["changes"], {"diff": diff})
  2278. if salt.utils.platform.is_windows():
  2279. import subprocess
  2280. import win32api
  2281. p = subprocess.Popen(
  2282. salt.utils.stringutils.to_str(
  2283. "type {}".format(win32api.GetShortPathName(test_file))
  2284. ),
  2285. shell=True,
  2286. stdout=subprocess.PIPE,
  2287. stderr=subprocess.PIPE,
  2288. )
  2289. p.poll()
  2290. out = p.stdout.read()
  2291. self.assertEqual(
  2292. out.decode("utf-8"),
  2293. os.linesep.join((korean_2, korean_1, korean_3)) + os.linesep,
  2294. )
  2295. else:
  2296. self.assertEqual(
  2297. ret["some-utf8-file-content-test"]["comment"],
  2298. 'Command "cat "{0}"" run'.format(test_file_encoded),
  2299. )
  2300. self.assertEqual(
  2301. ret["some-utf8-file-content-test"]["changes"]["stdout"],
  2302. "\n".join((korean_2, korean_1, korean_3)),
  2303. )
  2304. finally:
  2305. try:
  2306. os.remove(template_path)
  2307. except OSError:
  2308. pass
  2309. @pytest.mark.skip_if_not_root
  2310. @skipIf(not HAS_PWD, "pwd not available. Skipping test")
  2311. @skipIf(not HAS_GRP, "grp not available. Skipping test")
  2312. @with_system_user_and_group(
  2313. TEST_SYSTEM_USER, TEST_SYSTEM_GROUP, on_existing="delete", delete=True
  2314. )
  2315. @with_tempdir()
  2316. @pytest.mark.slow_test(seconds=10) # Test takes >5 and <=10 seconds
  2317. def test_issue_12209_follow_symlinks(self, tempdir, user, group):
  2318. """
  2319. Ensure that symlinks are properly chowned when recursing (following
  2320. symlinks)
  2321. """
  2322. # Make the directories for this test
  2323. onedir = os.path.join(tempdir, "one")
  2324. twodir = os.path.join(tempdir, "two")
  2325. os.mkdir(onedir)
  2326. os.symlink(onedir, twodir)
  2327. # Run the state
  2328. ret = self.run_state(
  2329. "file.directory",
  2330. name=tempdir,
  2331. follow_symlinks=True,
  2332. user=user,
  2333. group=group,
  2334. recurse=["user", "group"],
  2335. )
  2336. self.assertSaltTrueReturn(ret)
  2337. # Double-check, in case state mis-reported a True result. Since we are
  2338. # following symlinks, we expect twodir to still be owned by root, but
  2339. # onedir should be owned by the 'issue12209' user.
  2340. onestats = os.stat(onedir)
  2341. twostats = os.lstat(twodir)
  2342. self.assertEqual(pwd.getpwuid(onestats.st_uid).pw_name, user)
  2343. self.assertEqual(pwd.getpwuid(twostats.st_uid).pw_name, "root")
  2344. self.assertEqual(grp.getgrgid(onestats.st_gid).gr_name, group)
  2345. if salt.utils.path.which("id"):
  2346. root_group = self.run_function("user.primary_group", ["root"])
  2347. self.assertEqual(grp.getgrgid(twostats.st_gid).gr_name, root_group)
  2348. @pytest.mark.skip_if_not_root
  2349. @skipIf(not HAS_PWD, "pwd not available. Skipping test")
  2350. @skipIf(not HAS_GRP, "grp not available. Skipping test")
  2351. @with_system_user_and_group(
  2352. TEST_SYSTEM_USER, TEST_SYSTEM_GROUP, on_existing="delete", delete=True
  2353. )
  2354. @with_tempdir()
  2355. @pytest.mark.slow_test(seconds=10) # Test takes >5 and <=10 seconds
  2356. def test_issue_12209_no_follow_symlinks(self, tempdir, user, group):
  2357. """
  2358. Ensure that symlinks are properly chowned when recursing (not following
  2359. symlinks)
  2360. """
  2361. # Make the directories for this test
  2362. onedir = os.path.join(tempdir, "one")
  2363. twodir = os.path.join(tempdir, "two")
  2364. os.mkdir(onedir)
  2365. os.symlink(onedir, twodir)
  2366. # Run the state
  2367. ret = self.run_state(
  2368. "file.directory",
  2369. name=tempdir,
  2370. follow_symlinks=False,
  2371. user=user,
  2372. group=group,
  2373. recurse=["user", "group"],
  2374. )
  2375. self.assertSaltTrueReturn(ret)
  2376. # Double-check, in case state mis-reported a True result. Since we
  2377. # are not following symlinks, we expect twodir to now be owned by
  2378. # the 'issue12209' user, just link onedir.
  2379. onestats = os.stat(onedir)
  2380. twostats = os.lstat(twodir)
  2381. self.assertEqual(pwd.getpwuid(onestats.st_uid).pw_name, user)
  2382. self.assertEqual(pwd.getpwuid(twostats.st_uid).pw_name, user)
  2383. self.assertEqual(grp.getgrgid(onestats.st_gid).gr_name, group)
  2384. self.assertEqual(grp.getgrgid(twostats.st_gid).gr_name, group)
  2385. @with_tempfile(create=False)
  2386. @with_tempfile()
  2387. @pytest.mark.slow_test(seconds=60) # Test takes >30 and <=60 seconds
  2388. def test_template_local_file(self, source, dest):
  2389. """
  2390. Test a file.managed state with a local file as the source. Test both
  2391. with the file:// protocol designation prepended, and without it.
  2392. """
  2393. with salt.utils.files.fopen(source, "w") as fp_:
  2394. fp_.write("{{ foo }}\n")
  2395. for prefix in ("file://", ""):
  2396. ret = self.run_state(
  2397. "file.managed",
  2398. name=dest,
  2399. source=prefix + source,
  2400. template="jinja",
  2401. context={"foo": "Hello world!"},
  2402. )
  2403. self.assertSaltTrueReturn(ret)
  2404. @with_tempfile()
  2405. @pytest.mark.slow_test(seconds=30) # Test takes >10 and <=30 seconds
  2406. def test_template_local_file_noclobber(self, source):
  2407. """
  2408. Test the case where a source file is in the minion's local filesystem,
  2409. and the source path is the same as the destination path.
  2410. """
  2411. with salt.utils.files.fopen(source, "w") as fp_:
  2412. fp_.write("{{ foo }}\n")
  2413. ret = self.run_state(
  2414. "file.managed",
  2415. name=source,
  2416. source=source,
  2417. template="jinja",
  2418. context={"foo": "Hello world!"},
  2419. )
  2420. self.assertSaltFalseReturn(ret)
  2421. self.assertIn(
  2422. ("Source file cannot be the same as destination"),
  2423. ret[next(iter(ret))]["comment"],
  2424. )
  2425. @with_tempfile(create=False)
  2426. @with_tempfile(create=False)
  2427. @pytest.mark.slow_test(seconds=30) # Test takes >10 and <=30 seconds
  2428. def test_issue_25250_force_copy_deletes(self, source, dest):
  2429. """
  2430. ensure force option in copy state does not delete target file
  2431. """
  2432. shutil.copyfile(os.path.join(RUNTIME_VARS.FILES, "hosts"), source)
  2433. shutil.copyfile(os.path.join(RUNTIME_VARS.FILES, "file/base/cheese"), dest)
  2434. self.run_state("file.copy", name=dest, source=source, force=True)
  2435. self.assertTrue(os.path.exists(dest))
  2436. self.assertTrue(filecmp.cmp(source, dest))
  2437. os.remove(source)
  2438. os.remove(dest)
  2439. @skipIf(IS_WINDOWS, "Windows does not report any file modes. Skipping.")
  2440. @pytest.mark.destructive_test
  2441. @with_tempfile()
  2442. @pytest.mark.slow_test(seconds=10) # Test takes >5 and <=10 seconds
  2443. def test_file_copy_make_dirs(self, source):
  2444. """
  2445. ensure make_dirs creates correct user perms
  2446. """
  2447. shutil.copyfile(os.path.join(RUNTIME_VARS.FILES, "hosts"), source)
  2448. dest = os.path.join(RUNTIME_VARS.TMP, "dir1", "dir2", "copied_file.txt")
  2449. user = "salt"
  2450. mode = "0644"
  2451. ret = self.run_function("user.add", [user])
  2452. self.assertTrue(ret, "Failed to add user. Are you running as sudo?")
  2453. ret = self.run_state(
  2454. "file.copy", name=dest, source=source, user=user, makedirs=True, mode=mode
  2455. )
  2456. self.assertSaltTrueReturn(ret)
  2457. file_checks = [
  2458. dest,
  2459. os.path.join(RUNTIME_VARS.TMP, "dir1"),
  2460. os.path.join(RUNTIME_VARS.TMP, "dir1", "dir2"),
  2461. ]
  2462. for check in file_checks:
  2463. user_check = self.run_function("file.get_user", [check])
  2464. mode_check = self.run_function("file.get_mode", [check])
  2465. self.assertEqual(user_check, user)
  2466. self.assertEqual(salt.utils.files.normalize_mode(mode_check), mode)
  2467. @pytest.mark.slow_test(seconds=30) # Test takes >10 and <=30 seconds
  2468. def test_contents_pillar_with_pillar_list(self):
  2469. """
  2470. This tests for any regressions for this issue:
  2471. https://github.com/saltstack/salt/issues/30934
  2472. """
  2473. state_file = "file_contents_pillar"
  2474. ret = self.run_function("state.sls", mods=state_file)
  2475. self.assertSaltTrueReturn(ret)
  2476. @pytest.mark.skip_if_not_root
  2477. @skipIf(not HAS_PWD, "pwd not available. Skipping test")
  2478. @skipIf(not HAS_GRP, "grp not available. Skipping test")
  2479. @with_system_user_and_group(
  2480. TEST_SYSTEM_USER, TEST_SYSTEM_GROUP, on_existing="delete", delete=True
  2481. )
  2482. @pytest.mark.slow_test(seconds=10) # Test takes >5 and <=10 seconds
  2483. def test_owner_after_setuid(self, user, group):
  2484. """
  2485. Test to check file user/group after setting setuid or setgid.
  2486. Because Python os.chown() does reset the setuid/setgid to 0.
  2487. https://github.com/saltstack/salt/pull/45257
  2488. """
  2489. # Desired configuration.
  2490. desired = {
  2491. "file": os.path.join(RUNTIME_VARS.TMP, "file_with_setuid"),
  2492. "user": user,
  2493. "group": group,
  2494. "mode": "4750",
  2495. }
  2496. # Run the state.
  2497. ret = self.run_state(
  2498. "file.managed",
  2499. name=desired["file"],
  2500. user=desired["user"],
  2501. group=desired["group"],
  2502. mode=desired["mode"],
  2503. )
  2504. # Check result.
  2505. file_stat = os.stat(desired["file"])
  2506. result = {
  2507. "user": pwd.getpwuid(file_stat.st_uid).pw_name,
  2508. "group": grp.getgrgid(file_stat.st_gid).gr_name,
  2509. "mode": oct(stat.S_IMODE(file_stat.st_mode)),
  2510. }
  2511. self.assertSaltTrueReturn(ret)
  2512. self.assertEqual(desired["user"], result["user"])
  2513. self.assertEqual(desired["group"], result["group"])
  2514. self.assertEqual(desired["mode"], result["mode"].lstrip("0Oo"))
  2515. @pytest.mark.slow_test(seconds=30) # Test takes >10 and <=30 seconds
  2516. def test_binary_contents(self):
  2517. """
  2518. This tests to ensure that binary contents do not cause a traceback.
  2519. """
  2520. name = os.path.join(RUNTIME_VARS.TMP, "1px.gif")
  2521. try:
  2522. ret = self.run_state("file.managed", name=name, contents=BINARY_FILE)
  2523. self.assertSaltTrueReturn(ret)
  2524. finally:
  2525. try:
  2526. os.remove(name)
  2527. except OSError:
  2528. pass
  2529. @pytest.mark.slow_test(seconds=60) # Test takes >30 and <=60 seconds
  2530. def test_binary_contents_twice(self):
  2531. """
  2532. This test ensures that after a binary file is created, salt can confirm
  2533. that the file is in the correct state.
  2534. """
  2535. # Create a binary file
  2536. name = os.path.join(RUNTIME_VARS.TMP, "1px.gif")
  2537. # First run state ensures file is created
  2538. ret = self.run_state("file.managed", name=name, contents=BINARY_FILE)
  2539. self.assertSaltTrueReturn(ret)
  2540. # Second run of state ensures file is in correct state
  2541. ret = self.run_state("file.managed", name=name, contents=BINARY_FILE)
  2542. self.assertSaltTrueReturn(ret)
  2543. try:
  2544. os.remove(name)
  2545. except OSError:
  2546. pass
  2547. @pytest.mark.skip_if_not_root
  2548. @skipIf(not HAS_PWD, "pwd not available. Skipping test")
  2549. @skipIf(not HAS_GRP, "grp not available. Skipping test")
  2550. @with_system_user_and_group(
  2551. TEST_SYSTEM_USER, TEST_SYSTEM_GROUP, on_existing="delete", delete=True
  2552. )
  2553. @with_tempdir()
  2554. @pytest.mark.slow_test(seconds=10) # Test takes >5 and <=10 seconds
  2555. def test_issue_48336_file_managed_mode_setuid(self, tempdir, user, group):
  2556. """
  2557. Ensure that mode is correct with changing of ownership and group
  2558. symlinks)
  2559. """
  2560. tempfile = os.path.join(tempdir, "temp_file_issue_48336")
  2561. # Run the state
  2562. ret = self.run_state(
  2563. "file.managed", name=tempfile, user=user, group=group, mode="4750",
  2564. )
  2565. self.assertSaltTrueReturn(ret)
  2566. # Check that the owner and group are correct, and
  2567. # the mode is what we expect
  2568. temp_file_stats = os.stat(tempfile)
  2569. # Normalize the mode
  2570. temp_file_mode = six.text_type(oct(stat.S_IMODE(temp_file_stats.st_mode)))
  2571. temp_file_mode = salt.utils.files.normalize_mode(temp_file_mode)
  2572. self.assertEqual(temp_file_mode, "4750")
  2573. self.assertEqual(pwd.getpwuid(temp_file_stats.st_uid).pw_name, user)
  2574. self.assertEqual(grp.getgrgid(temp_file_stats.st_gid).gr_name, group)
  2575. @with_tempdir()
  2576. @pytest.mark.slow_test(seconds=30) # Test takes >10 and <=30 seconds
  2577. def test_issue_48557(self, tempdir):
  2578. tempfile = os.path.join(tempdir, "temp_file_issue_48557")
  2579. with salt.utils.files.fopen(tempfile, "wb") as fp:
  2580. fp.write(os.linesep.join(["test1", "test2", "test3", ""]).encode("utf-8"))
  2581. ret = self.run_state(
  2582. "file.line", name=tempfile, after="test2", mode="insert", content="test4"
  2583. )
  2584. self.assertSaltTrueReturn(ret)
  2585. with salt.utils.files.fopen(tempfile, "rb") as fp:
  2586. content = fp.read()
  2587. self.assertEqual(
  2588. content,
  2589. os.linesep.join(["test1", "test2", "test4", "test3", ""]).encode("utf-8"),
  2590. )
  2591. @with_tempfile()
  2592. @pytest.mark.slow_test(seconds=60) # Test takes >30 and <=60 seconds
  2593. def test_issue_50221(self, name):
  2594. expected = "abc{0}{0}{0}".format(os.linesep)
  2595. ret = self.run_function("pillar.get", ["issue-50221"])
  2596. assert ret == expected
  2597. ret = self.run_function("state.apply", ["issue-50221"], pillar={"name": name},)
  2598. self.assertSaltTrueReturn(ret)
  2599. with salt.utils.files.fopen(name, "r") as fp:
  2600. contents = fp.read()
  2601. assert contents == expected
  2602. @pytest.mark.slow_test(seconds=30) # Test takes >10 and <=30 seconds
  2603. def test_managed_file_issue_51208(self):
  2604. """
  2605. Test to ensure we can handle a file with escaped double-quotes
  2606. """
  2607. name = os.path.join(RUNTIME_VARS.TMP, "issue_51208.txt")
  2608. ret = self.run_state(
  2609. "file.managed", name=name, source="salt://issue-51208/vimrc.stub"
  2610. )
  2611. src = os.path.join(RUNTIME_VARS.BASE_FILES, "issue-51208", "vimrc.stub")
  2612. with salt.utils.files.fopen(src, "r") as fp_:
  2613. master_data = fp_.read()
  2614. with salt.utils.files.fopen(name, "r") as fp_:
  2615. minion_data = fp_.read()
  2616. self.assertEqual(master_data, minion_data)
  2617. self.assertSaltTrueReturn(ret)
  2618. @pytest.mark.windows_whitelisted
  2619. class BlockreplaceTest(ModuleCase, SaltReturnAssertsMixin):
  2620. marker_start = "# start"
  2621. marker_end = "# end"
  2622. content = dedent(
  2623. six.text_type(
  2624. """\
  2625. Line 1 of block
  2626. Line 2 of block
  2627. """
  2628. )
  2629. )
  2630. without_block = dedent(
  2631. six.text_type(
  2632. """\
  2633. Hello world!
  2634. # comment here
  2635. """
  2636. )
  2637. )
  2638. with_non_matching_block = dedent(
  2639. six.text_type(
  2640. """\
  2641. Hello world!
  2642. # start
  2643. No match here
  2644. # end
  2645. # comment here
  2646. """
  2647. )
  2648. )
  2649. with_non_matching_block_and_marker_end_not_after_newline = dedent(
  2650. six.text_type(
  2651. """\
  2652. Hello world!
  2653. # start
  2654. No match here# end
  2655. # comment here
  2656. """
  2657. )
  2658. )
  2659. with_matching_block = dedent(
  2660. six.text_type(
  2661. """\
  2662. Hello world!
  2663. # start
  2664. Line 1 of block
  2665. Line 2 of block
  2666. # end
  2667. # comment here
  2668. """
  2669. )
  2670. )
  2671. with_matching_block_and_extra_newline = dedent(
  2672. six.text_type(
  2673. """\
  2674. Hello world!
  2675. # start
  2676. Line 1 of block
  2677. Line 2 of block
  2678. # end
  2679. # comment here
  2680. """
  2681. )
  2682. )
  2683. with_matching_block_and_marker_end_not_after_newline = dedent(
  2684. six.text_type(
  2685. """\
  2686. Hello world!
  2687. # start
  2688. Line 1 of block
  2689. Line 2 of block# end
  2690. # comment here
  2691. """
  2692. )
  2693. )
  2694. content_explicit_posix_newlines = "Line 1 of block\n" "Line 2 of block\n"
  2695. content_explicit_windows_newlines = "Line 1 of block\r\n" "Line 2 of block\r\n"
  2696. without_block_explicit_posix_newlines = "Hello world!\n\n" "# comment here\n"
  2697. without_block_explicit_windows_newlines = (
  2698. "Hello world!\r\n\r\n" "# comment here\r\n"
  2699. )
  2700. with_block_prepended_explicit_posix_newlines = (
  2701. "# start\n"
  2702. "Line 1 of block\n"
  2703. "Line 2 of block\n"
  2704. "# end\n"
  2705. "Hello world!\n\n"
  2706. "# comment here\n"
  2707. )
  2708. with_block_prepended_explicit_windows_newlines = (
  2709. "# start\r\n"
  2710. "Line 1 of block\r\n"
  2711. "Line 2 of block\r\n"
  2712. "# end\r\n"
  2713. "Hello world!\r\n\r\n"
  2714. "# comment here\r\n"
  2715. )
  2716. with_block_appended_explicit_posix_newlines = (
  2717. "Hello world!\n\n"
  2718. "# comment here\n"
  2719. "# start\n"
  2720. "Line 1 of block\n"
  2721. "Line 2 of block\n"
  2722. "# end\n"
  2723. )
  2724. with_block_appended_explicit_windows_newlines = (
  2725. "Hello world!\r\n\r\n"
  2726. "# comment here\r\n"
  2727. "# start\r\n"
  2728. "Line 1 of block\r\n"
  2729. "Line 2 of block\r\n"
  2730. "# end\r\n"
  2731. )
  2732. @staticmethod
  2733. def _write(dest, content):
  2734. with salt.utils.files.fopen(dest, "wb") as fp_:
  2735. fp_.write(salt.utils.stringutils.to_bytes(content))
  2736. @staticmethod
  2737. def _read(src):
  2738. with salt.utils.files.fopen(src, "rb") as fp_:
  2739. return salt.utils.stringutils.to_unicode(fp_.read())
  2740. @with_tempfile()
  2741. @pytest.mark.slow_test(seconds=60) # Test takes >30 and <=60 seconds
  2742. def test_prepend(self, name):
  2743. """
  2744. Test blockreplace when prepend_if_not_found=True and block doesn't
  2745. exist in file.
  2746. """
  2747. expected = (
  2748. self.marker_start
  2749. + os.linesep
  2750. + self.content
  2751. + self.marker_end
  2752. + os.linesep
  2753. + self.without_block
  2754. )
  2755. # Pass 1: content ends in newline
  2756. self._write(name, self.without_block)
  2757. ret = self.run_state(
  2758. "file.blockreplace",
  2759. name=name,
  2760. content=self.content,
  2761. marker_start=self.marker_start,
  2762. marker_end=self.marker_end,
  2763. prepend_if_not_found=True,
  2764. )
  2765. self.assertSaltTrueReturn(ret)
  2766. self.assertTrue(ret[next(iter(ret))]["changes"])
  2767. self.assertEqual(self._read(name), expected)
  2768. # Pass 1a: Re-run state, no changes should be made
  2769. ret = self.run_state(
  2770. "file.blockreplace",
  2771. name=name,
  2772. content=self.content,
  2773. marker_start=self.marker_start,
  2774. marker_end=self.marker_end,
  2775. prepend_if_not_found=True,
  2776. )
  2777. self.assertSaltTrueReturn(ret)
  2778. self.assertFalse(ret[next(iter(ret))]["changes"])
  2779. self.assertEqual(self._read(name), expected)
  2780. # Pass 2: content does not end in newline
  2781. self._write(name, self.without_block)
  2782. ret = self.run_state(
  2783. "file.blockreplace",
  2784. name=name,
  2785. content=self.content.rstrip("\r\n"),
  2786. marker_start=self.marker_start,
  2787. marker_end=self.marker_end,
  2788. prepend_if_not_found=True,
  2789. )
  2790. self.assertSaltTrueReturn(ret)
  2791. self.assertTrue(ret[next(iter(ret))]["changes"])
  2792. self.assertEqual(self._read(name), expected)
  2793. # Pass 2a: Re-run state, no changes should be made
  2794. ret = self.run_state(
  2795. "file.blockreplace",
  2796. name=name,
  2797. content=self.content.rstrip("\r\n"),
  2798. marker_start=self.marker_start,
  2799. marker_end=self.marker_end,
  2800. prepend_if_not_found=True,
  2801. )
  2802. self.assertSaltTrueReturn(ret)
  2803. self.assertFalse(ret[next(iter(ret))]["changes"])
  2804. self.assertEqual(self._read(name), expected)
  2805. @with_tempfile()
  2806. @pytest.mark.slow_test(seconds=60) # Test takes >30 and <=60 seconds
  2807. def test_prepend_append_newline(self, name):
  2808. """
  2809. Test blockreplace when prepend_if_not_found=True and block doesn't
  2810. exist in file. Test with append_newline explicitly set to True.
  2811. """
  2812. # Pass 1: content ends in newline
  2813. expected = (
  2814. self.marker_start
  2815. + os.linesep
  2816. + self.content
  2817. + os.linesep
  2818. + self.marker_end
  2819. + os.linesep
  2820. + self.without_block
  2821. )
  2822. self._write(name, self.without_block)
  2823. ret = self.run_state(
  2824. "file.blockreplace",
  2825. name=name,
  2826. content=self.content,
  2827. marker_start=self.marker_start,
  2828. marker_end=self.marker_end,
  2829. prepend_if_not_found=True,
  2830. append_newline=True,
  2831. )
  2832. self.assertSaltTrueReturn(ret)
  2833. self.assertTrue(ret[next(iter(ret))]["changes"])
  2834. self.assertEqual(self._read(name), expected)
  2835. # Pass 1a: Re-run state, no changes should be made
  2836. ret = self.run_state(
  2837. "file.blockreplace",
  2838. name=name,
  2839. content=self.content,
  2840. marker_start=self.marker_start,
  2841. marker_end=self.marker_end,
  2842. prepend_if_not_found=True,
  2843. append_newline=True,
  2844. )
  2845. self.assertSaltTrueReturn(ret)
  2846. self.assertFalse(ret[next(iter(ret))]["changes"])
  2847. self.assertEqual(self._read(name), expected)
  2848. # Pass 2: content does not end in newline
  2849. expected = (
  2850. self.marker_start
  2851. + os.linesep
  2852. + self.content
  2853. + self.marker_end
  2854. + os.linesep
  2855. + self.without_block
  2856. )
  2857. self._write(name, self.without_block)
  2858. ret = self.run_state(
  2859. "file.blockreplace",
  2860. name=name,
  2861. content=self.content.rstrip("\r\n"),
  2862. marker_start=self.marker_start,
  2863. marker_end=self.marker_end,
  2864. prepend_if_not_found=True,
  2865. append_newline=True,
  2866. )
  2867. self.assertSaltTrueReturn(ret)
  2868. self.assertTrue(ret[next(iter(ret))]["changes"])
  2869. self.assertEqual(self._read(name), expected)
  2870. # Pass 2a: Re-run state, no changes should be made
  2871. ret = self.run_state(
  2872. "file.blockreplace",
  2873. name=name,
  2874. content=self.content.rstrip("\r\n"),
  2875. marker_start=self.marker_start,
  2876. marker_end=self.marker_end,
  2877. prepend_if_not_found=True,
  2878. append_newline=True,
  2879. )
  2880. self.assertSaltTrueReturn(ret)
  2881. self.assertFalse(ret[next(iter(ret))]["changes"])
  2882. self.assertEqual(self._read(name), expected)
  2883. @with_tempfile()
  2884. @pytest.mark.slow_test(seconds=60) # Test takes >30 and <=60 seconds
  2885. def test_prepend_no_append_newline(self, name):
  2886. """
  2887. Test blockreplace when prepend_if_not_found=True and block doesn't
  2888. exist in file. Test with append_newline explicitly set to False.
  2889. """
  2890. # Pass 1: content ends in newline
  2891. expected = (
  2892. self.marker_start
  2893. + os.linesep
  2894. + self.content
  2895. + self.marker_end
  2896. + os.linesep
  2897. + self.without_block
  2898. )
  2899. self._write(name, self.without_block)
  2900. ret = self.run_state(
  2901. "file.blockreplace",
  2902. name=name,
  2903. content=self.content,
  2904. marker_start=self.marker_start,
  2905. marker_end=self.marker_end,
  2906. prepend_if_not_found=True,
  2907. append_newline=False,
  2908. )
  2909. self.assertSaltTrueReturn(ret)
  2910. self.assertTrue(ret[next(iter(ret))]["changes"])
  2911. self.assertEqual(self._read(name), expected)
  2912. # Pass 1a: Re-run state, no changes should be made
  2913. ret = self.run_state(
  2914. "file.blockreplace",
  2915. name=name,
  2916. content=self.content,
  2917. marker_start=self.marker_start,
  2918. marker_end=self.marker_end,
  2919. prepend_if_not_found=True,
  2920. append_newline=False,
  2921. )
  2922. self.assertSaltTrueReturn(ret)
  2923. self.assertFalse(ret[next(iter(ret))]["changes"])
  2924. self.assertEqual(self._read(name), expected)
  2925. # Pass 2: content does not end in newline
  2926. expected = (
  2927. self.marker_start
  2928. + os.linesep
  2929. + self.content.rstrip("\r\n")
  2930. + self.marker_end
  2931. + os.linesep
  2932. + self.without_block
  2933. )
  2934. self._write(name, self.without_block)
  2935. ret = self.run_state(
  2936. "file.blockreplace",
  2937. name=name,
  2938. content=self.content.rstrip("\r\n"),
  2939. marker_start=self.marker_start,
  2940. marker_end=self.marker_end,
  2941. prepend_if_not_found=True,
  2942. append_newline=False,
  2943. )
  2944. self.assertSaltTrueReturn(ret)
  2945. self.assertTrue(ret[next(iter(ret))]["changes"])
  2946. self.assertEqual(self._read(name), expected)
  2947. # Pass 2a: Re-run state, no changes should be made
  2948. ret = self.run_state(
  2949. "file.blockreplace",
  2950. name=name,
  2951. content=self.content.rstrip("\r\n"),
  2952. marker_start=self.marker_start,
  2953. marker_end=self.marker_end,
  2954. prepend_if_not_found=True,
  2955. append_newline=False,
  2956. )
  2957. self.assertSaltTrueReturn(ret)
  2958. self.assertFalse(ret[next(iter(ret))]["changes"])
  2959. self.assertEqual(self._read(name), expected)
  2960. @with_tempfile()
  2961. @pytest.mark.slow_test(seconds=60) # Test takes >30 and <=60 seconds
  2962. def test_append(self, name):
  2963. """
  2964. Test blockreplace when append_if_not_found=True and block doesn't
  2965. exist in file.
  2966. """
  2967. expected = (
  2968. self.without_block
  2969. + self.marker_start
  2970. + os.linesep
  2971. + self.content
  2972. + self.marker_end
  2973. + os.linesep
  2974. )
  2975. # Pass 1: content ends in newline
  2976. self._write(name, self.without_block)
  2977. ret = self.run_state(
  2978. "file.blockreplace",
  2979. name=name,
  2980. content=self.content,
  2981. marker_start=self.marker_start,
  2982. marker_end=self.marker_end,
  2983. append_if_not_found=True,
  2984. )
  2985. self.assertSaltTrueReturn(ret)
  2986. self.assertTrue(ret[next(iter(ret))]["changes"])
  2987. self.assertEqual(self._read(name), expected)
  2988. # Pass 1a: Re-run state, no changes should be made
  2989. ret = self.run_state(
  2990. "file.blockreplace",
  2991. name=name,
  2992. content=self.content,
  2993. marker_start=self.marker_start,
  2994. marker_end=self.marker_end,
  2995. append_if_not_found=True,
  2996. )
  2997. self.assertSaltTrueReturn(ret)
  2998. self.assertFalse(ret[next(iter(ret))]["changes"])
  2999. self.assertEqual(self._read(name), expected)
  3000. # Pass 2: content does not end in newline
  3001. self._write(name, self.without_block)
  3002. ret = self.run_state(
  3003. "file.blockreplace",
  3004. name=name,
  3005. content=self.content.rstrip("\r\n"),
  3006. marker_start=self.marker_start,
  3007. marker_end=self.marker_end,
  3008. append_if_not_found=True,
  3009. )
  3010. self.assertSaltTrueReturn(ret)
  3011. self.assertTrue(ret[next(iter(ret))]["changes"])
  3012. self.assertEqual(self._read(name), expected)
  3013. # Pass 2a: Re-run state, no changes should be made
  3014. ret = self.run_state(
  3015. "file.blockreplace",
  3016. name=name,
  3017. content=self.content.rstrip("\r\n"),
  3018. marker_start=self.marker_start,
  3019. marker_end=self.marker_end,
  3020. append_if_not_found=True,
  3021. )
  3022. self.assertSaltTrueReturn(ret)
  3023. self.assertFalse(ret[next(iter(ret))]["changes"])
  3024. self.assertEqual(self._read(name), expected)
  3025. @with_tempfile()
  3026. @pytest.mark.slow_test(seconds=60) # Test takes >30 and <=60 seconds
  3027. def test_append_append_newline(self, name):
  3028. """
  3029. Test blockreplace when append_if_not_found=True and block doesn't
  3030. exist in file. Test with append_newline explicitly set to True.
  3031. """
  3032. # Pass 1: content ends in newline
  3033. expected = (
  3034. self.without_block
  3035. + self.marker_start
  3036. + os.linesep
  3037. + self.content
  3038. + os.linesep
  3039. + self.marker_end
  3040. + os.linesep
  3041. )
  3042. self._write(name, self.without_block)
  3043. ret = self.run_state(
  3044. "file.blockreplace",
  3045. name=name,
  3046. content=self.content,
  3047. marker_start=self.marker_start,
  3048. marker_end=self.marker_end,
  3049. append_if_not_found=True,
  3050. append_newline=True,
  3051. )
  3052. self.assertSaltTrueReturn(ret)
  3053. self.assertTrue(ret[next(iter(ret))]["changes"])
  3054. self.assertEqual(self._read(name), expected)
  3055. # Pass 1a: Re-run state, no changes should be made
  3056. ret = self.run_state(
  3057. "file.blockreplace",
  3058. name=name,
  3059. content=self.content,
  3060. marker_start=self.marker_start,
  3061. marker_end=self.marker_end,
  3062. append_if_not_found=True,
  3063. append_newline=True,
  3064. )
  3065. self.assertSaltTrueReturn(ret)
  3066. self.assertFalse(ret[next(iter(ret))]["changes"])
  3067. self.assertEqual(self._read(name), expected)
  3068. # Pass 2: content does not end in newline
  3069. expected = (
  3070. self.without_block
  3071. + self.marker_start
  3072. + os.linesep
  3073. + self.content
  3074. + self.marker_end
  3075. + os.linesep
  3076. )
  3077. self._write(name, self.without_block)
  3078. ret = self.run_state(
  3079. "file.blockreplace",
  3080. name=name,
  3081. content=self.content.rstrip("\r\n"),
  3082. marker_start=self.marker_start,
  3083. marker_end=self.marker_end,
  3084. append_if_not_found=True,
  3085. append_newline=True,
  3086. )
  3087. self.assertSaltTrueReturn(ret)
  3088. self.assertTrue(ret[next(iter(ret))]["changes"])
  3089. self.assertEqual(self._read(name), expected)
  3090. # Pass 2a: Re-run state, no changes should be made
  3091. ret = self.run_state(
  3092. "file.blockreplace",
  3093. name=name,
  3094. content=self.content.rstrip("\r\n"),
  3095. marker_start=self.marker_start,
  3096. marker_end=self.marker_end,
  3097. append_if_not_found=True,
  3098. append_newline=True,
  3099. )
  3100. self.assertSaltTrueReturn(ret)
  3101. self.assertFalse(ret[next(iter(ret))]["changes"])
  3102. self.assertEqual(self._read(name), expected)
  3103. @with_tempfile()
  3104. @pytest.mark.slow_test(seconds=60) # Test takes >30 and <=60 seconds
  3105. def test_append_no_append_newline(self, name):
  3106. """
  3107. Test blockreplace when append_if_not_found=True and block doesn't
  3108. exist in file. Test with append_newline explicitly set to False.
  3109. """
  3110. # Pass 1: content ends in newline
  3111. expected = (
  3112. self.without_block
  3113. + self.marker_start
  3114. + os.linesep
  3115. + self.content
  3116. + self.marker_end
  3117. + os.linesep
  3118. )
  3119. self._write(name, self.without_block)
  3120. ret = self.run_state(
  3121. "file.blockreplace",
  3122. name=name,
  3123. content=self.content,
  3124. marker_start=self.marker_start,
  3125. marker_end=self.marker_end,
  3126. append_if_not_found=True,
  3127. append_newline=False,
  3128. )
  3129. self.assertSaltTrueReturn(ret)
  3130. self.assertTrue(ret[next(iter(ret))]["changes"])
  3131. self.assertEqual(self._read(name), expected)
  3132. # Pass 1a: Re-run state, no changes should be made
  3133. ret = self.run_state(
  3134. "file.blockreplace",
  3135. name=name,
  3136. content=self.content,
  3137. marker_start=self.marker_start,
  3138. marker_end=self.marker_end,
  3139. append_if_not_found=True,
  3140. append_newline=False,
  3141. )
  3142. self.assertSaltTrueReturn(ret)
  3143. self.assertFalse(ret[next(iter(ret))]["changes"])
  3144. self.assertEqual(self._read(name), expected)
  3145. # Pass 2: content does not end in newline
  3146. expected = (
  3147. self.without_block
  3148. + self.marker_start
  3149. + os.linesep
  3150. + self.content.rstrip("\r\n")
  3151. + self.marker_end
  3152. + os.linesep
  3153. )
  3154. self._write(name, self.without_block)
  3155. ret = self.run_state(
  3156. "file.blockreplace",
  3157. name=name,
  3158. content=self.content.rstrip("\r\n"),
  3159. marker_start=self.marker_start,
  3160. marker_end=self.marker_end,
  3161. append_if_not_found=True,
  3162. append_newline=False,
  3163. )
  3164. self.assertSaltTrueReturn(ret)
  3165. self.assertTrue(ret[next(iter(ret))]["changes"])
  3166. self.assertEqual(self._read(name), expected)
  3167. # Pass 2a: Re-run state, no changes should be made
  3168. ret = self.run_state(
  3169. "file.blockreplace",
  3170. name=name,
  3171. content=self.content.rstrip("\r\n"),
  3172. marker_start=self.marker_start,
  3173. marker_end=self.marker_end,
  3174. append_if_not_found=True,
  3175. append_newline=False,
  3176. )
  3177. self.assertSaltTrueReturn(ret)
  3178. self.assertFalse(ret[next(iter(ret))]["changes"])
  3179. self.assertEqual(self._read(name), expected)
  3180. @with_tempfile()
  3181. @pytest.mark.slow_test(seconds=60) # Test takes >30 and <=60 seconds
  3182. def test_prepend_auto_line_separator(self, name):
  3183. """
  3184. This tests the line separator auto-detection when prepending the block
  3185. """
  3186. # POSIX newlines to Windows newlines
  3187. self._write(name, self.without_block_explicit_windows_newlines)
  3188. ret = self.run_state(
  3189. "file.blockreplace",
  3190. name=name,
  3191. content=self.content_explicit_posix_newlines,
  3192. marker_start=self.marker_start,
  3193. marker_end=self.marker_end,
  3194. prepend_if_not_found=True,
  3195. )
  3196. self.assertSaltTrueReturn(ret)
  3197. self.assertTrue(ret[next(iter(ret))]["changes"])
  3198. self.assertEqual(
  3199. self._read(name), self.with_block_prepended_explicit_windows_newlines
  3200. )
  3201. # Re-run state, no changes should be made
  3202. ret = self.run_state(
  3203. "file.blockreplace",
  3204. name=name,
  3205. content=self.content_explicit_posix_newlines,
  3206. marker_start=self.marker_start,
  3207. marker_end=self.marker_end,
  3208. prepend_if_not_found=True,
  3209. )
  3210. self.assertSaltTrueReturn(ret)
  3211. self.assertFalse(ret[next(iter(ret))]["changes"])
  3212. self.assertEqual(
  3213. self._read(name), self.with_block_prepended_explicit_windows_newlines
  3214. )
  3215. # Windows newlines to POSIX newlines
  3216. self._write(name, self.without_block_explicit_posix_newlines)
  3217. ret = self.run_state(
  3218. "file.blockreplace",
  3219. name=name,
  3220. content=self.content_explicit_windows_newlines,
  3221. marker_start=self.marker_start,
  3222. marker_end=self.marker_end,
  3223. prepend_if_not_found=True,
  3224. )
  3225. self.assertSaltTrueReturn(ret)
  3226. self.assertTrue(ret[next(iter(ret))]["changes"])
  3227. self.assertEqual(
  3228. self._read(name), self.with_block_prepended_explicit_posix_newlines
  3229. )
  3230. # Re-run state, no changes should be made
  3231. ret = self.run_state(
  3232. "file.blockreplace",
  3233. name=name,
  3234. content=self.content_explicit_windows_newlines,
  3235. marker_start=self.marker_start,
  3236. marker_end=self.marker_end,
  3237. prepend_if_not_found=True,
  3238. )
  3239. self.assertSaltTrueReturn(ret)
  3240. self.assertFalse(ret[next(iter(ret))]["changes"])
  3241. self.assertEqual(
  3242. self._read(name), self.with_block_prepended_explicit_posix_newlines
  3243. )
  3244. @with_tempfile()
  3245. @pytest.mark.slow_test(seconds=60) # Test takes >30 and <=60 seconds
  3246. def test_append_auto_line_separator(self, name):
  3247. """
  3248. This tests the line separator auto-detection when appending the block
  3249. """
  3250. # POSIX newlines to Windows newlines
  3251. self._write(name, self.without_block_explicit_windows_newlines)
  3252. ret = self.run_state(
  3253. "file.blockreplace",
  3254. name=name,
  3255. content=self.content_explicit_posix_newlines,
  3256. marker_start=self.marker_start,
  3257. marker_end=self.marker_end,
  3258. append_if_not_found=True,
  3259. )
  3260. self.assertSaltTrueReturn(ret)
  3261. self.assertTrue(ret[next(iter(ret))]["changes"])
  3262. self.assertEqual(
  3263. self._read(name), self.with_block_appended_explicit_windows_newlines
  3264. )
  3265. # Re-run state, no changes should be made
  3266. ret = self.run_state(
  3267. "file.blockreplace",
  3268. name=name,
  3269. content=self.content_explicit_posix_newlines,
  3270. marker_start=self.marker_start,
  3271. marker_end=self.marker_end,
  3272. append_if_not_found=True,
  3273. )
  3274. self.assertSaltTrueReturn(ret)
  3275. self.assertFalse(ret[next(iter(ret))]["changes"])
  3276. self.assertEqual(
  3277. self._read(name), self.with_block_appended_explicit_windows_newlines
  3278. )
  3279. # Windows newlines to POSIX newlines
  3280. self._write(name, self.without_block_explicit_posix_newlines)
  3281. ret = self.run_state(
  3282. "file.blockreplace",
  3283. name=name,
  3284. content=self.content_explicit_windows_newlines,
  3285. marker_start=self.marker_start,
  3286. marker_end=self.marker_end,
  3287. append_if_not_found=True,
  3288. )
  3289. self.assertSaltTrueReturn(ret)
  3290. self.assertTrue(ret[next(iter(ret))]["changes"])
  3291. self.assertEqual(
  3292. self._read(name), self.with_block_appended_explicit_posix_newlines
  3293. )
  3294. # Re-run state, no changes should be made
  3295. ret = self.run_state(
  3296. "file.blockreplace",
  3297. name=name,
  3298. content=self.content_explicit_windows_newlines,
  3299. marker_start=self.marker_start,
  3300. marker_end=self.marker_end,
  3301. append_if_not_found=True,
  3302. )
  3303. self.assertSaltTrueReturn(ret)
  3304. self.assertFalse(ret[next(iter(ret))]["changes"])
  3305. self.assertEqual(
  3306. self._read(name), self.with_block_appended_explicit_posix_newlines
  3307. )
  3308. @with_tempfile()
  3309. @pytest.mark.slow_test(seconds=60) # Test takes >30 and <=60 seconds
  3310. def test_non_matching_block(self, name):
  3311. """
  3312. Test blockreplace when block exists but its contents are not a
  3313. match.
  3314. """
  3315. # Pass 1: content ends in newline
  3316. self._write(name, self.with_non_matching_block)
  3317. ret = self.run_state(
  3318. "file.blockreplace",
  3319. name=name,
  3320. content=self.content,
  3321. marker_start=self.marker_start,
  3322. marker_end=self.marker_end,
  3323. )
  3324. self.assertSaltTrueReturn(ret)
  3325. self.assertTrue(ret[next(iter(ret))]["changes"])
  3326. self.assertEqual(self._read(name), self.with_matching_block)
  3327. # Pass 1a: Re-run state, no changes should be made
  3328. ret = self.run_state(
  3329. "file.blockreplace",
  3330. name=name,
  3331. content=self.content,
  3332. marker_start=self.marker_start,
  3333. marker_end=self.marker_end,
  3334. )
  3335. self.assertSaltTrueReturn(ret)
  3336. self.assertFalse(ret[next(iter(ret))]["changes"])
  3337. self.assertEqual(self._read(name), self.with_matching_block)
  3338. # Pass 2: content does not end in newline
  3339. self._write(name, self.with_non_matching_block)
  3340. ret = self.run_state(
  3341. "file.blockreplace",
  3342. name=name,
  3343. content=self.content.rstrip("\r\n"),
  3344. marker_start=self.marker_start,
  3345. marker_end=self.marker_end,
  3346. )
  3347. self.assertSaltTrueReturn(ret)
  3348. self.assertTrue(ret[next(iter(ret))]["changes"])
  3349. self.assertEqual(self._read(name), self.with_matching_block)
  3350. # Pass 2a: Re-run state, no changes should be made
  3351. ret = self.run_state(
  3352. "file.blockreplace",
  3353. name=name,
  3354. content=self.content.rstrip("\r\n"),
  3355. marker_start=self.marker_start,
  3356. marker_end=self.marker_end,
  3357. )
  3358. self.assertSaltTrueReturn(ret)
  3359. self.assertFalse(ret[next(iter(ret))]["changes"])
  3360. self.assertEqual(self._read(name), self.with_matching_block)
  3361. @with_tempfile()
  3362. @pytest.mark.slow_test(seconds=60) # Test takes >30 and <=60 seconds
  3363. def test_non_matching_block_append_newline(self, name):
  3364. """
  3365. Test blockreplace when block exists but its contents are not a
  3366. match. Test with append_newline explicitly set to True.
  3367. """
  3368. # Pass 1: content ends in newline
  3369. self._write(name, self.with_non_matching_block)
  3370. ret = self.run_state(
  3371. "file.blockreplace",
  3372. name=name,
  3373. content=self.content,
  3374. marker_start=self.marker_start,
  3375. marker_end=self.marker_end,
  3376. append_newline=True,
  3377. )
  3378. self.assertSaltTrueReturn(ret)
  3379. self.assertTrue(ret[next(iter(ret))]["changes"])
  3380. self.assertEqual(self._read(name), self.with_matching_block_and_extra_newline)
  3381. # Pass 1a: Re-run state, no changes should be made
  3382. ret = self.run_state(
  3383. "file.blockreplace",
  3384. name=name,
  3385. content=self.content,
  3386. marker_start=self.marker_start,
  3387. marker_end=self.marker_end,
  3388. append_newline=True,
  3389. )
  3390. self.assertSaltTrueReturn(ret)
  3391. self.assertFalse(ret[next(iter(ret))]["changes"])
  3392. self.assertEqual(self._read(name), self.with_matching_block_and_extra_newline)
  3393. # Pass 2: content does not end in newline
  3394. self._write(name, self.with_non_matching_block)
  3395. ret = self.run_state(
  3396. "file.blockreplace",
  3397. name=name,
  3398. content=self.content.rstrip("\r\n"),
  3399. marker_start=self.marker_start,
  3400. marker_end=self.marker_end,
  3401. append_newline=True,
  3402. )
  3403. self.assertSaltTrueReturn(ret)
  3404. self.assertTrue(ret[next(iter(ret))]["changes"])
  3405. self.assertEqual(self._read(name), self.with_matching_block)
  3406. # Pass 2a: Re-run state, no changes should be made
  3407. ret = self.run_state(
  3408. "file.blockreplace",
  3409. name=name,
  3410. content=self.content.rstrip("\r\n"),
  3411. marker_start=self.marker_start,
  3412. marker_end=self.marker_end,
  3413. append_newline=True,
  3414. )
  3415. self.assertSaltTrueReturn(ret)
  3416. self.assertFalse(ret[next(iter(ret))]["changes"])
  3417. self.assertEqual(self._read(name), self.with_matching_block)
  3418. @with_tempfile()
  3419. @pytest.mark.slow_test(seconds=60) # Test takes >30 and <=60 seconds
  3420. def test_non_matching_block_no_append_newline(self, name):
  3421. """
  3422. Test blockreplace when block exists but its contents are not a
  3423. match. Test with append_newline explicitly set to False.
  3424. """
  3425. # Pass 1: content ends in newline
  3426. self._write(name, self.with_non_matching_block)
  3427. ret = self.run_state(
  3428. "file.blockreplace",
  3429. name=name,
  3430. content=self.content,
  3431. marker_start=self.marker_start,
  3432. marker_end=self.marker_end,
  3433. append_newline=False,
  3434. )
  3435. self.assertSaltTrueReturn(ret)
  3436. self.assertTrue(ret[next(iter(ret))]["changes"])
  3437. self.assertEqual(self._read(name), self.with_matching_block)
  3438. # Pass 1a: Re-run state, no changes should be made
  3439. ret = self.run_state(
  3440. "file.blockreplace",
  3441. name=name,
  3442. content=self.content,
  3443. marker_start=self.marker_start,
  3444. marker_end=self.marker_end,
  3445. append_newline=False,
  3446. )
  3447. self.assertSaltTrueReturn(ret)
  3448. self.assertFalse(ret[next(iter(ret))]["changes"])
  3449. self.assertEqual(self._read(name), self.with_matching_block)
  3450. # Pass 2: content does not end in newline
  3451. self._write(name, self.with_non_matching_block)
  3452. ret = self.run_state(
  3453. "file.blockreplace",
  3454. name=name,
  3455. content=self.content.rstrip("\r\n"),
  3456. marker_start=self.marker_start,
  3457. marker_end=self.marker_end,
  3458. append_newline=False,
  3459. )
  3460. self.assertSaltTrueReturn(ret)
  3461. self.assertTrue(ret[next(iter(ret))]["changes"])
  3462. self.assertEqual(
  3463. self._read(name), self.with_matching_block_and_marker_end_not_after_newline
  3464. )
  3465. # Pass 2a: Re-run state, no changes should be made
  3466. ret = self.run_state(
  3467. "file.blockreplace",
  3468. name=name,
  3469. content=self.content.rstrip("\r\n"),
  3470. marker_start=self.marker_start,
  3471. marker_end=self.marker_end,
  3472. append_newline=False,
  3473. )
  3474. self.assertSaltTrueReturn(ret)
  3475. self.assertFalse(ret[next(iter(ret))]["changes"])
  3476. self.assertEqual(
  3477. self._read(name), self.with_matching_block_and_marker_end_not_after_newline
  3478. )
  3479. @with_tempfile()
  3480. @pytest.mark.slow_test(seconds=60) # Test takes >30 and <=60 seconds
  3481. def test_non_matching_block_and_marker_not_after_newline(self, name):
  3482. """
  3483. Test blockreplace when block exists but its contents are not a
  3484. match, and the marker_end is not directly preceded by a newline.
  3485. """
  3486. # Pass 1: content ends in newline
  3487. self._write(name, self.with_non_matching_block_and_marker_end_not_after_newline)
  3488. ret = self.run_state(
  3489. "file.blockreplace",
  3490. name=name,
  3491. content=self.content,
  3492. marker_start=self.marker_start,
  3493. marker_end=self.marker_end,
  3494. )
  3495. self.assertSaltTrueReturn(ret)
  3496. self.assertTrue(ret[next(iter(ret))]["changes"])
  3497. self.assertEqual(self._read(name), self.with_matching_block)
  3498. # Pass 1a: Re-run state, no changes should be made
  3499. ret = self.run_state(
  3500. "file.blockreplace",
  3501. name=name,
  3502. content=self.content,
  3503. marker_start=self.marker_start,
  3504. marker_end=self.marker_end,
  3505. )
  3506. self.assertSaltTrueReturn(ret)
  3507. self.assertFalse(ret[next(iter(ret))]["changes"])
  3508. self.assertEqual(self._read(name), self.with_matching_block)
  3509. # Pass 2: content does not end in newline
  3510. self._write(name, self.with_non_matching_block_and_marker_end_not_after_newline)
  3511. ret = self.run_state(
  3512. "file.blockreplace",
  3513. name=name,
  3514. content=self.content.rstrip("\r\n"),
  3515. marker_start=self.marker_start,
  3516. marker_end=self.marker_end,
  3517. )
  3518. self.assertSaltTrueReturn(ret)
  3519. self.assertTrue(ret[next(iter(ret))]["changes"])
  3520. self.assertEqual(self._read(name), self.with_matching_block)
  3521. # Pass 2a: Re-run state, no changes should be made
  3522. ret = self.run_state(
  3523. "file.blockreplace",
  3524. name=name,
  3525. content=self.content.rstrip("\r\n"),
  3526. marker_start=self.marker_start,
  3527. marker_end=self.marker_end,
  3528. )
  3529. self.assertSaltTrueReturn(ret)
  3530. self.assertFalse(ret[next(iter(ret))]["changes"])
  3531. self.assertEqual(self._read(name), self.with_matching_block)
  3532. @with_tempfile()
  3533. @pytest.mark.slow_test(seconds=60) # Test takes >30 and <=60 seconds
  3534. def test_non_matching_block_and_marker_not_after_newline_append_newline(self, name):
  3535. """
  3536. Test blockreplace when block exists but its contents are not a match,
  3537. and the marker_end is not directly preceded by a newline. Test with
  3538. append_newline explicitly set to True.
  3539. """
  3540. # Pass 1: content ends in newline
  3541. self._write(name, self.with_non_matching_block_and_marker_end_not_after_newline)
  3542. ret = self.run_state(
  3543. "file.blockreplace",
  3544. name=name,
  3545. content=self.content,
  3546. marker_start=self.marker_start,
  3547. marker_end=self.marker_end,
  3548. append_newline=True,
  3549. )
  3550. self.assertSaltTrueReturn(ret)
  3551. self.assertTrue(ret[next(iter(ret))]["changes"])
  3552. self.assertEqual(self._read(name), self.with_matching_block_and_extra_newline)
  3553. # Pass 1a: Re-run state, no changes should be made
  3554. ret = self.run_state(
  3555. "file.blockreplace",
  3556. name=name,
  3557. content=self.content,
  3558. marker_start=self.marker_start,
  3559. marker_end=self.marker_end,
  3560. append_newline=True,
  3561. )
  3562. self.assertSaltTrueReturn(ret)
  3563. self.assertFalse(ret[next(iter(ret))]["changes"])
  3564. self.assertEqual(self._read(name), self.with_matching_block_and_extra_newline)
  3565. # Pass 2: content does not end in newline
  3566. self._write(name, self.with_non_matching_block_and_marker_end_not_after_newline)
  3567. ret = self.run_state(
  3568. "file.blockreplace",
  3569. name=name,
  3570. content=self.content.rstrip("\r\n"),
  3571. marker_start=self.marker_start,
  3572. marker_end=self.marker_end,
  3573. append_newline=True,
  3574. )
  3575. self.assertSaltTrueReturn(ret)
  3576. self.assertTrue(ret[next(iter(ret))]["changes"])
  3577. self.assertEqual(self._read(name), self.with_matching_block)
  3578. # Pass 2a: Re-run state, no changes should be made
  3579. ret = self.run_state(
  3580. "file.blockreplace",
  3581. name=name,
  3582. content=self.content.rstrip("\r\n"),
  3583. marker_start=self.marker_start,
  3584. marker_end=self.marker_end,
  3585. append_newline=True,
  3586. )
  3587. self.assertSaltTrueReturn(ret)
  3588. self.assertFalse(ret[next(iter(ret))]["changes"])
  3589. self.assertEqual(self._read(name), self.with_matching_block)
  3590. @with_tempfile()
  3591. @pytest.mark.slow_test(seconds=60) # Test takes >30 and <=60 seconds
  3592. def test_non_matching_block_and_marker_not_after_newline_no_append_newline(
  3593. self, name
  3594. ):
  3595. """
  3596. Test blockreplace when block exists but its contents are not a match,
  3597. and the marker_end is not directly preceded by a newline. Test with
  3598. append_newline explicitly set to False.
  3599. """
  3600. # Pass 1: content ends in newline
  3601. self._write(name, self.with_non_matching_block_and_marker_end_not_after_newline)
  3602. ret = self.run_state(
  3603. "file.blockreplace",
  3604. name=name,
  3605. content=self.content,
  3606. marker_start=self.marker_start,
  3607. marker_end=self.marker_end,
  3608. append_newline=False,
  3609. )
  3610. self.assertSaltTrueReturn(ret)
  3611. self.assertTrue(ret[next(iter(ret))]["changes"])
  3612. self.assertEqual(self._read(name), self.with_matching_block)
  3613. # Pass 1a: Re-run state, no changes should be made
  3614. ret = self.run_state(
  3615. "file.blockreplace",
  3616. name=name,
  3617. content=self.content,
  3618. marker_start=self.marker_start,
  3619. marker_end=self.marker_end,
  3620. append_newline=False,
  3621. )
  3622. self.assertSaltTrueReturn(ret)
  3623. self.assertFalse(ret[next(iter(ret))]["changes"])
  3624. self.assertEqual(self._read(name), self.with_matching_block)
  3625. # Pass 2: content does not end in newline
  3626. self._write(name, self.with_non_matching_block_and_marker_end_not_after_newline)
  3627. ret = self.run_state(
  3628. "file.blockreplace",
  3629. name=name,
  3630. content=self.content.rstrip("\r\n"),
  3631. marker_start=self.marker_start,
  3632. marker_end=self.marker_end,
  3633. append_newline=False,
  3634. )
  3635. self.assertSaltTrueReturn(ret)
  3636. self.assertTrue(ret[next(iter(ret))]["changes"])
  3637. self.assertEqual(
  3638. self._read(name), self.with_matching_block_and_marker_end_not_after_newline
  3639. )
  3640. # Pass 2a: Re-run state, no changes should be made
  3641. ret = self.run_state(
  3642. "file.blockreplace",
  3643. name=name,
  3644. content=self.content.rstrip("\r\n"),
  3645. marker_start=self.marker_start,
  3646. marker_end=self.marker_end,
  3647. append_newline=False,
  3648. )
  3649. self.assertSaltTrueReturn(ret)
  3650. self.assertFalse(ret[next(iter(ret))]["changes"])
  3651. self.assertEqual(
  3652. self._read(name), self.with_matching_block_and_marker_end_not_after_newline
  3653. )
  3654. @with_tempfile()
  3655. @pytest.mark.slow_test(seconds=60) # Test takes >30 and <=60 seconds
  3656. def test_matching_block(self, name):
  3657. """
  3658. Test blockreplace when block exists and its contents are a match. No
  3659. changes should be made.
  3660. """
  3661. # Pass 1: content ends in newline
  3662. self._write(name, self.with_matching_block)
  3663. ret = self.run_state(
  3664. "file.blockreplace",
  3665. name=name,
  3666. content=self.content,
  3667. marker_start=self.marker_start,
  3668. marker_end=self.marker_end,
  3669. )
  3670. self.assertSaltTrueReturn(ret)
  3671. self.assertFalse(ret[next(iter(ret))]["changes"])
  3672. self.assertEqual(self._read(name), self.with_matching_block)
  3673. # Pass 1a: Re-run state, no changes should be made
  3674. ret = self.run_state(
  3675. "file.blockreplace",
  3676. name=name,
  3677. content=self.content,
  3678. marker_start=self.marker_start,
  3679. marker_end=self.marker_end,
  3680. )
  3681. self.assertSaltTrueReturn(ret)
  3682. self.assertFalse(ret[next(iter(ret))]["changes"])
  3683. self.assertEqual(self._read(name), self.with_matching_block)
  3684. # Pass 2: content does not end in newline
  3685. self._write(name, self.with_matching_block)
  3686. ret = self.run_state(
  3687. "file.blockreplace",
  3688. name=name,
  3689. content=self.content.rstrip("\r\n"),
  3690. marker_start=self.marker_start,
  3691. marker_end=self.marker_end,
  3692. )
  3693. self.assertSaltTrueReturn(ret)
  3694. self.assertFalse(ret[next(iter(ret))]["changes"])
  3695. self.assertEqual(self._read(name), self.with_matching_block)
  3696. # Pass 2a: Re-run state, no changes should be made
  3697. ret = self.run_state(
  3698. "file.blockreplace",
  3699. name=name,
  3700. content=self.content.rstrip("\r\n"),
  3701. marker_start=self.marker_start,
  3702. marker_end=self.marker_end,
  3703. )
  3704. self.assertSaltTrueReturn(ret)
  3705. self.assertFalse(ret[next(iter(ret))]["changes"])
  3706. self.assertEqual(self._read(name), self.with_matching_block)
  3707. @with_tempfile()
  3708. @pytest.mark.slow_test(seconds=60) # Test takes >30 and <=60 seconds
  3709. def test_matching_block_append_newline(self, name):
  3710. """
  3711. Test blockreplace when block exists and its contents are a match. Test
  3712. with append_newline explicitly set to True. This will result in an
  3713. extra newline when the content ends in a newline, and will not when the
  3714. content does not end in a newline.
  3715. """
  3716. # Pass 1: content ends in newline
  3717. self._write(name, self.with_matching_block)
  3718. ret = self.run_state(
  3719. "file.blockreplace",
  3720. name=name,
  3721. content=self.content,
  3722. marker_start=self.marker_start,
  3723. marker_end=self.marker_end,
  3724. append_newline=True,
  3725. )
  3726. self.assertSaltTrueReturn(ret)
  3727. self.assertTrue(ret[next(iter(ret))]["changes"])
  3728. self.assertEqual(self._read(name), self.with_matching_block_and_extra_newline)
  3729. # Pass 1a: Re-run state, no changes should be made
  3730. ret = self.run_state(
  3731. "file.blockreplace",
  3732. name=name,
  3733. content=self.content,
  3734. marker_start=self.marker_start,
  3735. marker_end=self.marker_end,
  3736. append_newline=True,
  3737. )
  3738. self.assertSaltTrueReturn(ret)
  3739. self.assertFalse(ret[next(iter(ret))]["changes"])
  3740. self.assertEqual(self._read(name), self.with_matching_block_and_extra_newline)
  3741. # Pass 2: content does not end in newline
  3742. self._write(name, self.with_matching_block)
  3743. ret = self.run_state(
  3744. "file.blockreplace",
  3745. name=name,
  3746. content=self.content.rstrip("\r\n"),
  3747. marker_start=self.marker_start,
  3748. marker_end=self.marker_end,
  3749. append_newline=True,
  3750. )
  3751. self.assertSaltTrueReturn(ret)
  3752. self.assertFalse(ret[next(iter(ret))]["changes"])
  3753. self.assertEqual(self._read(name), self.with_matching_block)
  3754. # Pass 2a: Re-run state, no changes should be made
  3755. ret = self.run_state(
  3756. "file.blockreplace",
  3757. name=name,
  3758. content=self.content.rstrip("\r\n"),
  3759. marker_start=self.marker_start,
  3760. marker_end=self.marker_end,
  3761. append_newline=True,
  3762. )
  3763. self.assertSaltTrueReturn(ret)
  3764. self.assertFalse(ret[next(iter(ret))]["changes"])
  3765. self.assertEqual(self._read(name), self.with_matching_block)
  3766. @with_tempfile()
  3767. @pytest.mark.slow_test(seconds=60) # Test takes >30 and <=60 seconds
  3768. def test_matching_block_no_append_newline(self, name):
  3769. """
  3770. Test blockreplace when block exists and its contents are a match. Test
  3771. with append_newline explicitly set to False. This will result in the
  3772. marker_end not being directly preceded by a newline when the content
  3773. does not end in a newline.
  3774. """
  3775. # Pass 1: content ends in newline
  3776. self._write(name, self.with_matching_block)
  3777. ret = self.run_state(
  3778. "file.blockreplace",
  3779. name=name,
  3780. content=self.content,
  3781. marker_start=self.marker_start,
  3782. marker_end=self.marker_end,
  3783. append_newline=False,
  3784. )
  3785. self.assertSaltTrueReturn(ret)
  3786. self.assertFalse(ret[next(iter(ret))]["changes"])
  3787. self.assertEqual(self._read(name), self.with_matching_block)
  3788. # Pass 1a: Re-run state, no changes should be made
  3789. ret = self.run_state(
  3790. "file.blockreplace",
  3791. name=name,
  3792. content=self.content,
  3793. marker_start=self.marker_start,
  3794. marker_end=self.marker_end,
  3795. append_newline=False,
  3796. )
  3797. self.assertSaltTrueReturn(ret)
  3798. self.assertFalse(ret[next(iter(ret))]["changes"])
  3799. self.assertEqual(self._read(name), self.with_matching_block)
  3800. # Pass 2: content does not end in newline
  3801. self._write(name, self.with_matching_block)
  3802. ret = self.run_state(
  3803. "file.blockreplace",
  3804. name=name,
  3805. content=self.content.rstrip("\r\n"),
  3806. marker_start=self.marker_start,
  3807. marker_end=self.marker_end,
  3808. append_newline=False,
  3809. )
  3810. self.assertSaltTrueReturn(ret)
  3811. self.assertTrue(ret[next(iter(ret))]["changes"])
  3812. self.assertEqual(
  3813. self._read(name), self.with_matching_block_and_marker_end_not_after_newline
  3814. )
  3815. # Pass 2a: Re-run state, no changes should be made
  3816. ret = self.run_state(
  3817. "file.blockreplace",
  3818. name=name,
  3819. content=self.content.rstrip("\r\n"),
  3820. marker_start=self.marker_start,
  3821. marker_end=self.marker_end,
  3822. append_newline=False,
  3823. )
  3824. self.assertSaltTrueReturn(ret)
  3825. self.assertFalse(ret[next(iter(ret))]["changes"])
  3826. self.assertEqual(
  3827. self._read(name), self.with_matching_block_and_marker_end_not_after_newline
  3828. )
  3829. @with_tempfile()
  3830. @pytest.mark.slow_test(seconds=60) # Test takes >30 and <=60 seconds
  3831. def test_matching_block_and_marker_not_after_newline(self, name):
  3832. """
  3833. Test blockreplace when block exists and its contents are a match, but
  3834. the marker_end is not directly preceded by a newline.
  3835. """
  3836. # Pass 1: content ends in newline
  3837. self._write(name, self.with_matching_block_and_marker_end_not_after_newline)
  3838. ret = self.run_state(
  3839. "file.blockreplace",
  3840. name=name,
  3841. content=self.content,
  3842. marker_start=self.marker_start,
  3843. marker_end=self.marker_end,
  3844. )
  3845. self.assertSaltTrueReturn(ret)
  3846. self.assertTrue(ret[next(iter(ret))]["changes"])
  3847. self.assertEqual(self._read(name), self.with_matching_block)
  3848. # Pass 1a: Re-run state, no changes should be made
  3849. ret = self.run_state(
  3850. "file.blockreplace",
  3851. name=name,
  3852. content=self.content,
  3853. marker_start=self.marker_start,
  3854. marker_end=self.marker_end,
  3855. )
  3856. self.assertSaltTrueReturn(ret)
  3857. self.assertFalse(ret[next(iter(ret))]["changes"])
  3858. self.assertEqual(self._read(name), self.with_matching_block)
  3859. # Pass 2: content does not end in newline
  3860. self._write(name, self.with_matching_block_and_marker_end_not_after_newline)
  3861. ret = self.run_state(
  3862. "file.blockreplace",
  3863. name=name,
  3864. content=self.content.rstrip("\r\n"),
  3865. marker_start=self.marker_start,
  3866. marker_end=self.marker_end,
  3867. )
  3868. self.assertSaltTrueReturn(ret)
  3869. self.assertTrue(ret[next(iter(ret))]["changes"])
  3870. self.assertEqual(self._read(name), self.with_matching_block)
  3871. # Pass 2a: Re-run state, no changes should be made
  3872. ret = self.run_state(
  3873. "file.blockreplace",
  3874. name=name,
  3875. content=self.content.rstrip("\r\n"),
  3876. marker_start=self.marker_start,
  3877. marker_end=self.marker_end,
  3878. )
  3879. self.assertSaltTrueReturn(ret)
  3880. self.assertFalse(ret[next(iter(ret))]["changes"])
  3881. self.assertEqual(self._read(name), self.with_matching_block)
  3882. @with_tempfile()
  3883. @pytest.mark.slow_test(seconds=60) # Test takes >30 and <=60 seconds
  3884. def test_matching_block_and_marker_not_after_newline_append_newline(self, name):
  3885. """
  3886. Test blockreplace when block exists and its contents are a match, but
  3887. the marker_end is not directly preceded by a newline. Test with
  3888. append_newline explicitly set to True. This will result in an extra
  3889. newline when the content ends in a newline, and will not when the
  3890. content does not end in a newline.
  3891. """
  3892. # Pass 1: content ends in newline
  3893. self._write(name, self.with_matching_block_and_marker_end_not_after_newline)
  3894. ret = self.run_state(
  3895. "file.blockreplace",
  3896. name=name,
  3897. content=self.content,
  3898. marker_start=self.marker_start,
  3899. marker_end=self.marker_end,
  3900. append_newline=True,
  3901. )
  3902. self.assertSaltTrueReturn(ret)
  3903. self.assertTrue(ret[next(iter(ret))]["changes"])
  3904. self.assertEqual(self._read(name), self.with_matching_block_and_extra_newline)
  3905. # Pass 1a: Re-run state, no changes should be made
  3906. ret = self.run_state(
  3907. "file.blockreplace",
  3908. name=name,
  3909. content=self.content,
  3910. marker_start=self.marker_start,
  3911. marker_end=self.marker_end,
  3912. append_newline=True,
  3913. )
  3914. self.assertSaltTrueReturn(ret)
  3915. self.assertFalse(ret[next(iter(ret))]["changes"])
  3916. self.assertEqual(self._read(name), self.with_matching_block_and_extra_newline)
  3917. # Pass 2: content does not end in newline
  3918. self._write(name, self.with_matching_block_and_marker_end_not_after_newline)
  3919. ret = self.run_state(
  3920. "file.blockreplace",
  3921. name=name,
  3922. content=self.content.rstrip("\r\n"),
  3923. marker_start=self.marker_start,
  3924. marker_end=self.marker_end,
  3925. append_newline=True,
  3926. )
  3927. self.assertSaltTrueReturn(ret)
  3928. self.assertTrue(ret[next(iter(ret))]["changes"])
  3929. self.assertEqual(self._read(name), self.with_matching_block)
  3930. # Pass 2a: Re-run state, no changes should be made
  3931. ret = self.run_state(
  3932. "file.blockreplace",
  3933. name=name,
  3934. content=self.content.rstrip("\r\n"),
  3935. marker_start=self.marker_start,
  3936. marker_end=self.marker_end,
  3937. append_newline=True,
  3938. )
  3939. self.assertSaltTrueReturn(ret)
  3940. self.assertFalse(ret[next(iter(ret))]["changes"])
  3941. self.assertEqual(self._read(name), self.with_matching_block)
  3942. @with_tempfile()
  3943. @pytest.mark.slow_test(seconds=60) # Test takes >30 and <=60 seconds
  3944. def test_matching_block_and_marker_not_after_newline_no_append_newline(self, name):
  3945. """
  3946. Test blockreplace when block exists and its contents are a match, but
  3947. the marker_end is not directly preceded by a newline. Test with
  3948. append_newline explicitly set to False.
  3949. """
  3950. # Pass 1: content ends in newline
  3951. self._write(name, self.with_matching_block_and_marker_end_not_after_newline)
  3952. ret = self.run_state(
  3953. "file.blockreplace",
  3954. name=name,
  3955. content=self.content,
  3956. marker_start=self.marker_start,
  3957. marker_end=self.marker_end,
  3958. append_newline=False,
  3959. )
  3960. self.assertSaltTrueReturn(ret)
  3961. self.assertTrue(ret[next(iter(ret))]["changes"])
  3962. self.assertEqual(self._read(name), self.with_matching_block)
  3963. # Pass 1a: Re-run state, no changes should be made
  3964. ret = self.run_state(
  3965. "file.blockreplace",
  3966. name=name,
  3967. content=self.content,
  3968. marker_start=self.marker_start,
  3969. marker_end=self.marker_end,
  3970. append_newline=False,
  3971. )
  3972. self.assertSaltTrueReturn(ret)
  3973. self.assertFalse(ret[next(iter(ret))]["changes"])
  3974. self.assertEqual(self._read(name), self.with_matching_block)
  3975. # Pass 2: content does not end in newline
  3976. self._write(name, self.with_matching_block_and_marker_end_not_after_newline)
  3977. ret = self.run_state(
  3978. "file.blockreplace",
  3979. name=name,
  3980. content=self.content.rstrip("\r\n"),
  3981. marker_start=self.marker_start,
  3982. marker_end=self.marker_end,
  3983. append_newline=False,
  3984. )
  3985. self.assertSaltTrueReturn(ret)
  3986. self.assertFalse(ret[next(iter(ret))]["changes"])
  3987. self.assertEqual(
  3988. self._read(name), self.with_matching_block_and_marker_end_not_after_newline
  3989. )
  3990. # Pass 2a: Re-run state, no changes should be made
  3991. ret = self.run_state(
  3992. "file.blockreplace",
  3993. name=name,
  3994. content=self.content.rstrip("\r\n"),
  3995. marker_start=self.marker_start,
  3996. marker_end=self.marker_end,
  3997. append_newline=False,
  3998. )
  3999. self.assertSaltTrueReturn(ret)
  4000. self.assertFalse(ret[next(iter(ret))]["changes"])
  4001. self.assertEqual(
  4002. self._read(name), self.with_matching_block_and_marker_end_not_after_newline
  4003. )
  4004. @with_tempfile()
  4005. @pytest.mark.slow_test(seconds=30) # Test takes >10 and <=30 seconds
  4006. def test_issue_49043(self, name):
  4007. ret = self.run_function("state.sls", mods="issue-49043", pillar={"name": name},)
  4008. log.error("ret = %s", repr(ret))
  4009. diff = "--- \n+++ \n@@ -0,0 +1,3 @@\n"
  4010. diff += dedent(
  4011. """\
  4012. +#-- start managed zone --
  4013. +äöü
  4014. +#-- end managed zone --
  4015. """
  4016. )
  4017. job = "file_|-somefile-blockreplace_|-{}_|-blockreplace".format(name)
  4018. self.assertEqual(ret[job]["changes"]["diff"], diff)
  4019. @pytest.mark.windows_whitelisted
  4020. class RemoteFileTest(ModuleCase, SaltReturnAssertsMixin):
  4021. """
  4022. Uses a local tornado webserver to test http(s) file.managed states with and
  4023. without skip_verify
  4024. """
  4025. @classmethod
  4026. def setUpClass(cls):
  4027. cls.webserver = Webserver()
  4028. cls.webserver.start()
  4029. cls.source = cls.webserver.url("grail/scene33")
  4030. if IS_WINDOWS:
  4031. # CRLF vs LF causes a different hash on windows
  4032. cls.source_hash = "21438b3d5fd2c0028bcab92f7824dc69"
  4033. else:
  4034. cls.source_hash = "d2feb3beb323c79fc7a0f44f1408b4a3"
  4035. @classmethod
  4036. def tearDownClass(cls):
  4037. cls.webserver.stop()
  4038. @with_tempfile(create=False)
  4039. def setUp(self, name): # pylint: disable=arguments-differ
  4040. self.name = name
  4041. def tearDown(self):
  4042. try:
  4043. os.remove(self.name)
  4044. except OSError as exc:
  4045. if exc.errno != errno.ENOENT:
  4046. six.reraise(*sys.exc_info())
  4047. def run_state(self, *args, **kwargs): # pylint: disable=arguments-differ
  4048. ret = super(RemoteFileTest, self).run_state(*args, **kwargs)
  4049. log.debug("ret = %s", ret)
  4050. return ret
  4051. @pytest.mark.slow_test(seconds=30) # Test takes >10 and <=30 seconds
  4052. def test_file_managed_http_source_no_hash(self):
  4053. """
  4054. Test a remote file with no hash
  4055. """
  4056. ret = self.run_state(
  4057. "file.managed", name=self.name, source=self.source, skip_verify=False
  4058. )
  4059. # This should fail because no hash was provided
  4060. self.assertSaltFalseReturn(ret)
  4061. @pytest.mark.slow_test(seconds=30) # Test takes >10 and <=30 seconds
  4062. def test_file_managed_http_source(self):
  4063. """
  4064. Test a remote file with no hash
  4065. """
  4066. ret = self.run_state(
  4067. "file.managed",
  4068. name=self.name,
  4069. source=self.source,
  4070. source_hash=self.source_hash,
  4071. skip_verify=False,
  4072. )
  4073. self.assertSaltTrueReturn(ret)
  4074. @pytest.mark.slow_test(seconds=30) # Test takes >10 and <=30 seconds
  4075. def test_file_managed_http_source_skip_verify(self):
  4076. """
  4077. Test a remote file using skip_verify
  4078. """
  4079. ret = self.run_state(
  4080. "file.managed", name=self.name, source=self.source, skip_verify=True
  4081. )
  4082. self.assertSaltTrueReturn(ret)
  4083. @pytest.mark.slow_test(seconds=30) # Test takes >10 and <=30 seconds
  4084. def test_file_managed_keep_source_false_http(self):
  4085. """
  4086. This test ensures that we properly clean the cached file if keep_source
  4087. is set to False, for source files using an http:// URL
  4088. """
  4089. # Run the state
  4090. ret = self.run_state(
  4091. "file.managed",
  4092. name=self.name,
  4093. source=self.source,
  4094. source_hash=self.source_hash,
  4095. keep_source=False,
  4096. )
  4097. ret = ret[next(iter(ret))]
  4098. assert ret["result"] is True
  4099. # Now make sure that the file is not cached
  4100. result = self.run_function("cp.is_cached", [self.source])
  4101. assert result == "", "File is still cached at {0}".format(result)
  4102. @skipIf(not salt.utils.path.which("patch"), "patch is not installed")
  4103. @pytest.mark.windows_whitelisted
  4104. class PatchTest(ModuleCase, SaltReturnAssertsMixin):
  4105. def _check_patch_version(self, min_version):
  4106. """
  4107. patch version check
  4108. """
  4109. version = self.run_function("cmd.run", ["patch --version"]).splitlines()[0]
  4110. version = version.split()[1]
  4111. if _LooseVersion(version) < _LooseVersion(min_version):
  4112. self.skipTest(
  4113. "Minimum patch version required: {0}. "
  4114. "Patch version installed: {1}".format(min_version, version)
  4115. )
  4116. @classmethod
  4117. def setUpClass(cls):
  4118. cls.webserver = Webserver()
  4119. cls.webserver.start()
  4120. cls.numbers_patch_name = "numbers.patch"
  4121. cls.math_patch_name = "math.patch"
  4122. cls.all_patch_name = "all.patch"
  4123. cls.numbers_patch_template_name = cls.numbers_patch_name + ".jinja"
  4124. cls.math_patch_template_name = cls.math_patch_name + ".jinja"
  4125. cls.all_patch_template_name = cls.all_patch_name + ".jinja"
  4126. cls.numbers_patch_path = "patches/" + cls.numbers_patch_name
  4127. cls.math_patch_path = "patches/" + cls.math_patch_name
  4128. cls.all_patch_path = "patches/" + cls.all_patch_name
  4129. cls.numbers_patch_template_path = "patches/" + cls.numbers_patch_template_name
  4130. cls.math_patch_template_path = "patches/" + cls.math_patch_template_name
  4131. cls.all_patch_template_path = "patches/" + cls.all_patch_template_name
  4132. cls.numbers_patch = "salt://" + cls.numbers_patch_path
  4133. cls.math_patch = "salt://" + cls.math_patch_path
  4134. cls.all_patch = "salt://" + cls.all_patch_path
  4135. cls.numbers_patch_template = "salt://" + cls.numbers_patch_template_path
  4136. cls.math_patch_template = "salt://" + cls.math_patch_template_path
  4137. cls.all_patch_template = "salt://" + cls.all_patch_template_path
  4138. cls.numbers_patch_http = cls.webserver.url(cls.numbers_patch_path)
  4139. cls.math_patch_http = cls.webserver.url(cls.math_patch_path)
  4140. cls.all_patch_http = cls.webserver.url(cls.all_patch_path)
  4141. cls.numbers_patch_template_http = cls.webserver.url(
  4142. cls.numbers_patch_template_path
  4143. )
  4144. cls.math_patch_template_http = cls.webserver.url(cls.math_patch_template_path)
  4145. cls.all_patch_template_http = cls.webserver.url(cls.all_patch_template_path)
  4146. patches_dir = os.path.join(RUNTIME_VARS.FILES, "file", "base", "patches")
  4147. cls.numbers_patch_hash = salt.utils.hashutils.get_hash(
  4148. os.path.join(patches_dir, cls.numbers_patch_name)
  4149. )
  4150. cls.math_patch_hash = salt.utils.hashutils.get_hash(
  4151. os.path.join(patches_dir, cls.math_patch_name)
  4152. )
  4153. cls.all_patch_hash = salt.utils.hashutils.get_hash(
  4154. os.path.join(patches_dir, cls.all_patch_name)
  4155. )
  4156. cls.numbers_patch_template_hash = salt.utils.hashutils.get_hash(
  4157. os.path.join(patches_dir, cls.numbers_patch_template_name)
  4158. )
  4159. cls.math_patch_template_hash = salt.utils.hashutils.get_hash(
  4160. os.path.join(patches_dir, cls.math_patch_template_name)
  4161. )
  4162. cls.all_patch_template_hash = salt.utils.hashutils.get_hash(
  4163. os.path.join(patches_dir, cls.all_patch_template_name)
  4164. )
  4165. cls.context = {"two": "two", "ten": 10}
  4166. @classmethod
  4167. def tearDownClass(cls):
  4168. cls.webserver.stop()
  4169. def setUp(self):
  4170. """
  4171. Create a new unpatched set of files
  4172. """
  4173. self.base_dir = tempfile.mkdtemp(dir=RUNTIME_VARS.TMP)
  4174. os.makedirs(os.path.join(self.base_dir, "foo", "bar"))
  4175. self.numbers_file = os.path.join(self.base_dir, "foo", "numbers.txt")
  4176. self.math_file = os.path.join(self.base_dir, "foo", "bar", "math.txt")
  4177. with salt.utils.files.fopen(self.numbers_file, "w") as fp_:
  4178. fp_.write(
  4179. textwrap.dedent(
  4180. """\
  4181. one
  4182. two
  4183. three
  4184. 1
  4185. 2
  4186. 3
  4187. """
  4188. )
  4189. )
  4190. with salt.utils.files.fopen(self.math_file, "w") as fp_:
  4191. fp_.write(
  4192. textwrap.dedent(
  4193. """\
  4194. Five plus five is ten
  4195. Four squared is sixteen
  4196. """
  4197. )
  4198. )
  4199. self.addCleanup(shutil.rmtree, self.base_dir, ignore_errors=True)
  4200. @pytest.mark.slow_test(seconds=5) # Test takes >1 and <=5 seconds
  4201. def test_patch_single_file(self):
  4202. """
  4203. Test file.patch using a patch applied to a single file
  4204. """
  4205. ret = self.run_state(
  4206. "file.patch", name=self.numbers_file, source=self.numbers_patch,
  4207. )
  4208. self.assertSaltTrueReturn(ret)
  4209. ret = ret[next(iter(ret))]
  4210. self.assertEqual(ret["comment"], "Patch successfully applied")
  4211. # Re-run the state, should succeed and there should be a message about
  4212. # a partially-applied hunk.
  4213. ret = self.run_state(
  4214. "file.patch", name=self.numbers_file, source=self.numbers_patch,
  4215. )
  4216. self.assertSaltTrueReturn(ret)
  4217. ret = ret[next(iter(ret))]
  4218. self.assertEqual(ret["comment"], "Patch was already applied")
  4219. self.assertEqual(ret["changes"], {})
  4220. @pytest.mark.slow_test(seconds=5) # Test takes >1 and <=5 seconds
  4221. def test_patch_directory(self):
  4222. """
  4223. Test file.patch using a patch applied to a directory, with changes
  4224. spanning multiple files.
  4225. """
  4226. self._check_patch_version("2.6")
  4227. ret = self.run_state(
  4228. "file.patch", name=self.base_dir, source=self.all_patch, strip=1,
  4229. )
  4230. self.assertSaltTrueReturn(ret)
  4231. ret = ret[next(iter(ret))]
  4232. self.assertEqual(ret["comment"], "Patch successfully applied")
  4233. # Re-run the state, should succeed and there should be a message about
  4234. # a partially-applied hunk.
  4235. ret = self.run_state(
  4236. "file.patch", name=self.base_dir, source=self.all_patch, strip=1,
  4237. )
  4238. self.assertSaltTrueReturn(ret)
  4239. ret = ret[next(iter(ret))]
  4240. self.assertEqual(ret["comment"], "Patch was already applied")
  4241. self.assertEqual(ret["changes"], {})
  4242. @pytest.mark.slow_test(seconds=5) # Test takes >1 and <=5 seconds
  4243. def test_patch_strip_parsing(self):
  4244. """
  4245. Test that we successfuly parse -p/--strip when included in the options
  4246. """
  4247. self._check_patch_version("2.6")
  4248. # Run the state using -p1
  4249. ret = self.run_state(
  4250. "file.patch", name=self.base_dir, source=self.all_patch, options="-p1",
  4251. )
  4252. self.assertSaltTrueReturn(ret)
  4253. ret = ret[next(iter(ret))]
  4254. self.assertEqual(ret["comment"], "Patch successfully applied")
  4255. # Re-run the state using --strip=1
  4256. ret = self.run_state(
  4257. "file.patch",
  4258. name=self.base_dir,
  4259. source=self.all_patch,
  4260. options="--strip=1",
  4261. )
  4262. self.assertSaltTrueReturn(ret)
  4263. ret = ret[next(iter(ret))]
  4264. self.assertEqual(ret["comment"], "Patch was already applied")
  4265. self.assertEqual(ret["changes"], {})
  4266. # Re-run the state using --strip 1
  4267. ret = self.run_state(
  4268. "file.patch",
  4269. name=self.base_dir,
  4270. source=self.all_patch,
  4271. options="--strip 1",
  4272. )
  4273. self.assertSaltTrueReturn(ret)
  4274. ret = ret[next(iter(ret))]
  4275. self.assertEqual(ret["comment"], "Patch was already applied")
  4276. self.assertEqual(ret["changes"], {})
  4277. @pytest.mark.slow_test(seconds=1) # Test takes >0.1 and <=1 seconds
  4278. def test_patch_saltenv(self):
  4279. """
  4280. Test that we attempt to download the patch from a non-base saltenv
  4281. """
  4282. # This state will fail because we don't have a patch file in that
  4283. # environment, but that is OK, we just want to test that we're looking
  4284. # in an environment other than base.
  4285. ret = self.run_state(
  4286. "file.patch", name=self.math_file, source=self.math_patch, saltenv="prod",
  4287. )
  4288. self.assertSaltFalseReturn(ret)
  4289. ret = ret[next(iter(ret))]
  4290. self.assertEqual(
  4291. ret["comment"],
  4292. "Source file {0} not found in saltenv 'prod'".format(self.math_patch),
  4293. )
  4294. @pytest.mark.slow_test(seconds=5) # Test takes >1 and <=5 seconds
  4295. def test_patch_single_file_failure(self):
  4296. """
  4297. Test file.patch using a patch applied to a single file. This tests a
  4298. failed patch.
  4299. """
  4300. # Empty the file to ensure that the patch doesn't apply cleanly
  4301. with salt.utils.files.fopen(self.numbers_file, "w"):
  4302. pass
  4303. ret = self.run_state(
  4304. "file.patch", name=self.numbers_file, source=self.numbers_patch,
  4305. )
  4306. self.assertSaltFalseReturn(ret)
  4307. ret = ret[next(iter(ret))]
  4308. self.assertIn("Patch would not apply cleanly", ret["comment"])
  4309. # Test the reject_file option and ensure that the rejects are written
  4310. # to the path specified.
  4311. reject_file = salt.utils.files.mkstemp()
  4312. ret = self.run_state(
  4313. "file.patch",
  4314. name=self.numbers_file,
  4315. source=self.numbers_patch,
  4316. reject_file=reject_file,
  4317. strip=1,
  4318. )
  4319. self.assertSaltFalseReturn(ret)
  4320. ret = ret[next(iter(ret))]
  4321. self.assertIn("Patch would not apply cleanly", ret["comment"])
  4322. self.assertRegex(
  4323. ret["comment"], "saving rejects to (file )?{0}".format(reject_file)
  4324. )
  4325. @pytest.mark.slow_test(seconds=5) # Test takes >1 and <=5 seconds
  4326. def test_patch_directory_failure(self):
  4327. """
  4328. Test file.patch using a patch applied to a directory, with changes
  4329. spanning multiple files.
  4330. """
  4331. # Empty the file to ensure that the patch doesn't apply
  4332. with salt.utils.files.fopen(self.math_file, "w"):
  4333. pass
  4334. ret = self.run_state(
  4335. "file.patch", name=self.base_dir, source=self.all_patch, strip=1,
  4336. )
  4337. self.assertSaltFalseReturn(ret)
  4338. ret = ret[next(iter(ret))]
  4339. self.assertIn("Patch would not apply cleanly", ret["comment"])
  4340. # Test the reject_file option and ensure that the rejects are written
  4341. # to the path specified.
  4342. reject_file = salt.utils.files.mkstemp()
  4343. ret = self.run_state(
  4344. "file.patch",
  4345. name=self.base_dir,
  4346. source=self.all_patch,
  4347. reject_file=reject_file,
  4348. strip=1,
  4349. )
  4350. self.assertSaltFalseReturn(ret)
  4351. ret = ret[next(iter(ret))]
  4352. self.assertIn("Patch would not apply cleanly", ret["comment"])
  4353. self.assertRegex(
  4354. ret["comment"], "saving rejects to (file )?{0}".format(reject_file)
  4355. )
  4356. @pytest.mark.slow_test(seconds=5) # Test takes >1 and <=5 seconds
  4357. def test_patch_single_file_remote_source(self):
  4358. """
  4359. Test file.patch using a patch applied to a single file, with the patch
  4360. coming from a remote source.
  4361. """
  4362. # Try without a source_hash and without skip_verify=True, this should
  4363. # fail with a message about the source_hash
  4364. ret = self.run_state(
  4365. "file.patch", name=self.math_file, source=self.math_patch_http,
  4366. )
  4367. self.assertSaltFalseReturn(ret)
  4368. ret = ret[next(iter(ret))]
  4369. self.assertIn("Unable to verify upstream hash", ret["comment"])
  4370. # Re-run the state with a source hash, it should now succeed
  4371. ret = self.run_state(
  4372. "file.patch",
  4373. name=self.math_file,
  4374. source=self.math_patch_http,
  4375. source_hash=self.math_patch_hash,
  4376. )
  4377. self.assertSaltTrueReturn(ret)
  4378. ret = ret[next(iter(ret))]
  4379. self.assertEqual(ret["comment"], "Patch successfully applied")
  4380. # Re-run again, this time with no hash and skip_verify=True to test
  4381. # skipping hash verification
  4382. ret = self.run_state(
  4383. "file.patch",
  4384. name=self.math_file,
  4385. source=self.math_patch_http,
  4386. skip_verify=True,
  4387. )
  4388. self.assertSaltTrueReturn(ret)
  4389. ret = ret[next(iter(ret))]
  4390. self.assertEqual(ret["comment"], "Patch was already applied")
  4391. self.assertEqual(ret["changes"], {})
  4392. @pytest.mark.slow_test(seconds=5) # Test takes >1 and <=5 seconds
  4393. def test_patch_directory_remote_source(self):
  4394. """
  4395. Test file.patch using a patch applied to a directory, with changes
  4396. spanning multiple files, and the patch file coming from a remote
  4397. source.
  4398. """
  4399. self._check_patch_version("2.6")
  4400. # Try without a source_hash and without skip_verify=True, this should
  4401. # fail with a message about the source_hash
  4402. ret = self.run_state(
  4403. "file.patch", name=self.base_dir, source=self.all_patch_http, strip=1,
  4404. )
  4405. self.assertSaltFalseReturn(ret)
  4406. ret = ret[next(iter(ret))]
  4407. self.assertIn("Unable to verify upstream hash", ret["comment"])
  4408. # Re-run the state with a source hash, it should now succeed
  4409. ret = self.run_state(
  4410. "file.patch",
  4411. name=self.base_dir,
  4412. source=self.all_patch_http,
  4413. source_hash=self.all_patch_hash,
  4414. strip=1,
  4415. )
  4416. self.assertSaltTrueReturn(ret)
  4417. ret = ret[next(iter(ret))]
  4418. self.assertEqual(ret["comment"], "Patch successfully applied")
  4419. # Re-run again, this time with no hash and skip_verify=True to test
  4420. # skipping hash verification
  4421. ret = self.run_state(
  4422. "file.patch",
  4423. name=self.base_dir,
  4424. source=self.all_patch_http,
  4425. strip=1,
  4426. skip_verify=True,
  4427. )
  4428. self.assertSaltTrueReturn(ret)
  4429. ret = ret[next(iter(ret))]
  4430. self.assertEqual(ret["comment"], "Patch was already applied")
  4431. self.assertEqual(ret["changes"], {})
  4432. @pytest.mark.slow_test(seconds=5) # Test takes >1 and <=5 seconds
  4433. def test_patch_single_file_template(self):
  4434. """
  4435. Test file.patch using a patch applied to a single file, with jinja
  4436. templating applied to the patch file.
  4437. """
  4438. ret = self.run_state(
  4439. "file.patch",
  4440. name=self.numbers_file,
  4441. source=self.numbers_patch_template,
  4442. template="jinja",
  4443. context=self.context,
  4444. )
  4445. self.assertSaltTrueReturn(ret)
  4446. ret = ret[next(iter(ret))]
  4447. self.assertEqual(ret["comment"], "Patch successfully applied")
  4448. # Re-run the state, should succeed and there should be a message about
  4449. # a partially-applied hunk.
  4450. ret = self.run_state(
  4451. "file.patch",
  4452. name=self.numbers_file,
  4453. source=self.numbers_patch_template,
  4454. template="jinja",
  4455. context=self.context,
  4456. )
  4457. self.assertSaltTrueReturn(ret)
  4458. ret = ret[next(iter(ret))]
  4459. self.assertEqual(ret["comment"], "Patch was already applied")
  4460. self.assertEqual(ret["changes"], {})
  4461. @pytest.mark.slow_test(seconds=5) # Test takes >1 and <=5 seconds
  4462. def test_patch_directory_template(self):
  4463. """
  4464. Test file.patch using a patch applied to a directory, with changes
  4465. spanning multiple files, and with jinja templating applied to the patch
  4466. file.
  4467. """
  4468. self._check_patch_version("2.6")
  4469. ret = self.run_state(
  4470. "file.patch",
  4471. name=self.base_dir,
  4472. source=self.all_patch_template,
  4473. template="jinja",
  4474. context=self.context,
  4475. strip=1,
  4476. )
  4477. self.assertSaltTrueReturn(ret)
  4478. ret = ret[next(iter(ret))]
  4479. self.assertEqual(ret["comment"], "Patch successfully applied")
  4480. # Re-run the state, should succeed and there should be a message about
  4481. # a partially-applied hunk.
  4482. ret = self.run_state(
  4483. "file.patch",
  4484. name=self.base_dir,
  4485. source=self.all_patch_template,
  4486. template="jinja",
  4487. context=self.context,
  4488. strip=1,
  4489. )
  4490. self.assertSaltTrueReturn(ret)
  4491. ret = ret[next(iter(ret))]
  4492. self.assertEqual(ret["comment"], "Patch was already applied")
  4493. self.assertEqual(ret["changes"], {})
  4494. @pytest.mark.slow_test(seconds=5) # Test takes >1 and <=5 seconds
  4495. def test_patch_single_file_remote_source_template(self):
  4496. """
  4497. Test file.patch using a patch applied to a single file, with the patch
  4498. coming from a remote source.
  4499. """
  4500. # Try without a source_hash and without skip_verify=True, this should
  4501. # fail with a message about the source_hash
  4502. ret = self.run_state(
  4503. "file.patch",
  4504. name=self.math_file,
  4505. source=self.math_patch_template_http,
  4506. template="jinja",
  4507. context=self.context,
  4508. )
  4509. self.assertSaltFalseReturn(ret)
  4510. ret = ret[next(iter(ret))]
  4511. self.assertIn("Unable to verify upstream hash", ret["comment"])
  4512. # Re-run the state with a source hash, it should now succeed
  4513. ret = self.run_state(
  4514. "file.patch",
  4515. name=self.math_file,
  4516. source=self.math_patch_template_http,
  4517. source_hash=self.math_patch_template_hash,
  4518. template="jinja",
  4519. context=self.context,
  4520. )
  4521. self.assertSaltTrueReturn(ret)
  4522. ret = ret[next(iter(ret))]
  4523. self.assertEqual(ret["comment"], "Patch successfully applied")
  4524. # Re-run again, this time with no hash and skip_verify=True to test
  4525. # skipping hash verification
  4526. ret = self.run_state(
  4527. "file.patch",
  4528. name=self.math_file,
  4529. source=self.math_patch_template_http,
  4530. template="jinja",
  4531. context=self.context,
  4532. skip_verify=True,
  4533. )
  4534. self.assertSaltTrueReturn(ret)
  4535. ret = ret[next(iter(ret))]
  4536. self.assertEqual(ret["comment"], "Patch was already applied")
  4537. self.assertEqual(ret["changes"], {})
  4538. @pytest.mark.slow_test(seconds=5) # Test takes >1 and <=5 seconds
  4539. def test_patch_directory_remote_source_template(self):
  4540. """
  4541. Test file.patch using a patch applied to a directory, with changes
  4542. spanning multiple files, and the patch file coming from a remote
  4543. source.
  4544. """
  4545. self._check_patch_version("2.6")
  4546. # Try without a source_hash and without skip_verify=True, this should
  4547. # fail with a message about the source_hash
  4548. ret = self.run_state(
  4549. "file.patch",
  4550. name=self.base_dir,
  4551. source=self.all_patch_template_http,
  4552. template="jinja",
  4553. context=self.context,
  4554. strip=1,
  4555. )
  4556. self.assertSaltFalseReturn(ret)
  4557. ret = ret[next(iter(ret))]
  4558. self.assertIn("Unable to verify upstream hash", ret["comment"])
  4559. # Re-run the state with a source hash, it should now succeed
  4560. ret = self.run_state(
  4561. "file.patch",
  4562. name=self.base_dir,
  4563. source=self.all_patch_template_http,
  4564. source_hash=self.all_patch_template_hash,
  4565. template="jinja",
  4566. context=self.context,
  4567. strip=1,
  4568. )
  4569. self.assertSaltTrueReturn(ret)
  4570. ret = ret[next(iter(ret))]
  4571. self.assertEqual(ret["comment"], "Patch successfully applied")
  4572. # Re-run again, this time with no hash and skip_verify=True to test
  4573. # skipping hash verification
  4574. ret = self.run_state(
  4575. "file.patch",
  4576. name=self.base_dir,
  4577. source=self.all_patch_template_http,
  4578. template="jinja",
  4579. context=self.context,
  4580. strip=1,
  4581. skip_verify=True,
  4582. )
  4583. self.assertSaltTrueReturn(ret)
  4584. ret = ret[next(iter(ret))]
  4585. self.assertEqual(ret["comment"], "Patch was already applied")
  4586. self.assertEqual(ret["changes"], {})
  4587. @pytest.mark.slow_test(seconds=5) # Test takes >1 and <=5 seconds
  4588. def test_patch_test_mode(self):
  4589. """
  4590. Test file.patch using test=True
  4591. """
  4592. # Try without a source_hash and without skip_verify=True, this should
  4593. # fail with a message about the source_hash
  4594. ret = self.run_state(
  4595. "file.patch", name=self.numbers_file, source=self.numbers_patch, test=True,
  4596. )
  4597. self.assertSaltNoneReturn(ret)
  4598. ret = ret[next(iter(ret))]
  4599. self.assertEqual(ret["comment"], "The patch would be applied")
  4600. self.assertTrue(ret["changes"])
  4601. # Apply the patch for real. We'll then be able to test below that we
  4602. # exit with a True rather than a None result if test=True is used on an
  4603. # already-applied patch.
  4604. ret = self.run_state(
  4605. "file.patch", name=self.numbers_file, source=self.numbers_patch,
  4606. )
  4607. self.assertSaltTrueReturn(ret)
  4608. ret = ret[next(iter(ret))]
  4609. self.assertEqual(ret["comment"], "Patch successfully applied")
  4610. self.assertTrue(ret["changes"])
  4611. # Run again with test=True. Since the pre-check happens before we do
  4612. # the __opts__['test'] check, we should exit with a True result just
  4613. # the same as if we try to run this state on an already-patched file
  4614. # *without* test=True.
  4615. ret = self.run_state(
  4616. "file.patch", name=self.numbers_file, source=self.numbers_patch, test=True,
  4617. )
  4618. self.assertSaltTrueReturn(ret)
  4619. ret = ret[next(iter(ret))]
  4620. self.assertEqual(ret["comment"], "Patch was already applied")
  4621. self.assertEqual(ret["changes"], {})
  4622. # Empty the file to ensure that the patch doesn't apply cleanly
  4623. with salt.utils.files.fopen(self.numbers_file, "w"):
  4624. pass
  4625. # Run again with test=True. Similar to the above run, we are testing
  4626. # that we return before we reach the __opts__['test'] check. In this
  4627. # case we should return a False result because we should already know
  4628. # by this point that the patch will not apply cleanly.
  4629. ret = self.run_state(
  4630. "file.patch", name=self.numbers_file, source=self.numbers_patch, test=True,
  4631. )
  4632. self.assertSaltFalseReturn(ret)
  4633. ret = ret[next(iter(ret))]
  4634. self.assertIn("Patch would not apply cleanly", ret["comment"])
  4635. self.assertEqual(ret["changes"], {})
  4636. WIN_TEST_FILE = "c:/testfile"
  4637. @pytest.mark.destructive_test
  4638. @skipIf(not IS_WINDOWS, "windows test only")
  4639. @pytest.mark.windows_whitelisted
  4640. class WinFileTest(ModuleCase):
  4641. """
  4642. Test for the file state on Windows
  4643. """
  4644. def setUp(self):
  4645. self.run_state(
  4646. "file.managed", name=WIN_TEST_FILE, makedirs=True, contents="Only a test"
  4647. )
  4648. def tearDown(self):
  4649. self.run_state("file.absent", name=WIN_TEST_FILE)
  4650. @pytest.mark.slow_test(seconds=60) # Test takes >30 and <=60 seconds
  4651. def test_file_managed(self):
  4652. """
  4653. Test file.managed on Windows
  4654. """
  4655. self.assertTrue(self.run_state("file.exists", name=WIN_TEST_FILE))
  4656. @pytest.mark.slow_test(seconds=60) # Test takes >30 and <=60 seconds
  4657. def test_file_copy(self):
  4658. """
  4659. Test file.copy on Windows
  4660. """
  4661. ret = self.run_state(
  4662. "file.copy", name="c:/testfile_copy", makedirs=True, source=WIN_TEST_FILE
  4663. )
  4664. self.assertTrue(ret)
  4665. @pytest.mark.slow_test(seconds=60) # Test takes >30 and <=60 seconds
  4666. def test_file_comment(self):
  4667. """
  4668. Test file.comment on Windows
  4669. """
  4670. self.run_state("file.comment", name=WIN_TEST_FILE, regex="^Only")
  4671. with salt.utils.files.fopen(WIN_TEST_FILE, "r") as fp_:
  4672. self.assertTrue(fp_.read().startswith("#Only"))
  4673. @pytest.mark.slow_test(seconds=60) # Test takes >30 and <=60 seconds
  4674. def test_file_replace(self):
  4675. """
  4676. Test file.replace on Windows
  4677. """
  4678. self.run_state(
  4679. "file.replace", name=WIN_TEST_FILE, pattern="test", repl="testing"
  4680. )
  4681. with salt.utils.files.fopen(WIN_TEST_FILE, "r") as fp_:
  4682. self.assertIn("testing", fp_.read())
  4683. @pytest.mark.slow_test(seconds=60) # Test takes >30 and <=60 seconds
  4684. def test_file_absent(self):
  4685. """
  4686. Test file.absent on Windows
  4687. """
  4688. ret = self.run_state("file.absent", name=WIN_TEST_FILE)
  4689. self.assertTrue(ret)