test_vmware.py 201 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159
  1. # -*- coding: utf-8 -*-
  2. """
  3. :codeauthor: Alexandru Bleotu <alexandru.bleotu@morganstanley.com>
  4. Tests for cluster related functions in salt.utils.vmware
  5. """
  6. # Import python libraries
  7. from __future__ import absolute_import, print_function, unicode_literals
  8. import base64
  9. import logging
  10. import ssl
  11. import sys
  12. import salt.utils.vmware
  13. # Import Salt libraries
  14. from salt.exceptions import (
  15. ArgumentValueError,
  16. CommandExecutionError,
  17. VMwareApiError,
  18. VMwareConnectionError,
  19. VMwareObjectRetrievalError,
  20. VMwareRuntimeError,
  21. VMwareSystemError,
  22. )
  23. # Import Third Party Libs
  24. from salt.ext import six
  25. from tests.support.mixins import LoaderModuleMockMixin
  26. from tests.support.mock import MagicMock, PropertyMock, call, patch
  27. # Import Salt testing libraries
  28. from tests.support.runtests import RUNTIME_VARS
  29. from tests.support.unit import TestCase, skipIf
  30. try:
  31. from pyVmomi import vim, vmodl # pylint: disable=no-name-in-module
  32. HAS_PYVMOMI = True
  33. except ImportError:
  34. HAS_PYVMOMI = False
  35. try:
  36. import gssapi
  37. HAS_GSSAPI = True
  38. except ImportError:
  39. HAS_GSSAPI = False
  40. if sys.version_info[:3] > (2, 7, 8):
  41. SSL_VALIDATION = True
  42. else:
  43. SSL_VALIDATION = False
  44. if hasattr(ssl, "_create_unverified_context"):
  45. ssl_context = "ssl._create_unverified_context"
  46. else:
  47. ssl_context = "ssl._create_stdlib_context"
  48. # Get Logging Started
  49. log = logging.getLogger(__name__)
  50. @skipIf(not HAS_PYVMOMI, "The 'pyvmomi' library is missing")
  51. class GetClusterTestCase(TestCase):
  52. """
  53. Tests for salt.utils.vmware.get_cluster
  54. """
  55. def setUp(self):
  56. patches = (
  57. ("salt.utils.vmware.get_managed_object_name", MagicMock()),
  58. ("salt.utils.vmware.get_service_instance_from_managed_object", MagicMock()),
  59. (
  60. "salt.utils.vmware.get_mors_with_properties",
  61. MagicMock(
  62. return_value=[{"name": "fake_cluster", "object": MagicMock()}]
  63. ),
  64. ),
  65. )
  66. for mod, mock in patches:
  67. patcher = patch(mod, mock)
  68. patcher.start()
  69. self.addCleanup(patcher.stop)
  70. self.mock_si = MagicMock()
  71. self.mock_dc = MagicMock()
  72. self.mock_cluster1 = MagicMock()
  73. self.mock_cluster2 = MagicMock()
  74. self.mock_entries = [
  75. {"name": "fake_cluster1", "object": self.mock_cluster1},
  76. {"name": "fake_cluster2", "object": self.mock_cluster2},
  77. ]
  78. for attr in (
  79. "mock_si",
  80. "mock_dc",
  81. "mock_cluster1",
  82. "mock_cluster2",
  83. "mock_entries",
  84. ):
  85. self.addCleanup(delattr, self, attr)
  86. def test_get_managed_object_name_call(self):
  87. mock_get_managed_object_name = MagicMock()
  88. with patch(
  89. "salt.utils.vmware.get_managed_object_name", mock_get_managed_object_name
  90. ):
  91. salt.utils.vmware.get_cluster(self.mock_dc, "fake_cluster")
  92. mock_get_managed_object_name.assert_called_once_with(self.mock_dc)
  93. def test_get_service_instance_from_managed_object(self):
  94. mock_dc_name = MagicMock()
  95. mock_get_service_instance_from_managed_object = MagicMock()
  96. with patch(
  97. "salt.utils.vmware.get_managed_object_name",
  98. MagicMock(return_value=mock_dc_name),
  99. ):
  100. with patch(
  101. "salt.utils.vmware.get_service_instance_from_managed_object",
  102. mock_get_service_instance_from_managed_object,
  103. ):
  104. salt.utils.vmware.get_cluster(self.mock_dc, "fake_cluster")
  105. mock_get_service_instance_from_managed_object.assert_called_once_with(
  106. self.mock_dc, name=mock_dc_name
  107. )
  108. def test_traversal_spec_init(self):
  109. mock_dc_name = MagicMock()
  110. mock_traversal_spec = MagicMock()
  111. mock_traversal_spec_ini = MagicMock(return_value=mock_traversal_spec)
  112. mock_get_service_instance_from_managed_object = MagicMock()
  113. patch_traversal_spec_str = (
  114. "salt.utils.vmware.vmodl.query.PropertyCollector.TraversalSpec"
  115. )
  116. with patch(patch_traversal_spec_str, mock_traversal_spec_ini):
  117. salt.utils.vmware.get_cluster(self.mock_dc, "fake_cluster")
  118. mock_traversal_spec_ini.assert_has_calls(
  119. [
  120. call(path="childEntity", skip=False, type=vim.Folder),
  121. call(
  122. path="hostFolder",
  123. skip=True,
  124. type=vim.Datacenter,
  125. selectSet=[mock_traversal_spec],
  126. ),
  127. ]
  128. )
  129. def test_get_mors_with_properties_call(self):
  130. mock_get_mors_with_properties = MagicMock(
  131. return_value=[{"name": "fake_cluster", "object": MagicMock()}]
  132. )
  133. mock_traversal_spec = MagicMock()
  134. patch_traversal_spec_str = (
  135. "salt.utils.vmware.vmodl.query.PropertyCollector.TraversalSpec"
  136. )
  137. with patch(
  138. "salt.utils.vmware.get_service_instance_from_managed_object",
  139. MagicMock(return_value=self.mock_si),
  140. ):
  141. with patch(
  142. "salt.utils.vmware.get_mors_with_properties",
  143. mock_get_mors_with_properties,
  144. ):
  145. with patch(
  146. patch_traversal_spec_str,
  147. MagicMock(return_value=mock_traversal_spec),
  148. ):
  149. salt.utils.vmware.get_cluster(self.mock_dc, "fake_cluster")
  150. mock_get_mors_with_properties.assert_called_once_with(
  151. self.mock_si,
  152. vim.ClusterComputeResource,
  153. container_ref=self.mock_dc,
  154. property_list=["name"],
  155. traversal_spec=mock_traversal_spec,
  156. )
  157. def test_get_mors_with_properties_returns_empty_array(self):
  158. with patch(
  159. "salt.utils.vmware.get_managed_object_name",
  160. MagicMock(return_value="fake_dc"),
  161. ):
  162. with patch(
  163. "salt.utils.vmware.get_mors_with_properties", MagicMock(return_value=[])
  164. ):
  165. with self.assertRaises(VMwareObjectRetrievalError) as excinfo:
  166. salt.utils.vmware.get_cluster(self.mock_dc, "fake_cluster")
  167. self.assertEqual(
  168. excinfo.exception.strerror,
  169. "Cluster 'fake_cluster' was not found in " "datacenter 'fake_dc'",
  170. )
  171. def test_cluster_not_found(self):
  172. with patch(
  173. "salt.utils.vmware.get_managed_object_name",
  174. MagicMock(return_value="fake_dc"),
  175. ):
  176. with patch(
  177. "salt.utils.vmware.get_mors_with_properties",
  178. MagicMock(return_value=self.mock_entries),
  179. ):
  180. with self.assertRaises(VMwareObjectRetrievalError) as excinfo:
  181. salt.utils.vmware.get_cluster(self.mock_dc, "fake_cluster")
  182. self.assertEqual(
  183. excinfo.exception.strerror,
  184. "Cluster 'fake_cluster' was not found in " "datacenter 'fake_dc'",
  185. )
  186. def test_cluster_found(self):
  187. with patch(
  188. "salt.utils.vmware.get_managed_object_name",
  189. MagicMock(return_value="fake_dc"),
  190. ):
  191. with patch(
  192. "salt.utils.vmware.get_mors_with_properties",
  193. MagicMock(return_value=self.mock_entries),
  194. ):
  195. res = salt.utils.vmware.get_cluster(self.mock_dc, "fake_cluster2")
  196. self.assertEqual(res, self.mock_cluster2)
  197. @skipIf(not HAS_PYVMOMI, "The 'pyvmomi' library is missing")
  198. class CreateClusterTestCase(TestCase):
  199. """
  200. Tests for salt.utils.vmware.create_cluster
  201. """
  202. def setUp(self):
  203. patches = (("salt.utils.vmware.get_managed_object_name", MagicMock()),)
  204. for mod, mock in patches:
  205. patcher = patch(mod, mock)
  206. patcher.start()
  207. self.addCleanup(patcher.stop)
  208. self.mock_create_cluster_ex = MagicMock()
  209. self.mock_dc = MagicMock(
  210. hostFolder=MagicMock(CreateClusterEx=self.mock_create_cluster_ex)
  211. )
  212. self.mock_cluster_spec = MagicMock()
  213. for attr in ("mock_create_cluster_ex", "mock_dc", "mock_cluster_spec"):
  214. self.addCleanup(delattr, self, attr)
  215. def test_get_managed_object_name(self):
  216. mock_get_managed_object_name = MagicMock()
  217. with patch(
  218. "salt.utils.vmware.get_managed_object_name", mock_get_managed_object_name
  219. ):
  220. salt.utils.vmware.create_cluster(
  221. self.mock_dc, "fake_cluster", self.mock_cluster_spec
  222. )
  223. mock_get_managed_object_name.assert_called_once_with(self.mock_dc)
  224. def test_create_cluster_call(self):
  225. salt.utils.vmware.create_cluster(
  226. self.mock_dc, "fake_cluster", self.mock_cluster_spec
  227. )
  228. self.mock_create_cluster_ex.assert_called_once_with(
  229. "fake_cluster", self.mock_cluster_spec
  230. )
  231. def test_create_cluster_raise_no_permission(self):
  232. exc = vim.fault.NoPermission()
  233. exc.privilegeId = "Fake privilege"
  234. self.mock_dc.hostFolder.CreateClusterEx = MagicMock(side_effect=exc)
  235. with self.assertRaises(VMwareApiError) as excinfo:
  236. salt.utils.vmware.create_cluster(
  237. self.mock_dc, "fake_cluster", self.mock_cluster_spec
  238. )
  239. self.assertEqual(
  240. excinfo.exception.strerror,
  241. "Not enough permissions. Required privilege: " "Fake privilege",
  242. )
  243. def test_create_cluster_raise_vim_fault(self):
  244. exc = vim.fault.VimFault()
  245. exc.msg = "VimFault msg"
  246. self.mock_dc.hostFolder.CreateClusterEx = MagicMock(side_effect=exc)
  247. with self.assertRaises(VMwareApiError) as excinfo:
  248. salt.utils.vmware.create_cluster(
  249. self.mock_dc, "fake_cluster", self.mock_cluster_spec
  250. )
  251. self.assertEqual(excinfo.exception.strerror, "VimFault msg")
  252. def test_create_cluster_raise_runtime_fault(self):
  253. exc = vmodl.RuntimeFault()
  254. exc.msg = "RuntimeFault msg"
  255. self.mock_dc.hostFolder.CreateClusterEx = MagicMock(side_effect=exc)
  256. with self.assertRaises(VMwareRuntimeError) as excinfo:
  257. salt.utils.vmware.create_cluster(
  258. self.mock_dc, "fake_cluster", self.mock_cluster_spec
  259. )
  260. self.assertEqual(excinfo.exception.strerror, "RuntimeFault msg")
  261. @skipIf(not HAS_PYVMOMI, "The 'pyvmomi' library is missing")
  262. class UpdateClusterTestCase(TestCase):
  263. """
  264. Tests for salt.utils.vmware.update_cluster
  265. """
  266. def setUp(self):
  267. patches = (
  268. ("salt.utils.vmware.get_managed_object_name", MagicMock()),
  269. ("salt.utils.vmware.wait_for_task", MagicMock()),
  270. )
  271. for mod, mock in patches:
  272. patcher = patch(mod, mock)
  273. patcher.start()
  274. self.addCleanup(patcher.stop)
  275. self.mock_task = MagicMock()
  276. self.mock_reconfigure_compute_resource_task = MagicMock(
  277. return_value=self.mock_task
  278. )
  279. self.mock_cluster = MagicMock(
  280. ReconfigureComputeResource_Task=self.mock_reconfigure_compute_resource_task
  281. )
  282. self.mock_cluster_spec = MagicMock()
  283. for attr in (
  284. "mock_task",
  285. "mock_reconfigure_compute_resource_task",
  286. "mock_cluster",
  287. "mock_cluster_spec",
  288. ):
  289. self.addCleanup(delattr, self, attr)
  290. def test_get_managed_object_name(self):
  291. mock_get_managed_object_name = MagicMock()
  292. with patch(
  293. "salt.utils.vmware.get_managed_object_name", mock_get_managed_object_name
  294. ):
  295. salt.utils.vmware.update_cluster(self.mock_cluster, self.mock_cluster_spec)
  296. mock_get_managed_object_name.assert_called_once_with(self.mock_cluster)
  297. def test_reconfigure_compute_resource_task_call(self):
  298. salt.utils.vmware.update_cluster(self.mock_cluster, self.mock_cluster_spec)
  299. self.mock_reconfigure_compute_resource_task.assert_called_once_with(
  300. self.mock_cluster_spec, modify=True
  301. )
  302. def test_reconfigure_compute_resource_raise_no_permission(self):
  303. exc = vim.fault.NoPermission()
  304. exc.privilegeId = "Fake privilege"
  305. self.mock_cluster.ReconfigureComputeResource_Task = MagicMock(side_effect=exc)
  306. with self.assertRaises(VMwareApiError) as excinfo:
  307. salt.utils.vmware.update_cluster(self.mock_cluster, self.mock_cluster_spec)
  308. self.assertEqual(
  309. excinfo.exception.strerror,
  310. "Not enough permissions. Required privilege: " "Fake privilege",
  311. )
  312. def test_reconfigure_compute_resource_raise_vim_fault(self):
  313. exc = vim.fault.VimFault()
  314. exc.msg = "VimFault msg"
  315. self.mock_cluster.ReconfigureComputeResource_Task = MagicMock(side_effect=exc)
  316. with self.assertRaises(VMwareApiError) as excinfo:
  317. salt.utils.vmware.update_cluster(self.mock_cluster, self.mock_cluster_spec)
  318. self.assertEqual(excinfo.exception.strerror, "VimFault msg")
  319. def test_reconfigure_compute_resource_raise_runtime_fault(self):
  320. exc = vmodl.RuntimeFault()
  321. exc.msg = "RuntimeFault msg"
  322. self.mock_cluster.ReconfigureComputeResource_Task = MagicMock(side_effect=exc)
  323. with self.assertRaises(VMwareRuntimeError) as excinfo:
  324. salt.utils.vmware.update_cluster(self.mock_cluster, self.mock_cluster_spec)
  325. self.assertEqual(excinfo.exception.strerror, "RuntimeFault msg")
  326. def test_wait_for_task_call(self):
  327. mock_wait_for_task = MagicMock()
  328. with patch(
  329. "salt.utils.vmware.get_managed_object_name",
  330. MagicMock(return_value="fake_cluster"),
  331. ):
  332. with patch("salt.utils.vmware.wait_for_task", mock_wait_for_task):
  333. salt.utils.vmware.update_cluster(
  334. self.mock_cluster, self.mock_cluster_spec
  335. )
  336. mock_wait_for_task.assert_called_once_with(
  337. self.mock_task, "fake_cluster", "ClusterUpdateTask"
  338. )
  339. @skipIf(not HAS_PYVMOMI, "The 'pyvmomi' library is missing")
  340. class WaitForTaskTestCase(TestCase):
  341. """
  342. Tests for salt.utils.vmware.wait_for_task
  343. """
  344. def setUp(self):
  345. patches = (
  346. ("salt.utils.vmware.time.time", MagicMock(return_value=1)),
  347. ("salt.utils.vmware.time.sleep", MagicMock(return_value=None)),
  348. )
  349. for mod, mock in patches:
  350. patcher = patch(mod, mock)
  351. patcher.start()
  352. self.addCleanup(patcher.stop)
  353. def test_first_task_info_raise_no_permission(self):
  354. exc = vim.fault.NoPermission()
  355. exc.privilegeId = "Fake privilege"
  356. mock_task = MagicMock()
  357. type(mock_task).info = PropertyMock(side_effect=exc)
  358. with self.assertRaises(VMwareApiError) as excinfo:
  359. salt.utils.vmware.wait_for_task(
  360. mock_task, "fake_instance_name", "task_type"
  361. )
  362. self.assertEqual(
  363. excinfo.exception.strerror,
  364. "Not enough permissions. Required privilege: " "Fake privilege",
  365. )
  366. def test_first_task_info_raise_vim_fault(self):
  367. exc = vim.fault.VimFault()
  368. exc.msg = "VimFault msg"
  369. mock_task = MagicMock()
  370. type(mock_task).info = PropertyMock(side_effect=exc)
  371. with self.assertRaises(VMwareApiError) as excinfo:
  372. salt.utils.vmware.wait_for_task(
  373. mock_task, "fake_instance_name", "task_type"
  374. )
  375. self.assertEqual(excinfo.exception.strerror, "VimFault msg")
  376. def test_first_task_info_raise_runtime_fault(self):
  377. exc = vmodl.RuntimeFault()
  378. exc.msg = "RuntimeFault msg"
  379. mock_task = MagicMock()
  380. type(mock_task).info = PropertyMock(side_effect=exc)
  381. with self.assertRaises(VMwareRuntimeError) as excinfo:
  382. salt.utils.vmware.wait_for_task(
  383. mock_task, "fake_instance_name", "task_type"
  384. )
  385. self.assertEqual(excinfo.exception.strerror, "RuntimeFault msg")
  386. def test_inner_loop_task_info_raise_no_permission(self):
  387. exc = vim.fault.NoPermission()
  388. exc.privilegeId = "Fake privilege"
  389. mock_task = MagicMock()
  390. mock_info1 = MagicMock()
  391. type(mock_task).info = PropertyMock(side_effect=[mock_info1, exc])
  392. type(mock_info1).state = PropertyMock(side_effect=["running", "bad"])
  393. with self.assertRaises(VMwareApiError) as excinfo:
  394. salt.utils.vmware.wait_for_task(
  395. mock_task, "fake_instance_name", "task_type"
  396. )
  397. self.assertEqual(
  398. excinfo.exception.strerror,
  399. "Not enough permissions. Required privilege: " "Fake privilege",
  400. )
  401. def test_inner_loop_task_info_raise_vim_fault(self):
  402. exc = vim.fault.VimFault()
  403. exc.msg = "VimFault msg"
  404. mock_task = MagicMock()
  405. mock_info1 = MagicMock()
  406. type(mock_task).info = PropertyMock(side_effect=[mock_info1, exc])
  407. type(mock_info1).state = PropertyMock(side_effect=["running", "bad"])
  408. with self.assertRaises(VMwareApiError) as excinfo:
  409. salt.utils.vmware.wait_for_task(
  410. mock_task, "fake_instance_name", "task_type"
  411. )
  412. self.assertEqual(excinfo.exception.strerror, "VimFault msg")
  413. def test_inner_loop_task_info_raise_runtime_fault(self):
  414. exc = vmodl.RuntimeFault()
  415. exc.msg = "RuntimeFault msg"
  416. mock_task = MagicMock()
  417. mock_info1 = MagicMock()
  418. type(mock_task).info = PropertyMock(side_effect=[mock_info1, exc])
  419. type(mock_info1).state = PropertyMock(side_effect=["running", "bad"])
  420. with self.assertRaises(VMwareRuntimeError) as excinfo:
  421. salt.utils.vmware.wait_for_task(
  422. mock_task, "fake_instance_name", "task_type"
  423. )
  424. self.assertEqual(excinfo.exception.strerror, "RuntimeFault msg")
  425. def test_info_state_running(self):
  426. # The 'bad' values are invalid in the while loop
  427. mock_task = MagicMock()
  428. prop_mock_state = PropertyMock(side_effect=["running", "bad", "bad", "success"])
  429. prop_mock_result = PropertyMock()
  430. type(mock_task.info).state = prop_mock_state
  431. type(mock_task.info).result = prop_mock_result
  432. salt.utils.vmware.wait_for_task(mock_task, "fake_instance_name", "task_type")
  433. self.assertEqual(prop_mock_state.call_count, 4)
  434. self.assertEqual(prop_mock_result.call_count, 1)
  435. def test_info_state_running_continues_loop(self):
  436. mock_task = MagicMock()
  437. # The 'fake' values are required to match all the lookups and end the
  438. # loop
  439. prop_mock_state = PropertyMock(
  440. side_effect=["running", "fake", "fake", "success"]
  441. )
  442. prop_mock_result = PropertyMock()
  443. type(mock_task.info).state = prop_mock_state
  444. type(mock_task.info).result = prop_mock_result
  445. salt.utils.vmware.wait_for_task(mock_task, "fake_instance_name", "task_type")
  446. self.assertEqual(prop_mock_state.call_count, 4)
  447. self.assertEqual(prop_mock_result.call_count, 1)
  448. def test_info_state_queued_continues_loop(self):
  449. mock_task = MagicMock()
  450. # The 'fake' values are required to match all the lookups and end the
  451. # loop
  452. prop_mock_state = PropertyMock(
  453. side_effect=["fake", "queued", "fake", "fake", "success"]
  454. )
  455. prop_mock_result = PropertyMock()
  456. type(mock_task.info).state = prop_mock_state
  457. type(mock_task.info).result = prop_mock_result
  458. salt.utils.vmware.wait_for_task(mock_task, "fake_instance_name", "task_type")
  459. self.assertEqual(prop_mock_state.call_count, 5)
  460. self.assertEqual(prop_mock_result.call_count, 1)
  461. def test_info_state_success(self):
  462. mock_task = MagicMock()
  463. prop_mock_state = PropertyMock(return_value="success")
  464. prop_mock_result = PropertyMock()
  465. type(mock_task.info).state = prop_mock_state
  466. type(mock_task.info).result = prop_mock_result
  467. salt.utils.vmware.wait_for_task(mock_task, "fake_instance_name", "task_type")
  468. self.assertEqual(prop_mock_state.call_count, 3)
  469. self.assertEqual(prop_mock_result.call_count, 1)
  470. def test_info_error_exception(self):
  471. mock_task = MagicMock()
  472. prop_mock_state = PropertyMock(return_value="error")
  473. prop_mock_error = PropertyMock(side_effect=Exception("error exc"))
  474. type(mock_task.info).state = prop_mock_state
  475. type(mock_task.info).error = prop_mock_error
  476. with self.assertRaises(Exception) as excinfo:
  477. salt.utils.vmware.wait_for_task(
  478. mock_task, "fake_instance_name", "task_type"
  479. )
  480. self.assertEqual(six.text_type(excinfo.exception), "error exc")
  481. def test_info_error_no_permission(self):
  482. exc = vim.fault.NoPermission()
  483. exc.privilegeId = "Fake privilege"
  484. mock_task = MagicMock()
  485. prop_mock_state = PropertyMock(return_value="error")
  486. prop_mock_error = PropertyMock(side_effect=exc)
  487. type(mock_task.info).state = prop_mock_state
  488. type(mock_task.info).error = prop_mock_error
  489. with self.assertRaises(VMwareApiError) as excinfo:
  490. salt.utils.vmware.wait_for_task(
  491. mock_task, "fake_instance_name", "task_type"
  492. )
  493. self.assertEqual(
  494. excinfo.exception.strerror,
  495. "Not enough permissions. Required privilege: " "Fake privilege",
  496. )
  497. def test_info_error_vim_fault(self):
  498. exc = vim.fault.VimFault()
  499. exc.msg = "VimFault msg"
  500. mock_task = MagicMock()
  501. prop_mock_state = PropertyMock(return_value="error")
  502. prop_mock_error = PropertyMock(side_effect=exc)
  503. type(mock_task.info).state = prop_mock_state
  504. type(mock_task.info).error = prop_mock_error
  505. with self.assertRaises(VMwareApiError) as excinfo:
  506. salt.utils.vmware.wait_for_task(
  507. mock_task, "fake_instance_name", "task_type"
  508. )
  509. self.assertEqual(excinfo.exception.strerror, "VimFault msg")
  510. def test_info_error_system_fault(self):
  511. exc = vmodl.fault.SystemError()
  512. exc.msg = "SystemError msg"
  513. mock_task = MagicMock()
  514. prop_mock_state = PropertyMock(return_value="error")
  515. prop_mock_error = PropertyMock(side_effect=exc)
  516. type(mock_task.info).state = prop_mock_state
  517. type(mock_task.info).error = prop_mock_error
  518. with self.assertRaises(VMwareSystemError) as excinfo:
  519. salt.utils.vmware.wait_for_task(
  520. mock_task, "fake_instance_name", "task_type"
  521. )
  522. self.assertEqual(excinfo.exception.strerror, "SystemError msg")
  523. def test_info_error_invalid_argument_no_fault_message(self):
  524. exc = vmodl.fault.InvalidArgument()
  525. exc.faultMessage = None
  526. exc.msg = "InvalidArgumentFault msg"
  527. mock_task = MagicMock()
  528. prop_mock_state = PropertyMock(return_value="error")
  529. prop_mock_error = PropertyMock(side_effect=exc)
  530. type(mock_task.info).state = prop_mock_state
  531. type(mock_task.info).error = prop_mock_error
  532. with self.assertRaises(VMwareApiError) as excinfo:
  533. salt.utils.vmware.wait_for_task(
  534. mock_task, "fake_instance_name", "task_type"
  535. )
  536. self.assertEqual(excinfo.exception.strerror, "InvalidArgumentFault msg")
  537. def test_info_error_invalid_argument_with_fault_message(self):
  538. exc = vmodl.fault.InvalidArgument()
  539. fault_message = vim.LocalizableMessage()
  540. fault_message.message = "LocalFault msg"
  541. exc.faultMessage = [fault_message]
  542. exc.msg = "InvalidArgumentFault msg"
  543. mock_task = MagicMock()
  544. prop_mock_state = PropertyMock(return_value="error")
  545. prop_mock_error = PropertyMock(side_effect=exc)
  546. type(mock_task.info).state = prop_mock_state
  547. type(mock_task.info).error = prop_mock_error
  548. with self.assertRaises(VMwareApiError) as excinfo:
  549. salt.utils.vmware.wait_for_task(
  550. mock_task, "fake_instance_name", "task_type"
  551. )
  552. self.assertEqual(
  553. excinfo.exception.strerror, "InvalidArgumentFault msg (LocalFault msg)"
  554. )
  555. @skipIf(not HAS_PYVMOMI, "The 'pyvmomi' library is missing")
  556. class GetMorsWithPropertiesTestCase(TestCase):
  557. """
  558. Tests for salt.utils.get_mors_with_properties
  559. """
  560. si = None
  561. obj_type = None
  562. prop_list = None
  563. container_ref = None
  564. traversal_spec = None
  565. def setUp(self):
  566. self.si = MagicMock()
  567. self.obj_type = MagicMock()
  568. self.prop_list = MagicMock()
  569. self.container_ref = MagicMock()
  570. self.traversal_spec = MagicMock()
  571. def test_empty_content(self):
  572. get_content = MagicMock(return_value=[])
  573. with patch("salt.utils.vmware.get_content", get_content):
  574. ret = salt.utils.vmware.get_mors_with_properties(
  575. self.si,
  576. self.obj_type,
  577. self.prop_list,
  578. self.container_ref,
  579. self.traversal_spec,
  580. )
  581. get_content.assert_called_once_with(
  582. self.si,
  583. self.obj_type,
  584. property_list=self.prop_list,
  585. container_ref=self.container_ref,
  586. traversal_spec=self.traversal_spec,
  587. local_properties=False,
  588. )
  589. self.assertEqual(ret, [])
  590. def test_local_properties_set(self):
  591. obj_mock = MagicMock()
  592. # obj.propSet
  593. propSet_prop = PropertyMock(return_value=[])
  594. type(obj_mock).propSet = propSet_prop
  595. # obj.obj
  596. inner_obj_mock = MagicMock()
  597. obj_prop = PropertyMock(return_value=inner_obj_mock)
  598. type(obj_mock).obj = obj_prop
  599. get_content = MagicMock(return_value=[obj_mock])
  600. with patch("salt.utils.vmware.get_content", get_content):
  601. ret = salt.utils.vmware.get_mors_with_properties(
  602. self.si,
  603. self.obj_type,
  604. self.prop_list,
  605. self.container_ref,
  606. self.traversal_spec,
  607. local_properties=True,
  608. )
  609. get_content.assert_called_once_with(
  610. self.si,
  611. self.obj_type,
  612. property_list=self.prop_list,
  613. container_ref=self.container_ref,
  614. traversal_spec=self.traversal_spec,
  615. local_properties=True,
  616. )
  617. def test_one_element_content(self):
  618. obj_mock = MagicMock()
  619. # obj.propSet
  620. propSet_prop = PropertyMock(return_value=[])
  621. type(obj_mock).propSet = propSet_prop
  622. # obj.obj
  623. inner_obj_mock = MagicMock()
  624. obj_prop = PropertyMock(return_value=inner_obj_mock)
  625. type(obj_mock).obj = obj_prop
  626. get_content = MagicMock(return_value=[obj_mock])
  627. with patch("salt.utils.vmware.get_content", get_content):
  628. ret = salt.utils.vmware.get_mors_with_properties(
  629. self.si,
  630. self.obj_type,
  631. self.prop_list,
  632. self.container_ref,
  633. self.traversal_spec,
  634. )
  635. get_content.assert_called_once_with(
  636. self.si,
  637. self.obj_type,
  638. property_list=self.prop_list,
  639. container_ref=self.container_ref,
  640. traversal_spec=self.traversal_spec,
  641. local_properties=False,
  642. )
  643. self.assertEqual(propSet_prop.call_count, 1)
  644. self.assertEqual(obj_prop.call_count, 1)
  645. self.assertEqual(len(ret), 1)
  646. self.assertDictEqual(ret[0], {"object": inner_obj_mock})
  647. def test_multiple_element_content(self):
  648. # obj1
  649. obj1_mock = MagicMock()
  650. # obj1.propSet
  651. obj1_propSet_prop = PropertyMock(return_value=[])
  652. type(obj1_mock).propSet = obj1_propSet_prop
  653. # obj1.obj
  654. obj1_inner_obj_mock = MagicMock()
  655. obj1_obj_prop = PropertyMock(return_value=obj1_inner_obj_mock)
  656. type(obj1_mock).obj = obj1_obj_prop
  657. # obj2
  658. obj2_mock = MagicMock()
  659. # obj2.propSet
  660. obj2_propSet_prop = PropertyMock(return_value=[])
  661. type(obj2_mock).propSet = obj2_propSet_prop
  662. # obj2.obj
  663. obj2_inner_obj_mock = MagicMock()
  664. obj2_obj_prop = PropertyMock(return_value=obj2_inner_obj_mock)
  665. type(obj2_mock).obj = obj2_obj_prop
  666. get_content = MagicMock(return_value=[obj1_mock, obj2_mock])
  667. with patch("salt.utils.vmware.get_content", get_content):
  668. ret = salt.utils.vmware.get_mors_with_properties(
  669. self.si,
  670. self.obj_type,
  671. self.prop_list,
  672. self.container_ref,
  673. self.traversal_spec,
  674. )
  675. get_content.assert_called_once_with(
  676. self.si,
  677. self.obj_type,
  678. property_list=self.prop_list,
  679. container_ref=self.container_ref,
  680. traversal_spec=self.traversal_spec,
  681. local_properties=False,
  682. )
  683. self.assertEqual(obj1_propSet_prop.call_count, 1)
  684. self.assertEqual(obj2_propSet_prop.call_count, 1)
  685. self.assertEqual(obj1_obj_prop.call_count, 1)
  686. self.assertEqual(obj2_obj_prop.call_count, 1)
  687. self.assertEqual(len(ret), 2)
  688. self.assertDictEqual(ret[0], {"object": obj1_inner_obj_mock})
  689. self.assertDictEqual(ret[1], {"object": obj2_inner_obj_mock})
  690. def test_one_elem_one_property(self):
  691. obj_mock = MagicMock()
  692. # property mock
  693. prop_set_obj_mock = MagicMock()
  694. prop_set_obj_name_prop = PropertyMock(return_value="prop_name")
  695. prop_set_obj_val_prop = PropertyMock(return_value="prop_value")
  696. type(prop_set_obj_mock).name = prop_set_obj_name_prop
  697. type(prop_set_obj_mock).val = prop_set_obj_val_prop
  698. # obj.propSet
  699. propSet_prop = PropertyMock(return_value=[prop_set_obj_mock])
  700. type(obj_mock).propSet = propSet_prop
  701. # obj.obj
  702. inner_obj_mock = MagicMock()
  703. obj_prop = PropertyMock(return_value=inner_obj_mock)
  704. type(obj_mock).obj = obj_prop
  705. get_content = MagicMock(return_value=[obj_mock])
  706. with patch("salt.utils.vmware.get_content", get_content):
  707. ret = salt.utils.vmware.get_mors_with_properties(
  708. self.si,
  709. self.obj_type,
  710. self.prop_list,
  711. self.container_ref,
  712. self.traversal_spec,
  713. local_properties=False,
  714. )
  715. get_content.assert_called_once_with(
  716. self.si,
  717. self.obj_type,
  718. property_list=self.prop_list,
  719. container_ref=self.container_ref,
  720. traversal_spec=self.traversal_spec,
  721. local_properties=False,
  722. )
  723. self.assertEqual(propSet_prop.call_count, 1)
  724. self.assertEqual(prop_set_obj_name_prop.call_count, 1)
  725. self.assertEqual(prop_set_obj_val_prop.call_count, 1)
  726. self.assertEqual(obj_prop.call_count, 1)
  727. self.assertEqual(len(ret), 1)
  728. self.assertDictEqual(
  729. ret[0], {"prop_name": "prop_value", "object": inner_obj_mock}
  730. )
  731. def test_one_elem_multiple_properties(self):
  732. obj_mock = MagicMock()
  733. # property1 mock
  734. prop_set_obj1_mock = MagicMock()
  735. prop_set_obj1_name_prop = PropertyMock(return_value="prop_name1")
  736. prop_set_obj1_val_prop = PropertyMock(return_value="prop_value1")
  737. type(prop_set_obj1_mock).name = prop_set_obj1_name_prop
  738. type(prop_set_obj1_mock).val = prop_set_obj1_val_prop
  739. # property2 mock
  740. prop_set_obj2_mock = MagicMock()
  741. prop_set_obj2_name_prop = PropertyMock(return_value="prop_name2")
  742. prop_set_obj2_val_prop = PropertyMock(return_value="prop_value2")
  743. type(prop_set_obj2_mock).name = prop_set_obj2_name_prop
  744. type(prop_set_obj2_mock).val = prop_set_obj2_val_prop
  745. # obj.propSet
  746. propSet_prop = PropertyMock(
  747. return_value=[prop_set_obj1_mock, prop_set_obj2_mock]
  748. )
  749. type(obj_mock).propSet = propSet_prop
  750. # obj.obj
  751. inner_obj_mock = MagicMock()
  752. obj_prop = PropertyMock(return_value=inner_obj_mock)
  753. type(obj_mock).obj = obj_prop
  754. get_content = MagicMock(return_value=[obj_mock])
  755. with patch("salt.utils.vmware.get_content", get_content):
  756. ret = salt.utils.vmware.get_mors_with_properties(
  757. self.si,
  758. self.obj_type,
  759. self.prop_list,
  760. self.container_ref,
  761. self.traversal_spec,
  762. )
  763. get_content.assert_called_once_with(
  764. self.si,
  765. self.obj_type,
  766. property_list=self.prop_list,
  767. container_ref=self.container_ref,
  768. traversal_spec=self.traversal_spec,
  769. local_properties=False,
  770. )
  771. self.assertEqual(propSet_prop.call_count, 1)
  772. self.assertEqual(prop_set_obj1_name_prop.call_count, 1)
  773. self.assertEqual(prop_set_obj1_val_prop.call_count, 1)
  774. self.assertEqual(prop_set_obj2_name_prop.call_count, 1)
  775. self.assertEqual(prop_set_obj2_val_prop.call_count, 1)
  776. self.assertEqual(obj_prop.call_count, 1)
  777. self.assertEqual(len(ret), 1)
  778. self.assertDictEqual(
  779. ret[0],
  780. {
  781. "prop_name1": "prop_value1",
  782. "prop_name2": "prop_value2",
  783. "object": inner_obj_mock,
  784. },
  785. )
  786. @skipIf(not HAS_PYVMOMI, "The 'pyvmomi' library is missing")
  787. class GetPropertiesOfManagedObjectTestCase(TestCase):
  788. """
  789. Tests for salt.utils.get_properties_of_managed_object
  790. """
  791. def setUp(self):
  792. patches = (
  793. ("salt.utils.vmware.get_service_instance_from_managed_object", MagicMock()),
  794. (
  795. "salt.utils.vmware.get_mors_with_properties",
  796. MagicMock(return_value=[MagicMock()]),
  797. ),
  798. )
  799. for mod, mock in patches:
  800. patcher = patch(mod, mock)
  801. patcher.start()
  802. self.addCleanup(patcher.stop)
  803. self.mock_si = MagicMock()
  804. self.fake_mo_ref = vim.ManagedEntity("Fake")
  805. self.mock_props = MagicMock()
  806. self.mock_item_name = {"name": "fake_name"}
  807. self.mock_item = MagicMock()
  808. def test_get_service_instance_from_managed_object_call(self):
  809. mock_get_instance_from_managed_object = MagicMock()
  810. with patch(
  811. "salt.utils.vmware.get_service_instance_from_managed_object",
  812. mock_get_instance_from_managed_object,
  813. ):
  814. salt.utils.vmware.get_properties_of_managed_object(
  815. self.fake_mo_ref, self.mock_props
  816. )
  817. mock_get_instance_from_managed_object.assert_called_once_with(self.fake_mo_ref)
  818. def test_get_mors_with_properties_calls(self):
  819. mock_get_mors_with_properties = MagicMock(return_value=[MagicMock()])
  820. with patch(
  821. "salt.utils.vmware.get_service_instance_from_managed_object",
  822. MagicMock(return_value=self.mock_si),
  823. ):
  824. with patch(
  825. "salt.utils.vmware.get_mors_with_properties",
  826. mock_get_mors_with_properties,
  827. ):
  828. salt.utils.vmware.get_properties_of_managed_object(
  829. self.fake_mo_ref, self.mock_props
  830. )
  831. mock_get_mors_with_properties.assert_has_calls(
  832. [
  833. call(
  834. self.mock_si,
  835. vim.ManagedEntity,
  836. container_ref=self.fake_mo_ref,
  837. property_list=["name"],
  838. local_properties=True,
  839. ),
  840. call(
  841. self.mock_si,
  842. vim.ManagedEntity,
  843. container_ref=self.fake_mo_ref,
  844. property_list=self.mock_props,
  845. local_properties=True,
  846. ),
  847. ]
  848. )
  849. def test_managed_object_no_name_property(self):
  850. with patch(
  851. "salt.utils.vmware.get_mors_with_properties",
  852. MagicMock(side_effect=[vmodl.query.InvalidProperty(), []]),
  853. ):
  854. with self.assertRaises(VMwareApiError) as excinfo:
  855. salt.utils.vmware.get_properties_of_managed_object(
  856. self.fake_mo_ref, self.mock_props
  857. )
  858. self.assertEqual(
  859. "Properties of managed object '<unnamed>' weren't " "retrieved",
  860. excinfo.exception.strerror,
  861. )
  862. def test_no_items_named_object(self):
  863. with patch(
  864. "salt.utils.vmware.get_mors_with_properties",
  865. MagicMock(side_effect=[[self.mock_item_name], []]),
  866. ):
  867. with self.assertRaises(VMwareApiError) as excinfo:
  868. salt.utils.vmware.get_properties_of_managed_object(
  869. self.fake_mo_ref, self.mock_props
  870. )
  871. self.assertEqual(
  872. "Properties of managed object 'fake_name' weren't " "retrieved",
  873. excinfo.exception.strerror,
  874. )
  875. @skipIf(not HAS_PYVMOMI, "The 'pyvmomi' library is missing")
  876. class GetManagedObjectName(TestCase):
  877. """
  878. Tests for salt.utils.get_managed_object_name
  879. """
  880. def setUp(self):
  881. patches = (
  882. (
  883. "salt.utils.vmware.get_properties_of_managed_object",
  884. MagicMock(return_value={"key": "value"}),
  885. ),
  886. )
  887. for mod, mock in patches:
  888. patcher = patch(mod, mock)
  889. patcher.start()
  890. self.addCleanup(patcher.stop)
  891. self.mock_mo_ref = MagicMock()
  892. def test_get_properties_of_managed_object_call(self):
  893. mock_get_properties_of_managed_object = MagicMock()
  894. with patch(
  895. "salt.utils.vmware.get_properties_of_managed_object",
  896. mock_get_properties_of_managed_object,
  897. ):
  898. salt.utils.vmware.get_managed_object_name(self.mock_mo_ref)
  899. mock_get_properties_of_managed_object.assert_called_once_with(
  900. self.mock_mo_ref, ["name"]
  901. )
  902. def test_no_name_in_property_dict(self):
  903. ret = salt.utils.vmware.get_managed_object_name(self.mock_mo_ref)
  904. self.assertIsNone(ret)
  905. def test_return_managed_object_name(self):
  906. mock_get_properties_of_managed_object = MagicMock()
  907. with patch(
  908. "salt.utils.vmware.get_properties_of_managed_object",
  909. MagicMock(return_value={"name": "fake_name"}),
  910. ):
  911. ret = salt.utils.vmware.get_managed_object_name(self.mock_mo_ref)
  912. self.assertEqual(ret, "fake_name")
  913. @skipIf(not HAS_PYVMOMI, "The 'pyvmomi' library is missing")
  914. class GetContentTestCase(TestCase):
  915. """
  916. Tests for salt.utils.get_content
  917. """
  918. # Method names to be patched
  919. traversal_spec_method_name = (
  920. "salt.utils.vmware.vmodl.query.PropertyCollector.TraversalSpec"
  921. )
  922. property_spec_method_name = (
  923. "salt.utils.vmware.vmodl.query.PropertyCollector.PropertySpec"
  924. )
  925. obj_spec_method_name = "salt.utils.vmware.vmodl.query.PropertyCollector.ObjectSpec"
  926. filter_spec_method_name = (
  927. "salt.utils.vmware.vmodl.query.PropertyCollector.FilterSpec"
  928. )
  929. # Class variables
  930. si_mock = None
  931. root_folder_mock = None
  932. root_folder_prop = None
  933. container_view_mock = None
  934. create_container_view_mock = None
  935. result_mock = None
  936. retrieve_contents_mock = None
  937. destroy_mock = None
  938. obj_type_mock = None
  939. traversal_spec_ret_mock = None
  940. traversal_spec_mock = None
  941. property_spec_ret_mock = None
  942. property_spec_mock = None
  943. obj_spec_ret_mock = None
  944. obj_spec_mock = None
  945. filter_spec_ret_mock = None
  946. filter_spec_mock = None
  947. def setUp(self):
  948. patches = (
  949. ("salt.utils.vmware.get_root_folder", MagicMock()),
  950. (
  951. "salt.utils.vmware.vmodl.query.PropertyCollector.TraversalSpec",
  952. MagicMock(return_value=MagicMock()),
  953. ),
  954. (
  955. "salt.utils.vmware.vmodl.query.PropertyCollector.PropertySpec",
  956. MagicMock(return_value=MagicMock()),
  957. ),
  958. (
  959. "salt.utils.vmware.vmodl.query.PropertyCollector.ObjectSpec",
  960. MagicMock(return_value=MagicMock()),
  961. ),
  962. (
  963. "salt.utils.vmware.vmodl.query.PropertyCollector.FilterSpec",
  964. MagicMock(return_value=MagicMock()),
  965. ),
  966. )
  967. for mod, mock in patches:
  968. patcher = patch(mod, mock)
  969. patcher.start()
  970. self.addCleanup(patcher.stop)
  971. # setup the service instance
  972. self.si_mock = MagicMock()
  973. # RootFolder
  974. self.root_folder_mock = MagicMock()
  975. self.get_root_folder_mock = MagicMock(return_value=self.root_folder_mock)
  976. # CreateContainerView()
  977. self.container_view_mock = MagicMock()
  978. self.create_container_view_mock = MagicMock(
  979. return_value=self.container_view_mock
  980. )
  981. self.si_mock.content.viewManager.CreateContainerView = (
  982. self.create_container_view_mock
  983. )
  984. # RetrieveContents()
  985. self.result_mock = MagicMock()
  986. self.retrieve_contents_mock = MagicMock(return_value=self.result_mock)
  987. self.si_mock.content.propertyCollector.RetrieveContents = (
  988. self.retrieve_contents_mock
  989. )
  990. # Destroy()
  991. self.destroy_mock = MagicMock()
  992. self.container_view_mock.Destroy = self.destroy_mock
  993. # override mocks
  994. self.obj_type_mock = MagicMock()
  995. self.traversal_spec_ret_mock = MagicMock()
  996. self.traversal_spec_mock = MagicMock(return_value=self.traversal_spec_ret_mock)
  997. self.property_spec_ret_mock = MagicMock()
  998. self.property_spec_mock = MagicMock(return_value=self.property_spec_ret_mock)
  999. self.obj_spec_ret_mock = MagicMock()
  1000. self.obj_spec_mock = MagicMock(return_value=self.obj_spec_ret_mock)
  1001. self.filter_spec_ret_mock = MagicMock()
  1002. self.filter_spec_mock = MagicMock(return_value=self.filter_spec_ret_mock)
  1003. def test_empty_container_ref(self):
  1004. with patch("salt.utils.vmware.get_root_folder", self.get_root_folder_mock):
  1005. salt.utils.vmware.get_content(self.si_mock, self.obj_type_mock)
  1006. self.get_root_folder_mock.assert_called_once_with(self.si_mock)
  1007. self.create_container_view_mock.assert_called_once_with(
  1008. self.root_folder_mock, [self.obj_type_mock], True
  1009. )
  1010. def test_defined_container_ref(self):
  1011. container_ref_mock = MagicMock()
  1012. with patch("salt.utils.vmware.get_root_folder", self.get_root_folder_mock):
  1013. with patch(self.obj_spec_method_name, self.obj_type_mock):
  1014. salt.utils.vmware.get_content(
  1015. self.si_mock, self.obj_type_mock, container_ref=container_ref_mock
  1016. )
  1017. self.assertEqual(self.get_root_folder_mock.call_count, 0)
  1018. self.create_container_view_mock.assert_called_once_with(
  1019. container_ref_mock, [self.obj_type_mock], True
  1020. )
  1021. # Also checks destroy is called
  1022. def test_local_traversal_spec(self):
  1023. with patch("salt.utils.vmware.get_root_folder", self.get_root_folder_mock):
  1024. with patch(self.traversal_spec_method_name, self.traversal_spec_mock):
  1025. with patch(self.obj_spec_method_name, self.obj_spec_mock):
  1026. ret = salt.utils.vmware.get_content(
  1027. self.si_mock, self.obj_type_mock
  1028. )
  1029. self.create_container_view_mock.assert_called_once_with(
  1030. self.root_folder_mock, [self.obj_type_mock], True
  1031. )
  1032. self.traversal_spec_mock.assert_called_once_with(
  1033. name="traverseEntities",
  1034. path="view",
  1035. skip=False,
  1036. type=vim.view.ContainerView,
  1037. )
  1038. self.obj_spec_mock.assert_called_once_with(
  1039. obj=self.container_view_mock,
  1040. skip=True,
  1041. selectSet=[self.traversal_spec_ret_mock],
  1042. )
  1043. # check destroy is called
  1044. self.assertEqual(self.destroy_mock.call_count, 1)
  1045. def test_create_container_view_raise_no_permission(self):
  1046. exc = vim.fault.NoPermission()
  1047. exc.privilegeId = "Fake privilege"
  1048. self.si_mock.content.viewManager.CreateContainerView = MagicMock(
  1049. side_effect=exc
  1050. )
  1051. with patch("salt.utils.vmware.get_root_folder", self.get_root_folder_mock):
  1052. with self.assertRaises(VMwareApiError) as excinfo:
  1053. salt.utils.vmware.get_content(self.si_mock, self.obj_type_mock)
  1054. self.assertEqual(
  1055. excinfo.exception.strerror,
  1056. "Not enough permissions. Required privilege: " "Fake privilege",
  1057. )
  1058. def test_create_container_view_raise_vim_fault(self):
  1059. exc = vim.fault.VimFault()
  1060. exc.msg = "VimFault msg"
  1061. self.si_mock.content.viewManager.CreateContainerView = MagicMock(
  1062. side_effect=exc
  1063. )
  1064. with patch("salt.utils.vmware.get_root_folder", self.get_root_folder_mock):
  1065. with self.assertRaises(VMwareApiError) as excinfo:
  1066. salt.utils.vmware.get_content(self.si_mock, self.obj_type_mock)
  1067. self.assertEqual(excinfo.exception.strerror, "VimFault msg")
  1068. def test_create_container_view_raise_runtime_fault(self):
  1069. exc = vmodl.RuntimeFault()
  1070. exc.msg = "RuntimeFault msg"
  1071. self.si_mock.content.viewManager.CreateContainerView = MagicMock(
  1072. side_effect=exc
  1073. )
  1074. with patch("salt.utils.vmware.get_root_folder", self.get_root_folder_mock):
  1075. with self.assertRaises(VMwareRuntimeError) as excinfo:
  1076. salt.utils.vmware.get_content(self.si_mock, self.obj_type_mock)
  1077. self.assertEqual(excinfo.exception.strerror, "RuntimeFault msg")
  1078. def test_destroy_raise_no_permission(self):
  1079. exc = vim.fault.NoPermission()
  1080. exc.privilegeId = "Fake privilege"
  1081. self.si_mock.content.viewManager.CreateContainerView = MagicMock(
  1082. return_value=MagicMock(Destroy=MagicMock(side_effect=exc))
  1083. )
  1084. with patch("salt.utils.vmware.get_root_folder", self.get_root_folder_mock):
  1085. with self.assertRaises(VMwareApiError) as excinfo:
  1086. salt.utils.vmware.get_content(self.si_mock, self.obj_type_mock)
  1087. self.assertEqual(
  1088. excinfo.exception.strerror,
  1089. "Not enough permissions. Required privilege: " "Fake privilege",
  1090. )
  1091. def test_destroy_raise_vim_fault(self):
  1092. exc = vim.fault.VimFault()
  1093. exc.msg = "VimFault msg"
  1094. self.si_mock.content.viewManager.CreateContainerView = MagicMock(
  1095. return_value=MagicMock(Destroy=MagicMock(side_effect=exc))
  1096. )
  1097. with patch("salt.utils.vmware.get_root_folder", self.get_root_folder_mock):
  1098. with self.assertRaises(VMwareApiError) as excinfo:
  1099. salt.utils.vmware.get_content(self.si_mock, self.obj_type_mock)
  1100. self.assertEqual(excinfo.exception.strerror, "VimFault msg")
  1101. def test_destroy_raise_runtime_fault(self):
  1102. exc = vmodl.RuntimeFault()
  1103. exc.msg = "RuntimeFault msg"
  1104. self.si_mock.content.viewManager.CreateContainerView = MagicMock(
  1105. return_value=MagicMock(Destroy=MagicMock(side_effect=exc))
  1106. )
  1107. with patch("salt.utils.vmware.get_root_folder", self.get_root_folder_mock):
  1108. with self.assertRaises(VMwareRuntimeError) as excinfo:
  1109. salt.utils.vmware.get_content(self.si_mock, self.obj_type_mock)
  1110. self.assertEqual(excinfo.exception.strerror, "RuntimeFault msg")
  1111. # Also checks destroy is not called
  1112. def test_external_traversal_spec(self):
  1113. traversal_spec_obj_mock = MagicMock()
  1114. with patch("salt.utils.vmware.get_root_folder", self.get_root_folder_mock):
  1115. with patch(self.traversal_spec_method_name, self.traversal_spec_mock):
  1116. with patch(self.obj_spec_method_name, self.obj_spec_mock):
  1117. salt.utils.vmware.get_content(
  1118. self.si_mock,
  1119. self.obj_type_mock,
  1120. traversal_spec=traversal_spec_obj_mock,
  1121. )
  1122. self.obj_spec_mock.assert_called_once_with(
  1123. obj=self.root_folder_mock, skip=True, selectSet=[traversal_spec_obj_mock]
  1124. )
  1125. # Check local traversal methods are not called
  1126. self.assertEqual(self.create_container_view_mock.call_count, 0)
  1127. self.assertEqual(self.traversal_spec_mock.call_count, 0)
  1128. # check destroy is not called
  1129. self.assertEqual(self.destroy_mock.call_count, 0)
  1130. def test_property_obj_filter_specs_and_contents(self):
  1131. with patch(self.traversal_spec_method_name, self.traversal_spec_mock):
  1132. with patch(self.property_spec_method_name, self.property_spec_mock):
  1133. with patch(self.obj_spec_method_name, self.obj_spec_mock):
  1134. with patch(self.filter_spec_method_name, self.filter_spec_mock):
  1135. ret = salt.utils.vmware.get_content(
  1136. self.si_mock, self.obj_type_mock
  1137. )
  1138. self.traversal_spec_mock.assert_called_once_with(
  1139. name="traverseEntities",
  1140. path="view",
  1141. skip=False,
  1142. type=vim.view.ContainerView,
  1143. )
  1144. self.property_spec_mock.assert_called_once_with(
  1145. type=self.obj_type_mock, all=True, pathSet=None
  1146. )
  1147. self.obj_spec_mock.assert_called_once_with(
  1148. obj=self.container_view_mock,
  1149. skip=True,
  1150. selectSet=[self.traversal_spec_ret_mock],
  1151. )
  1152. self.retrieve_contents_mock.assert_called_once_with([self.filter_spec_ret_mock])
  1153. self.assertEqual(ret, self.result_mock)
  1154. def test_retrieve_contents_raise_no_permission(self):
  1155. exc = vim.fault.NoPermission()
  1156. exc.privilegeId = "Fake privilege"
  1157. self.si_mock.content.propertyCollector.RetrieveContents = MagicMock(
  1158. side_effect=exc
  1159. )
  1160. with self.assertRaises(VMwareApiError) as excinfo:
  1161. salt.utils.vmware.get_content(self.si_mock, self.obj_type_mock)
  1162. self.assertEqual(
  1163. excinfo.exception.strerror,
  1164. "Not enough permissions. Required privilege: " "Fake privilege",
  1165. )
  1166. def test_retrieve_contents_raise_vim_fault(self):
  1167. exc = vim.fault.VimFault()
  1168. exc.msg = "VimFault msg"
  1169. self.si_mock.content.propertyCollector.RetrieveContents = MagicMock(
  1170. side_effect=exc
  1171. )
  1172. with self.assertRaises(VMwareApiError) as excinfo:
  1173. salt.utils.vmware.get_content(self.si_mock, self.obj_type_mock)
  1174. self.assertEqual(excinfo.exception.strerror, "VimFault msg")
  1175. def test_retrieve_contents_raise_runtime_fault(self):
  1176. exc = vmodl.RuntimeFault()
  1177. exc.msg = "RuntimeFault msg"
  1178. self.si_mock.content.propertyCollector.RetrieveContents = MagicMock(
  1179. side_effect=exc
  1180. )
  1181. with self.assertRaises(VMwareRuntimeError) as excinfo:
  1182. salt.utils.vmware.get_content(self.si_mock, self.obj_type_mock)
  1183. self.assertEqual(excinfo.exception.strerror, "RuntimeFault msg")
  1184. def test_local_properties_set(self):
  1185. container_ref_mock = MagicMock()
  1186. with patch(self.traversal_spec_method_name, self.traversal_spec_mock):
  1187. with patch(self.property_spec_method_name, self.property_spec_mock):
  1188. with patch(self.obj_spec_method_name, self.obj_spec_mock):
  1189. salt.utils.vmware.get_content(
  1190. self.si_mock,
  1191. self.obj_type_mock,
  1192. container_ref=container_ref_mock,
  1193. local_properties=True,
  1194. )
  1195. self.assertEqual(self.traversal_spec_mock.call_count, 0)
  1196. self.obj_spec_mock.assert_called_once_with(
  1197. obj=container_ref_mock, skip=False, selectSet=None
  1198. )
  1199. @skipIf(not HAS_PYVMOMI, "The 'pyvmomi' library is missing")
  1200. class GetRootFolderTestCase(TestCase):
  1201. """
  1202. Tests for salt.utils.get_root_folder
  1203. """
  1204. def setUp(self):
  1205. self.mock_root_folder = MagicMock()
  1206. self.mock_content = MagicMock(rootFolder=self.mock_root_folder)
  1207. self.mock_si = MagicMock(
  1208. RetrieveContent=MagicMock(return_value=self.mock_content)
  1209. )
  1210. def test_raise_no_permission(self):
  1211. exc = vim.fault.NoPermission()
  1212. exc.privilegeId = "Fake privilege"
  1213. type(self.mock_content).rootFolder = PropertyMock(side_effect=exc)
  1214. with self.assertRaises(VMwareApiError) as excinfo:
  1215. salt.utils.vmware.get_root_folder(self.mock_si)
  1216. self.assertEqual(
  1217. excinfo.exception.strerror,
  1218. "Not enough permissions. Required privilege: " "Fake privilege",
  1219. )
  1220. def test_raise_vim_fault(self):
  1221. exc = vim.fault.VimFault()
  1222. exc.msg = "VimFault msg"
  1223. type(self.mock_content).rootFolder = PropertyMock(side_effect=exc)
  1224. with self.assertRaises(VMwareApiError) as excinfo:
  1225. salt.utils.vmware.get_root_folder(self.mock_si)
  1226. self.assertEqual(excinfo.exception.strerror, "VimFault msg")
  1227. def test_raise_runtime_fault(self):
  1228. exc = vmodl.RuntimeFault()
  1229. exc.msg = "RuntimeFault msg"
  1230. type(self.mock_content).rootFolder = PropertyMock(side_effect=exc)
  1231. with self.assertRaises(VMwareRuntimeError) as excinfo:
  1232. salt.utils.vmware.get_root_folder(self.mock_si)
  1233. self.assertEqual(excinfo.exception.strerror, "RuntimeFault msg")
  1234. def test_return(self):
  1235. ret = salt.utils.vmware.get_root_folder(self.mock_si)
  1236. self.assertEqual(ret, self.mock_root_folder)
  1237. @skipIf(not HAS_PYVMOMI, "The 'pyvmomi' library is missing")
  1238. class GetServiceInfoTestCase(TestCase):
  1239. """
  1240. Tests for salt.utils.vmware.get_service_info
  1241. """
  1242. def setUp(self):
  1243. self.mock_about = MagicMock()
  1244. self.mock_si = MagicMock(content=MagicMock())
  1245. type(self.mock_si.content).about = PropertyMock(return_value=self.mock_about)
  1246. def tearDown(self):
  1247. for attr in ("mock_si", "mock_about"):
  1248. delattr(self, attr)
  1249. def test_about_ret(self):
  1250. ret = salt.utils.vmware.get_service_info(self.mock_si)
  1251. self.assertEqual(ret, self.mock_about)
  1252. def test_about_raises_no_permission(self):
  1253. exc = vim.fault.NoPermission()
  1254. exc.privilegeId = "Fake privilege"
  1255. type(self.mock_si.content).about = PropertyMock(side_effect=exc)
  1256. with self.assertRaises(VMwareApiError) as excinfo:
  1257. salt.utils.vmware.get_service_info(self.mock_si)
  1258. self.assertEqual(
  1259. excinfo.exception.strerror,
  1260. "Not enough permissions. Required privilege: " "Fake privilege",
  1261. )
  1262. def test_about_raises_vim_fault(self):
  1263. exc = vim.fault.VimFault()
  1264. exc.msg = "VimFault msg"
  1265. type(self.mock_si.content).about = PropertyMock(side_effect=exc)
  1266. with self.assertRaises(VMwareApiError) as excinfo:
  1267. salt.utils.vmware.get_service_info(self.mock_si)
  1268. self.assertEqual(excinfo.exception.strerror, "VimFault msg")
  1269. def test_about_raises_runtime_fault(self):
  1270. exc = vmodl.RuntimeFault()
  1271. exc.msg = "RuntimeFault msg"
  1272. type(self.mock_si.content).about = PropertyMock(side_effect=exc)
  1273. with self.assertRaises(VMwareRuntimeError) as excinfo:
  1274. salt.utils.vmware.get_service_info(self.mock_si)
  1275. self.assertEqual(excinfo.exception.strerror, "RuntimeFault msg")
  1276. @skipIf(not HAS_PYVMOMI, "The 'pyvmomi' library is missing")
  1277. @skipIf(not HAS_GSSAPI, "The 'gssapi' library is missing")
  1278. class GssapiTokenTest(TestCase):
  1279. """
  1280. Test cases for salt.utils.vmware.get_gssapi_token
  1281. """
  1282. def setUp(self):
  1283. patches = (
  1284. ("gssapi.Name", MagicMock(return_value="service")),
  1285. ("gssapi.InitContext", MagicMock()),
  1286. )
  1287. for mod, mock in patches:
  1288. patcher = patch(mod, mock)
  1289. patcher.start()
  1290. self.addCleanup(patcher.stop)
  1291. def test_no_gssapi(self):
  1292. with patch("salt.utils.vmware.HAS_GSSAPI", False):
  1293. with self.assertRaises(ImportError) as excinfo:
  1294. salt.utils.vmware.get_gssapi_token("principal", "host", "domain")
  1295. self.assertIn(
  1296. "The gssapi library is not imported.", excinfo.exception.message
  1297. )
  1298. @skipIf(not HAS_GSSAPI, "The 'gssapi' library is missing")
  1299. def test_service_name(self):
  1300. mock_name = MagicMock()
  1301. with patch.object(salt.utils.vmware.gssapi, "Name", mock_name):
  1302. with self.assertRaises(CommandExecutionError):
  1303. salt.utils.vmware.get_gssapi_token("principal", "host", "domain")
  1304. mock_name.assert_called_once_with(
  1305. "principal/host@domain", gssapi.C_NT_USER_NAME
  1306. )
  1307. @skipIf(not HAS_GSSAPI, "The 'gssapi' library is missing")
  1308. def test_out_token_defined(self):
  1309. mock_context = MagicMock(return_value=MagicMock())
  1310. mock_context.return_value.established = False
  1311. mock_context.return_value.step = MagicMock(return_value="out_token")
  1312. with patch.object(salt.utils.vmware.gssapi, "InitContext", mock_context):
  1313. ret = salt.utils.vmware.get_gssapi_token("principal", "host", "domain")
  1314. self.assertEqual(mock_context.return_value.step.called, 1)
  1315. self.assertEqual(ret, base64.b64encode(b"out_token"))
  1316. @skipIf(not HAS_GSSAPI, "The 'gssapi' library is missing")
  1317. def test_out_token_undefined(self):
  1318. mock_context = MagicMock(return_value=MagicMock())
  1319. mock_context.return_value.established = False
  1320. mock_context.return_value.step = MagicMock(return_value=None)
  1321. with patch.object(salt.utils.vmware.gssapi, "InitContext", mock_context):
  1322. with self.assertRaises(CommandExecutionError) as excinfo:
  1323. salt.utils.vmware.get_gssapi_token("principal", "host", "domain")
  1324. self.assertEqual(mock_context.return_value.step.called, 1)
  1325. self.assertIn("Can't receive token", excinfo.exception.strerror)
  1326. @skipIf(not HAS_GSSAPI, "The 'gssapi' library is missing")
  1327. def test_context_extablished(self):
  1328. mock_context = MagicMock(return_value=MagicMock())
  1329. mock_context.return_value.established = True
  1330. mock_context.return_value.step = MagicMock(return_value="out_token")
  1331. with patch.object(salt.utils.vmware.gssapi, "InitContext", mock_context):
  1332. mock_context.established = True
  1333. mock_context.step = MagicMock(return_value=None)
  1334. with self.assertRaises(CommandExecutionError) as excinfo:
  1335. salt.utils.vmware.get_gssapi_token("principal", "host", "domain")
  1336. self.assertEqual(mock_context.step.called, 0)
  1337. self.assertIn(
  1338. "Context established, but didn't receive token",
  1339. excinfo.exception.strerror,
  1340. )
  1341. @skipIf(not HAS_PYVMOMI, "The 'pyvmomi' library is missing")
  1342. class PrivateGetServiceInstanceTestCase(TestCase):
  1343. """
  1344. Tests for salt.utils.vmware._get_service_instance
  1345. """
  1346. def setUp(self):
  1347. patches = (
  1348. ("salt.utils.vmware.SmartConnect", MagicMock()),
  1349. ("salt.utils.vmware.Disconnect", MagicMock()),
  1350. (
  1351. "salt.utils.vmware.get_gssapi_token",
  1352. MagicMock(return_value="fake_token"),
  1353. ),
  1354. )
  1355. for mod, mock in patches:
  1356. patcher = patch(mod, mock)
  1357. patcher.start()
  1358. self.addCleanup(patcher.stop)
  1359. def test_invalid_mechianism(self):
  1360. with self.assertRaises(CommandExecutionError) as excinfo:
  1361. salt.utils.vmware._get_service_instance(
  1362. host="fake_host.fqdn",
  1363. username="fake_username",
  1364. password="fake_password",
  1365. protocol="fake_protocol",
  1366. port=1,
  1367. mechanism="invalid_mechanism",
  1368. principal="fake principal",
  1369. domain="fake_domain",
  1370. )
  1371. self.assertIn("Unsupported mechanism", excinfo.exception.strerror)
  1372. def test_userpass_mechanism_empty_username(self):
  1373. with self.assertRaises(CommandExecutionError) as excinfo:
  1374. salt.utils.vmware._get_service_instance(
  1375. host="fake_host.fqdn",
  1376. username=None,
  1377. password="fake_password",
  1378. protocol="fake_protocol",
  1379. port=1,
  1380. mechanism="userpass",
  1381. principal="fake principal",
  1382. domain="fake_domain",
  1383. )
  1384. self.assertIn("mandatory parameter 'username'", excinfo.exception.strerror)
  1385. def test_userpass_mechanism_empty_password(self):
  1386. with self.assertRaises(CommandExecutionError) as excinfo:
  1387. salt.utils.vmware._get_service_instance(
  1388. host="fake_host.fqdn",
  1389. username="fake_username",
  1390. password=None,
  1391. protocol="fake_protocol",
  1392. port=1,
  1393. mechanism="userpass",
  1394. principal="fake principal",
  1395. domain="fake_domain",
  1396. )
  1397. self.assertIn("mandatory parameter 'password'", excinfo.exception.strerror)
  1398. def test_userpass_mechanism_no_domain(self):
  1399. mock_sc = MagicMock()
  1400. with patch("salt.utils.vmware.SmartConnect", mock_sc):
  1401. salt.utils.vmware._get_service_instance(
  1402. host="fake_host.fqdn",
  1403. username="fake_username",
  1404. password="fake_password",
  1405. protocol="fake_protocol",
  1406. port=1,
  1407. mechanism="userpass",
  1408. principal="fake principal",
  1409. domain=None,
  1410. )
  1411. mock_sc.assert_called_once_with(
  1412. host="fake_host.fqdn",
  1413. user="fake_username",
  1414. pwd="fake_password",
  1415. protocol="fake_protocol",
  1416. port=1,
  1417. b64token=None,
  1418. mechanism="userpass",
  1419. )
  1420. def test_userpass_mech_domain_unused(self):
  1421. mock_sc = MagicMock()
  1422. with patch("salt.utils.vmware.SmartConnect", mock_sc):
  1423. salt.utils.vmware._get_service_instance(
  1424. host="fake_host.fqdn",
  1425. username="fake_username@domain",
  1426. password="fake_password",
  1427. protocol="fake_protocol",
  1428. port=1,
  1429. mechanism="userpass",
  1430. principal="fake principal",
  1431. domain="fake_domain",
  1432. )
  1433. mock_sc.assert_called_once_with(
  1434. host="fake_host.fqdn",
  1435. user="fake_username@domain",
  1436. pwd="fake_password",
  1437. protocol="fake_protocol",
  1438. port=1,
  1439. b64token=None,
  1440. mechanism="userpass",
  1441. )
  1442. mock_sc.reset_mock()
  1443. salt.utils.vmware._get_service_instance(
  1444. host="fake_host.fqdn",
  1445. username="domain\\fake_username",
  1446. password="fake_password",
  1447. protocol="fake_protocol",
  1448. port=1,
  1449. mechanism="userpass",
  1450. principal="fake principal",
  1451. domain="fake_domain",
  1452. )
  1453. mock_sc.assert_called_once_with(
  1454. host="fake_host.fqdn",
  1455. user="domain\\fake_username",
  1456. pwd="fake_password",
  1457. protocol="fake_protocol",
  1458. port=1,
  1459. b64token=None,
  1460. mechanism="userpass",
  1461. )
  1462. def test_sspi_empty_principal(self):
  1463. with self.assertRaises(CommandExecutionError) as excinfo:
  1464. salt.utils.vmware._get_service_instance(
  1465. host="fake_host.fqdn",
  1466. username="fake_username",
  1467. password="fake_password",
  1468. protocol="fake_protocol",
  1469. port=1,
  1470. mechanism="sspi",
  1471. principal=None,
  1472. domain="fake_domain",
  1473. )
  1474. self.assertIn("mandatory parameters are missing", excinfo.exception.strerror)
  1475. def test_sspi_empty_domain(self):
  1476. with self.assertRaises(CommandExecutionError) as excinfo:
  1477. salt.utils.vmware._get_service_instance(
  1478. host="fake_host.fqdn",
  1479. username="fake_username",
  1480. password="fake_password",
  1481. protocol="fake_protocol",
  1482. port=1,
  1483. mechanism="sspi",
  1484. principal="fake_principal",
  1485. domain=None,
  1486. )
  1487. self.assertIn("mandatory parameters are missing", excinfo.exception.strerror)
  1488. def test_sspi_get_token_error(self):
  1489. mock_token = MagicMock(side_effect=Exception("Exception"))
  1490. with patch("salt.utils.vmware.get_gssapi_token", mock_token):
  1491. with self.assertRaises(VMwareConnectionError) as excinfo:
  1492. salt.utils.vmware._get_service_instance(
  1493. host="fake_host.fqdn",
  1494. username="fake_username",
  1495. password="fake_password",
  1496. protocol="fake_protocol",
  1497. port=1,
  1498. mechanism="sspi",
  1499. principal="fake_principal",
  1500. domain="fake_domain",
  1501. )
  1502. mock_token.assert_called_once_with(
  1503. "fake_principal", "fake_host.fqdn", "fake_domain"
  1504. )
  1505. self.assertEqual("Exception", excinfo.exception.strerror)
  1506. def test_sspi_get_token_success_(self):
  1507. mock_token = MagicMock(return_value="fake_token")
  1508. mock_sc = MagicMock()
  1509. with patch("salt.utils.vmware.get_gssapi_token", mock_token):
  1510. with patch("salt.utils.vmware.SmartConnect", mock_sc):
  1511. salt.utils.vmware._get_service_instance(
  1512. host="fake_host.fqdn",
  1513. username="fake_username",
  1514. password="fake_password",
  1515. protocol="fake_protocol",
  1516. port=1,
  1517. mechanism="sspi",
  1518. principal="fake_principal",
  1519. domain="fake_domain",
  1520. )
  1521. mock_token.assert_called_once_with(
  1522. "fake_principal", "fake_host.fqdn", "fake_domain"
  1523. )
  1524. mock_sc.assert_called_once_with(
  1525. host="fake_host.fqdn",
  1526. user="fake_username",
  1527. pwd="fake_password",
  1528. protocol="fake_protocol",
  1529. port=1,
  1530. b64token="fake_token",
  1531. mechanism="sspi",
  1532. )
  1533. def test_first_attempt_successful_connection(self):
  1534. mock_sc = MagicMock()
  1535. with patch("salt.utils.vmware.SmartConnect", mock_sc):
  1536. salt.utils.vmware._get_service_instance(
  1537. host="fake_host.fqdn",
  1538. username="fake_username",
  1539. password="fake_password",
  1540. protocol="fake_protocol",
  1541. port=1,
  1542. mechanism="sspi",
  1543. principal="fake_principal",
  1544. domain="fake_domain",
  1545. )
  1546. mock_sc.assert_called_once_with(
  1547. host="fake_host.fqdn",
  1548. user="fake_username",
  1549. pwd="fake_password",
  1550. protocol="fake_protocol",
  1551. port=1,
  1552. b64token="fake_token",
  1553. mechanism="sspi",
  1554. )
  1555. @skipIf(not SSL_VALIDATION, "SSL validation is not enabled")
  1556. def test_second_attempt_successful_connection(self):
  1557. with patch("ssl.SSLContext", MagicMock()), patch(ssl_context, MagicMock()):
  1558. exc = vim.fault.HostConnectFault()
  1559. exc.msg = "[SSL: CERTIFICATE_VERIFY_FAILED]"
  1560. mock_sc = MagicMock(side_effect=[exc, None])
  1561. mock_ssl = MagicMock()
  1562. with patch("salt.utils.vmware.SmartConnect", mock_sc):
  1563. with patch(ssl_context, mock_ssl):
  1564. salt.utils.vmware._get_service_instance(
  1565. host="fake_host.fqdn",
  1566. username="fake_username",
  1567. password="fake_password",
  1568. protocol="fake_protocol",
  1569. port=1,
  1570. mechanism="sspi",
  1571. principal="fake_principal",
  1572. domain="fake_domain",
  1573. )
  1574. mock_ssl.assert_called_once_with()
  1575. calls = [
  1576. call(
  1577. host="fake_host.fqdn",
  1578. user="fake_username",
  1579. pwd="fake_password",
  1580. protocol="fake_protocol",
  1581. port=1,
  1582. b64token="fake_token",
  1583. mechanism="sspi",
  1584. ),
  1585. call(
  1586. host="fake_host.fqdn",
  1587. user="fake_username",
  1588. pwd="fake_password",
  1589. protocol="fake_protocol",
  1590. port=1,
  1591. sslContext=mock_ssl.return_value,
  1592. b64token="fake_token",
  1593. mechanism="sspi",
  1594. ),
  1595. ]
  1596. mock_sc.assert_has_calls(calls)
  1597. @skipIf(not SSL_VALIDATION, "SSL validation is not enabled")
  1598. def test_third_attempt_successful_connection(self):
  1599. with patch("ssl.SSLContext", MagicMock()), patch(ssl_context, MagicMock()):
  1600. exc = vim.fault.HostConnectFault()
  1601. exc.msg = "[SSL: CERTIFICATE_VERIFY_FAILED]"
  1602. exc2 = Exception("certificate verify failed")
  1603. mock_sc = MagicMock(side_effect=[exc, exc2, None])
  1604. mock_ssl_unverif = MagicMock()
  1605. mock_ssl_context = MagicMock()
  1606. with patch("salt.utils.vmware.SmartConnect", mock_sc):
  1607. with patch(ssl_context, mock_ssl_unverif):
  1608. with patch("ssl.SSLContext", mock_ssl_context):
  1609. salt.utils.vmware._get_service_instance(
  1610. host="fake_host.fqdn",
  1611. username="fake_username",
  1612. password="fake_password",
  1613. protocol="fake_protocol",
  1614. port=1,
  1615. mechanism="sspi",
  1616. principal="fake_principal",
  1617. domain="fake_domain",
  1618. )
  1619. mock_ssl_context.assert_called_once_with(ssl.PROTOCOL_TLSv1)
  1620. mock_ssl_unverif.assert_called_once_with()
  1621. calls = [
  1622. call(
  1623. host="fake_host.fqdn",
  1624. user="fake_username",
  1625. pwd="fake_password",
  1626. protocol="fake_protocol",
  1627. port=1,
  1628. b64token="fake_token",
  1629. mechanism="sspi",
  1630. ),
  1631. call(
  1632. host="fake_host.fqdn",
  1633. user="fake_username",
  1634. pwd="fake_password",
  1635. protocol="fake_protocol",
  1636. port=1,
  1637. sslContext=mock_ssl_unverif.return_value,
  1638. b64token="fake_token",
  1639. mechanism="sspi",
  1640. ),
  1641. call(
  1642. host="fake_host.fqdn",
  1643. user="fake_username",
  1644. pwd="fake_password",
  1645. protocol="fake_protocol",
  1646. port=1,
  1647. sslContext=mock_ssl_context.return_value,
  1648. b64token="fake_token",
  1649. mechanism="sspi",
  1650. ),
  1651. ]
  1652. mock_sc.assert_has_calls(calls)
  1653. def test_first_attempt_unsuccessful_connection_default_error(self):
  1654. exc = Exception("Exception")
  1655. mock_sc = MagicMock(side_effect=exc)
  1656. with patch("salt.utils.vmware.SmartConnect", mock_sc):
  1657. with self.assertRaises(VMwareConnectionError) as excinfo:
  1658. salt.utils.vmware._get_service_instance(
  1659. host="fake_host.fqdn",
  1660. username="fake_username",
  1661. password="fake_password",
  1662. protocol="fake_protocol",
  1663. port=1,
  1664. mechanism="sspi",
  1665. principal="fake_principal",
  1666. domain="fake_domain",
  1667. )
  1668. self.assertEqual(mock_sc.call_count, 1)
  1669. self.assertIn(
  1670. "Could not connect to host 'fake_host.fqdn'",
  1671. excinfo.Exception.message,
  1672. )
  1673. def test_first_attempt_unsuccessful_connection_vim_fault(self):
  1674. exc = vim.fault.VimFault()
  1675. exc.msg = "VimFault"
  1676. mock_sc = MagicMock(side_effect=exc)
  1677. with patch("salt.utils.vmware.SmartConnect", mock_sc):
  1678. with self.assertRaises(VMwareConnectionError) as excinfo:
  1679. salt.utils.vmware._get_service_instance(
  1680. host="fake_host.fqdn",
  1681. username="fake_username",
  1682. password="fake_password",
  1683. protocol="fake_protocol",
  1684. port=1,
  1685. mechanism="sspi",
  1686. principal="fake_principal",
  1687. domain="fake_domain",
  1688. )
  1689. self.assertEqual(mock_sc.call_count, 1)
  1690. self.assertEqual("VimFault", excinfo.Exception.message)
  1691. @skipIf(not SSL_VALIDATION, "SSL validation is not enabled")
  1692. def test_second_attempt_unsuccsessful_connection_default_error(self):
  1693. with patch("ssl.SSLContext", MagicMock()), patch(ssl_context, MagicMock()):
  1694. exc = vim.fault.HostConnectFault()
  1695. exc.msg = "[SSL: CERTIFICATE_VERIFY_FAILED]"
  1696. exc2 = Exception("Exception")
  1697. mock_sc = MagicMock(side_effect=[exc, exc2])
  1698. with patch("salt.utils.vmware.SmartConnect", mock_sc):
  1699. with self.assertRaises(VMwareConnectionError) as excinfo:
  1700. salt.utils.vmware._get_service_instance(
  1701. host="fake_host.fqdn",
  1702. username="fake_username",
  1703. password="fake_password",
  1704. protocol="fake_protocol",
  1705. port=1,
  1706. mechanism="sspi",
  1707. principal="fake_principal",
  1708. domain="fake_domain",
  1709. )
  1710. self.assertEqual(mock_sc.call_count, 2)
  1711. self.assertIn(
  1712. "Could not connect to host 'fake_host.fqdn'",
  1713. excinfo.Exception.message,
  1714. )
  1715. @skipIf(not SSL_VALIDATION, "SSL validation is not enabled")
  1716. def test_second_attempt_unsuccsessful_connection_vim_fault(self):
  1717. with patch("ssl.SSLContext", MagicMock()), patch(ssl_context, MagicMock()):
  1718. exc = vim.fault.HostConnectFault()
  1719. exc.msg = "[SSL: CERTIFICATE_VERIFY_FAILED]"
  1720. exc2 = vim.fault.VimFault()
  1721. exc2.msg = "VimFault"
  1722. mock_sc = MagicMock(side_effect=[exc, exc2])
  1723. with patch("salt.utils.vmware.SmartConnect", mock_sc):
  1724. with self.assertRaises(VMwareConnectionError) as excinfo:
  1725. salt.utils.vmware._get_service_instance(
  1726. host="fake_host.fqdn",
  1727. username="fake_username",
  1728. password="fake_password",
  1729. protocol="fake_protocol",
  1730. port=1,
  1731. mechanism="sspi",
  1732. principal="fake_principal",
  1733. domain="fake_domain",
  1734. )
  1735. self.assertEqual(mock_sc.call_count, 2)
  1736. self.assertIn("VimFault", excinfo.Exception.message)
  1737. @skipIf(not SSL_VALIDATION, "SSL validation is not enabled")
  1738. def test_third_attempt_unsuccessful_connection_detault_error(self):
  1739. with patch("ssl.SSLContext", MagicMock()), patch(ssl_context, MagicMock()):
  1740. exc = vim.fault.HostConnectFault()
  1741. exc.msg = "[SSL: CERTIFICATE_VERIFY_FAILED]"
  1742. exc2 = Exception("certificate verify failed")
  1743. exc3 = Exception("Exception")
  1744. mock_sc = MagicMock(side_effect=[exc, exc2, exc3])
  1745. with patch("salt.utils.vmware.SmartConnect", mock_sc):
  1746. with self.assertRaises(VMwareConnectionError) as excinfo:
  1747. salt.utils.vmware._get_service_instance(
  1748. host="fake_host.fqdn",
  1749. username="fake_username",
  1750. password="fake_password",
  1751. protocol="fake_protocol",
  1752. port=1,
  1753. mechanism="sspi",
  1754. principal="fake_principal",
  1755. domain="fake_domain",
  1756. )
  1757. self.assertEqual(mock_sc.call_count, 3)
  1758. self.assertIn("Exception", excinfo.Exception.message)
  1759. @skipIf(not SSL_VALIDATION, "SSL validation is not enabled")
  1760. def test_third_attempt_unsuccessful_connection_vim_fault(self):
  1761. with patch("ssl.SSLContext", MagicMock()), patch(ssl_context, MagicMock()):
  1762. exc = vim.fault.HostConnectFault()
  1763. exc.msg = "[SSL: CERTIFICATE_VERIFY_FAILED]"
  1764. exc2 = Exception("certificate verify failed")
  1765. exc3 = vim.fault.VimFault()
  1766. exc3.msg = "VimFault"
  1767. mock_sc = MagicMock(side_effect=[exc, exc2, exc3])
  1768. with patch("salt.utils.vmware.SmartConnect", mock_sc):
  1769. with self.assertRaises(VMwareConnectionError) as excinfo:
  1770. salt.utils.vmware._get_service_instance(
  1771. host="fake_host.fqdn",
  1772. username="fake_username",
  1773. password="fake_password",
  1774. protocol="fake_protocol",
  1775. port=1,
  1776. mechanism="sspi",
  1777. principal="fake_principal",
  1778. domain="fake_domain",
  1779. )
  1780. self.assertEqual(mock_sc.call_count, 3)
  1781. self.assertIn("VimFault", excinfo.Exception.message)
  1782. @skipIf(not HAS_PYVMOMI, "The 'pyvmomi' library is missing")
  1783. class GetServiceInstanceTestCase(TestCase):
  1784. """
  1785. Tests for salt.utils.vmware.get_service_instance
  1786. """
  1787. def setUp(self):
  1788. patches = (
  1789. ("salt.utils.vmware.GetSi", MagicMock(return_value=None)),
  1790. (
  1791. "salt.utils.vmware._get_service_instance",
  1792. MagicMock(return_value=MagicMock()),
  1793. ),
  1794. )
  1795. for mod, mock in patches:
  1796. patcher = patch(mod, mock)
  1797. patcher.start()
  1798. self.addCleanup(patcher.stop)
  1799. def test_default_params(self):
  1800. mock_get_si = MagicMock()
  1801. with patch("salt.utils.vmware._get_service_instance", mock_get_si):
  1802. salt.utils.vmware.get_service_instance(host="fake_host")
  1803. mock_get_si.assert_called_once_with(
  1804. "fake_host", None, None, "https", 443, "userpass", None, None
  1805. )
  1806. def test_no_cached_service_instance_same_host_on_proxy(self):
  1807. with patch("salt.utils.platform.is_proxy", MagicMock(return_value=True)):
  1808. # Service instance is uncached when using class default mock objs
  1809. mock_get_si = MagicMock()
  1810. with patch("salt.utils.vmware._get_service_instance", mock_get_si):
  1811. salt.utils.vmware.get_service_instance(
  1812. host="fake_host",
  1813. username="fake_username",
  1814. password="fake_password",
  1815. protocol="fake_protocol",
  1816. port=1,
  1817. mechanism="fake_mechanism",
  1818. principal="fake_principal",
  1819. domain="fake_domain",
  1820. )
  1821. mock_get_si.assert_called_once_with(
  1822. "fake_host",
  1823. "fake_username",
  1824. "fake_password",
  1825. "fake_protocol",
  1826. 1,
  1827. "fake_mechanism",
  1828. "fake_principal",
  1829. "fake_domain",
  1830. )
  1831. def test_cached_service_instance_different_host(self):
  1832. mock_si = MagicMock()
  1833. mock_si_stub = MagicMock()
  1834. mock_disconnect = MagicMock()
  1835. mock_get_si = MagicMock(return_value=mock_si)
  1836. mock_getstub = MagicMock()
  1837. with patch("salt.utils.vmware.GetSi", mock_get_si):
  1838. with patch("salt.utils.vmware.GetStub", mock_getstub):
  1839. with patch("salt.utils.vmware.Disconnect", mock_disconnect):
  1840. salt.utils.vmware.get_service_instance(
  1841. host="fake_host",
  1842. username="fake_username",
  1843. password="fake_password",
  1844. protocol="fake_protocol",
  1845. port=1,
  1846. mechanism="fake_mechanism",
  1847. principal="fake_principal",
  1848. domain="fake_domain",
  1849. )
  1850. self.assertEqual(mock_get_si.call_count, 1)
  1851. self.assertEqual(mock_getstub.call_count, 1)
  1852. self.assertEqual(mock_disconnect.call_count, 1)
  1853. def test_uncached_service_instance(self):
  1854. # Service instance is uncached when using class default mock objs
  1855. mock_get_si = MagicMock()
  1856. with patch("salt.utils.vmware._get_service_instance", mock_get_si):
  1857. salt.utils.vmware.get_service_instance(
  1858. host="fake_host",
  1859. username="fake_username",
  1860. password="fake_password",
  1861. protocol="fake_protocol",
  1862. port=1,
  1863. mechanism="fake_mechanism",
  1864. principal="fake_principal",
  1865. domain="fake_domain",
  1866. )
  1867. mock_get_si.assert_called_once_with(
  1868. "fake_host",
  1869. "fake_username",
  1870. "fake_password",
  1871. "fake_protocol",
  1872. 1,
  1873. "fake_mechanism",
  1874. "fake_principal",
  1875. "fake_domain",
  1876. )
  1877. def test_unauthenticated_service_instance(self):
  1878. mock_si_current_time = MagicMock(side_effect=vim.fault.NotAuthenticated)
  1879. mock_si = MagicMock()
  1880. mock_get_si = MagicMock(return_value=mock_si)
  1881. mock_si.CurrentTime = mock_si_current_time
  1882. mock_disconnect = MagicMock()
  1883. with patch("salt.utils.vmware._get_service_instance", mock_get_si):
  1884. with patch("salt.utils.vmware.Disconnect", mock_disconnect):
  1885. salt.utils.vmware.get_service_instance(
  1886. host="fake_host",
  1887. username="fake_username",
  1888. password="fake_password",
  1889. protocol="fake_protocol",
  1890. port=1,
  1891. mechanism="fake_mechanism",
  1892. principal="fake_principal",
  1893. domain="fake_domain",
  1894. )
  1895. self.assertEqual(mock_si_current_time.call_count, 1)
  1896. self.assertEqual(mock_disconnect.call_count, 1)
  1897. self.assertEqual(mock_get_si.call_count, 2)
  1898. def test_current_time_raise_no_permission(self):
  1899. exc = vim.fault.NoPermission()
  1900. exc.privilegeId = "Fake privilege"
  1901. with patch(
  1902. "salt.utils.vmware._get_service_instance",
  1903. MagicMock(return_value=MagicMock(CurrentTime=MagicMock(side_effect=exc))),
  1904. ):
  1905. with self.assertRaises(VMwareApiError) as excinfo:
  1906. salt.utils.vmware.get_service_instance(
  1907. host="fake_host",
  1908. username="fake_username",
  1909. password="fake_password",
  1910. protocol="fake_protocol",
  1911. port=1,
  1912. mechanism="fake_mechanism",
  1913. principal="fake_principal",
  1914. domain="fake_domain",
  1915. )
  1916. self.assertEqual(
  1917. excinfo.exception.strerror,
  1918. "Not enough permissions. Required privilege: " "Fake privilege",
  1919. )
  1920. def test_current_time_raise_vim_fault(self):
  1921. exc = vim.fault.VimFault()
  1922. exc.msg = "VimFault msg"
  1923. with patch(
  1924. "salt.utils.vmware._get_service_instance",
  1925. MagicMock(return_value=MagicMock(CurrentTime=MagicMock(side_effect=exc))),
  1926. ):
  1927. with self.assertRaises(VMwareApiError) as excinfo:
  1928. salt.utils.vmware.get_service_instance(
  1929. host="fake_host",
  1930. username="fake_username",
  1931. password="fake_password",
  1932. protocol="fake_protocol",
  1933. port=1,
  1934. mechanism="fake_mechanism",
  1935. principal="fake_principal",
  1936. domain="fake_domain",
  1937. )
  1938. self.assertEqual(excinfo.exception.strerror, "VimFault msg")
  1939. def test_current_time_raise_runtime_fault(self):
  1940. exc = vmodl.RuntimeFault()
  1941. exc.msg = "RuntimeFault msg"
  1942. with patch(
  1943. "salt.utils.vmware._get_service_instance",
  1944. MagicMock(return_value=MagicMock(CurrentTime=MagicMock(side_effect=exc))),
  1945. ):
  1946. with self.assertRaises(VMwareRuntimeError) as excinfo:
  1947. salt.utils.vmware.get_service_instance(
  1948. host="fake_host",
  1949. username="fake_username",
  1950. password="fake_password",
  1951. protocol="fake_protocol",
  1952. port=1,
  1953. mechanism="fake_mechanism",
  1954. principal="fake_principal",
  1955. domain="fake_domain",
  1956. )
  1957. self.assertEqual(excinfo.exception.strerror, "RuntimeFault msg")
  1958. @skipIf(not HAS_PYVMOMI, "The 'pyvmomi' library is missing")
  1959. class DisconnectTestCase(TestCase):
  1960. """
  1961. Tests for salt.utils.vmware.disconnect
  1962. """
  1963. def setUp(self):
  1964. self.mock_si = MagicMock()
  1965. self.addCleanup(delattr, self, "mock_si")
  1966. def test_disconnect(self):
  1967. mock_disconnect = MagicMock()
  1968. with patch("salt.utils.vmware.Disconnect", mock_disconnect):
  1969. salt.utils.vmware.disconnect(service_instance=self.mock_si)
  1970. mock_disconnect.assert_called_once_with(self.mock_si)
  1971. def test_disconnect_raise_no_permission(self):
  1972. exc = vim.fault.NoPermission()
  1973. exc.privilegeId = "Fake privilege"
  1974. with patch("salt.utils.vmware.Disconnect", MagicMock(side_effect=exc)):
  1975. with self.assertRaises(VMwareApiError) as excinfo:
  1976. salt.utils.vmware.disconnect(service_instance=self.mock_si)
  1977. self.assertEqual(
  1978. excinfo.exception.strerror,
  1979. "Not enough permissions. Required privilege: " "Fake privilege",
  1980. )
  1981. def test_disconnect_raise_vim_fault(self):
  1982. exc = vim.fault.VimFault()
  1983. exc.msg = "VimFault msg"
  1984. with patch("salt.utils.vmware.Disconnect", MagicMock(side_effect=exc)):
  1985. with self.assertRaises(VMwareApiError) as excinfo:
  1986. salt.utils.vmware.disconnect(service_instance=self.mock_si)
  1987. self.assertEqual(excinfo.exception.strerror, "VimFault msg")
  1988. def test_disconnect_raise_runtime_fault(self):
  1989. exc = vmodl.RuntimeFault()
  1990. exc.msg = "RuntimeFault msg"
  1991. with patch("salt.utils.vmware.Disconnect", MagicMock(side_effect=exc)):
  1992. with self.assertRaises(VMwareRuntimeError) as excinfo:
  1993. salt.utils.vmware.disconnect(service_instance=self.mock_si)
  1994. self.assertEqual(excinfo.exception.strerror, "RuntimeFault msg")
  1995. @skipIf(not HAS_PYVMOMI, "The 'pyvmomi' library is missing")
  1996. class IsConnectionToAVCenterTestCase(TestCase):
  1997. """
  1998. Tests for salt.utils.vmware.is_connection_to_a_vcenter
  1999. """
  2000. def test_api_type_raise_no_permission(self):
  2001. exc = vim.fault.NoPermission()
  2002. exc.privilegeId = "Fake privilege"
  2003. mock_si = MagicMock()
  2004. type(mock_si.content.about).apiType = PropertyMock(side_effect=exc)
  2005. with self.assertRaises(VMwareApiError) as excinfo:
  2006. salt.utils.vmware.is_connection_to_a_vcenter(mock_si)
  2007. self.assertEqual(
  2008. excinfo.exception.strerror,
  2009. "Not enough permissions. Required privilege: " "Fake privilege",
  2010. )
  2011. def test_api_type_raise_vim_fault(self):
  2012. exc = vim.fault.VimFault()
  2013. exc.msg = "VimFault msg"
  2014. mock_si = MagicMock()
  2015. type(mock_si.content.about).apiType = PropertyMock(side_effect=exc)
  2016. with self.assertRaises(VMwareApiError) as excinfo:
  2017. salt.utils.vmware.is_connection_to_a_vcenter(mock_si)
  2018. self.assertEqual(excinfo.exception.strerror, "VimFault msg")
  2019. def test_api_type_raise_runtime_fault(self):
  2020. exc = vmodl.RuntimeFault()
  2021. exc.msg = "RuntimeFault msg"
  2022. mock_si = MagicMock()
  2023. type(mock_si.content.about).apiType = PropertyMock(side_effect=exc)
  2024. with self.assertRaises(VMwareRuntimeError) as excinfo:
  2025. salt.utils.vmware.is_connection_to_a_vcenter(mock_si)
  2026. self.assertEqual(excinfo.exception.strerror, "RuntimeFault msg")
  2027. def test_connected_to_a_vcenter(self):
  2028. mock_si = MagicMock()
  2029. mock_si.content.about.apiType = "VirtualCenter"
  2030. ret = salt.utils.vmware.is_connection_to_a_vcenter(mock_si)
  2031. self.assertTrue(ret)
  2032. def test_connected_to_a_host(self):
  2033. mock_si = MagicMock()
  2034. mock_si.content.about.apiType = "HostAgent"
  2035. ret = salt.utils.vmware.is_connection_to_a_vcenter(mock_si)
  2036. self.assertFalse(ret)
  2037. def test_connected_to_invalid_entity(self):
  2038. mock_si = MagicMock()
  2039. mock_si.content.about.apiType = "UnsupportedType"
  2040. with self.assertRaises(VMwareApiError) as excinfo:
  2041. salt.utils.vmware.is_connection_to_a_vcenter(mock_si)
  2042. self.assertIn(
  2043. "Unexpected api type 'UnsupportedType'", excinfo.exception.strerror
  2044. )
  2045. @skipIf(not HAS_PYVMOMI, "The 'pyvmomi' library is missing")
  2046. class GetNewServiceInstanceStub(TestCase, LoaderModuleMockMixin):
  2047. """
  2048. Tests for salt.utils.vmware.get_new_service_instance_stub
  2049. """
  2050. def setup_loader_modules(self):
  2051. return {
  2052. salt.utils.vmware: {
  2053. "__virtual__": MagicMock(return_value="vmware"),
  2054. "sys": MagicMock(),
  2055. "ssl": MagicMock(),
  2056. }
  2057. }
  2058. def setUp(self):
  2059. self.mock_stub = MagicMock(host="fake_host:1000", cookie='ignore"fake_cookie')
  2060. self.mock_si = MagicMock(_stub=self.mock_stub)
  2061. self.mock_ret = MagicMock()
  2062. self.mock_new_stub = MagicMock()
  2063. self.context_dict = {}
  2064. patches = (
  2065. (
  2066. "salt.utils.vmware.VmomiSupport.GetRequestContext",
  2067. MagicMock(return_value=self.context_dict),
  2068. ),
  2069. (
  2070. "salt.utils.vmware.SoapStubAdapter",
  2071. MagicMock(return_value=self.mock_new_stub),
  2072. ),
  2073. )
  2074. for mod, mock in patches:
  2075. patcher = patch(mod, mock)
  2076. patcher.start()
  2077. self.addCleanup(patcher.stop)
  2078. type(salt.utils.vmware.sys).version_info = PropertyMock(return_value=(2, 7, 9))
  2079. self.mock_context = MagicMock()
  2080. self.mock_create_default_context = MagicMock(return_value=self.mock_context)
  2081. salt.utils.vmware.ssl.create_default_context = self.mock_create_default_context
  2082. def tearDown(self):
  2083. for attr in (
  2084. "mock_stub",
  2085. "mock_si",
  2086. "mock_ret",
  2087. "mock_new_stub",
  2088. "context_dict",
  2089. "mock_context",
  2090. "mock_create_default_context",
  2091. ):
  2092. delattr(self, attr)
  2093. def test_ssl_default_context_loaded(self):
  2094. salt.utils.vmware.get_new_service_instance_stub(self.mock_si, "fake_path")
  2095. self.mock_create_default_context.assert_called_once_with()
  2096. self.assertFalse(self.mock_context.check_hostname)
  2097. self.assertEqual(self.mock_context.verify_mode, salt.utils.vmware.ssl.CERT_NONE)
  2098. def test_ssl_default_context_not_loaded(self):
  2099. type(salt.utils.vmware.sys).version_info = PropertyMock(return_value=(2, 7, 8))
  2100. salt.utils.vmware.get_new_service_instance_stub(self.mock_si, "fake_path")
  2101. self.assertEqual(self.mock_create_default_context.call_count, 0)
  2102. def test_session_cookie_in_context(self):
  2103. salt.utils.vmware.get_new_service_instance_stub(self.mock_si, "fake_path")
  2104. self.assertEqual(self.context_dict["vcSessionCookie"], "fake_cookie")
  2105. def test_get_new_stub(self):
  2106. mock_get_new_stub = MagicMock()
  2107. with patch("salt.utils.vmware.SoapStubAdapter", mock_get_new_stub):
  2108. salt.utils.vmware.get_new_service_instance_stub(
  2109. self.mock_si, "fake_path", "fake_ns", "fake_version"
  2110. )
  2111. mock_get_new_stub.assert_called_once_with(
  2112. host="fake_host",
  2113. ns="fake_ns",
  2114. path="fake_path",
  2115. version="fake_version",
  2116. poolSize=0,
  2117. sslContext=self.mock_context,
  2118. )
  2119. def test_get_new_stub_2_7_8_python(self):
  2120. type(salt.utils.vmware.sys).version_info = PropertyMock(return_value=(2, 7, 8))
  2121. mock_get_new_stub = MagicMock()
  2122. with patch("salt.utils.vmware.SoapStubAdapter", mock_get_new_stub):
  2123. salt.utils.vmware.get_new_service_instance_stub(
  2124. self.mock_si, "fake_path", "fake_ns", "fake_version"
  2125. )
  2126. mock_get_new_stub.assert_called_once_with(
  2127. host="fake_host",
  2128. ns="fake_ns",
  2129. path="fake_path",
  2130. version="fake_version",
  2131. poolSize=0,
  2132. sslContext=None,
  2133. )
  2134. def test_new_stub_returned(self):
  2135. ret = salt.utils.vmware.get_new_service_instance_stub(self.mock_si, "fake_path")
  2136. self.assertEqual(self.mock_new_stub.cookie, 'ignore"fake_cookie')
  2137. self.assertEqual(ret, self.mock_new_stub)
  2138. @skipIf(not HAS_PYVMOMI, "The 'pyvmomi' library is missing")
  2139. class GetServiceInstanceFromManagedObjectTestCase(TestCase):
  2140. """
  2141. Tests for salt.utils.vmware.get_managed_instance_from_managed_object
  2142. """
  2143. def setUp(self):
  2144. patches = (("salt.utils.vmware.vim.ServiceInstance", MagicMock()),)
  2145. for mod, mock in patches:
  2146. patcher = patch(mod, mock)
  2147. patcher.start()
  2148. self.addCleanup(patcher.stop)
  2149. self.mock_si = MagicMock()
  2150. self.mock_stub = PropertyMock()
  2151. self.mock_mo_ref = MagicMock(_stub=self.mock_stub)
  2152. for attr in ("mock_si", "mock_stub", "mock_mo_ref"):
  2153. self.addCleanup(delattr, self, attr)
  2154. def test_default_name_parameter(self):
  2155. mock_trace = MagicMock()
  2156. type(salt.utils.vmware.log).trace = mock_trace
  2157. salt.utils.vmware.get_service_instance_from_managed_object(self.mock_mo_ref)
  2158. mock_trace.assert_called_once_with(
  2159. "[%s] Retrieving service instance from managed object", "<unnamed>"
  2160. )
  2161. def test_name_parameter_passed_in(self):
  2162. mock_trace = MagicMock()
  2163. type(salt.utils.vmware.log).trace = mock_trace
  2164. salt.utils.vmware.get_service_instance_from_managed_object(
  2165. self.mock_mo_ref, "fake_mo_name"
  2166. )
  2167. mock_trace.assert_called_once_with(
  2168. "[%s] Retrieving service instance from managed object", "fake_mo_name"
  2169. )
  2170. def test_service_instance_instantiation(self):
  2171. mock_service_instance_ini = MagicMock()
  2172. with patch("salt.utils.vmware.vim.ServiceInstance", mock_service_instance_ini):
  2173. salt.utils.vmware.get_service_instance_from_managed_object(self.mock_mo_ref)
  2174. mock_service_instance_ini.assert_called_once_with("ServiceInstance")
  2175. def test_si_return_and_stub_assignment(self):
  2176. with patch(
  2177. "salt.utils.vmware.vim.ServiceInstance",
  2178. MagicMock(return_value=self.mock_si),
  2179. ):
  2180. ret = salt.utils.vmware.get_service_instance_from_managed_object(
  2181. self.mock_mo_ref
  2182. )
  2183. self.assertEqual(ret, self.mock_si)
  2184. self.assertEqual(ret._stub, self.mock_stub)
  2185. @skipIf(not HAS_PYVMOMI, "The 'pyvmomi' library is missing")
  2186. class GetDatacentersTestCase(TestCase):
  2187. """
  2188. Tests for salt.utils.vmware.get_datacenters
  2189. """
  2190. def setUp(self):
  2191. patches = (
  2192. (
  2193. "salt.utils.vmware.get_mors_with_properties",
  2194. MagicMock(return_value=[{"name": "fake_dc", "object": MagicMock()}]),
  2195. ),
  2196. )
  2197. for mod, mock in patches:
  2198. patcher = patch(mod, mock)
  2199. patcher.start()
  2200. self.addCleanup(patcher.stop)
  2201. self.mock_si = MagicMock()
  2202. self.mock_dc1 = MagicMock()
  2203. self.mock_dc2 = MagicMock()
  2204. self.mock_entries = [
  2205. {"name": "fake_dc1", "object": self.mock_dc1},
  2206. {"name": "fake_dc2", "object": self.mock_dc2},
  2207. ]
  2208. def test_get_mors_with_properties_call(self):
  2209. mock_get_mors_with_properties = MagicMock(
  2210. return_value=[{"name": "fake_dc", "object": MagicMock()}]
  2211. )
  2212. with patch(
  2213. "salt.utils.vmware.get_mors_with_properties", mock_get_mors_with_properties
  2214. ):
  2215. salt.utils.vmware.get_datacenters(
  2216. self.mock_si, datacenter_names=["fake_dc1"]
  2217. )
  2218. mock_get_mors_with_properties.assert_called_once_with(
  2219. self.mock_si, vim.Datacenter, property_list=["name"]
  2220. )
  2221. def test_get_mors_with_properties_returns_empty_array(self):
  2222. with patch(
  2223. "salt.utils.vmware.get_mors_with_properties", MagicMock(return_value=[])
  2224. ):
  2225. res = salt.utils.vmware.get_datacenters(
  2226. self.mock_si, datacenter_names=["fake_dc1"]
  2227. )
  2228. self.assertEqual(res, [])
  2229. def test_no_parameters(self):
  2230. with patch(
  2231. "salt.utils.vmware.get_mors_with_properties",
  2232. MagicMock(return_value=self.mock_entries),
  2233. ):
  2234. res = salt.utils.vmware.get_datacenters(self.mock_si)
  2235. self.assertEqual(res, [])
  2236. def test_datastore_not_found(self):
  2237. with patch(
  2238. "salt.utils.vmware.get_mors_with_properties",
  2239. MagicMock(return_value=self.mock_entries),
  2240. ):
  2241. res = salt.utils.vmware.get_datacenters(
  2242. self.mock_si, datacenter_names=["fake_dc"]
  2243. )
  2244. self.assertEqual(res, [])
  2245. def test_datastore_found(self):
  2246. with patch(
  2247. "salt.utils.vmware.get_mors_with_properties",
  2248. MagicMock(return_value=self.mock_entries),
  2249. ):
  2250. res = salt.utils.vmware.get_datacenters(
  2251. self.mock_si, datacenter_names=["fake_dc2"]
  2252. )
  2253. self.assertEqual(res, [self.mock_dc2])
  2254. def test_get_all_datastores(self):
  2255. with patch(
  2256. "salt.utils.vmware.get_mors_with_properties",
  2257. MagicMock(return_value=self.mock_entries),
  2258. ):
  2259. res = salt.utils.vmware.get_datacenters(
  2260. self.mock_si, get_all_datacenters=True
  2261. )
  2262. self.assertEqual(res, [self.mock_dc1, self.mock_dc2])
  2263. @skipIf(not HAS_PYVMOMI, "The 'pyvmomi' library is missing")
  2264. class GetDatacenterTestCase(TestCase):
  2265. """
  2266. Tests for salt.utils.vmware.get_datacenter
  2267. """
  2268. def setUp(self):
  2269. patches = (
  2270. (
  2271. "salt.utils.vmware.get_datacenters",
  2272. MagicMock(return_value=[MagicMock()]),
  2273. ),
  2274. )
  2275. for mod, mock in patches:
  2276. patcher = patch(mod, mock)
  2277. patcher.start()
  2278. self.addCleanup(patcher.stop)
  2279. self.mock_si = MagicMock()
  2280. self.mock_dc = MagicMock()
  2281. def test_get_datacenters_call(self):
  2282. mock_get_datacenters = MagicMock(return_value=[MagicMock()])
  2283. with patch("salt.utils.vmware.get_datacenters", mock_get_datacenters):
  2284. salt.utils.vmware.get_datacenter(self.mock_si, "fake_dc1")
  2285. mock_get_datacenters.assert_called_once_with(
  2286. self.mock_si, datacenter_names=["fake_dc1"]
  2287. )
  2288. def test_no_datacenters_returned(self):
  2289. with patch("salt.utils.vmware.get_datacenters", MagicMock(return_value=[])):
  2290. with self.assertRaises(VMwareObjectRetrievalError) as excinfo:
  2291. salt.utils.vmware.get_datacenter(self.mock_si, "fake_dc1")
  2292. self.assertEqual(
  2293. "Datacenter 'fake_dc1' was not found", excinfo.exception.strerror
  2294. )
  2295. def test_get_datacenter_return(self):
  2296. with patch(
  2297. "salt.utils.vmware.get_datacenters", MagicMock(return_value=[self.mock_dc])
  2298. ):
  2299. res = salt.utils.vmware.get_datacenter(self.mock_si, "fake_dc1")
  2300. self.assertEqual(res, self.mock_dc)
  2301. @skipIf(not HAS_PYVMOMI, "The 'pyvmomi' library is missing")
  2302. class CreateDatacenterTestCase(TestCase):
  2303. """
  2304. Tests for salt.utils.vmware.create_datacenter
  2305. """
  2306. def setUp(self):
  2307. patches = (("salt.utils.vmware.get_root_folder", MagicMock()),)
  2308. for mod, mock in patches:
  2309. patcher = patch(mod, mock)
  2310. patcher.start()
  2311. self.addCleanup(patcher.stop)
  2312. self.mock_si = MagicMock()
  2313. self.mock_dc = MagicMock()
  2314. self.mock_create_datacenter = MagicMock(return_value=self.mock_dc)
  2315. self.mock_root_folder = MagicMock(CreateDatacenter=self.mock_create_datacenter)
  2316. def test_get_root_folder(self):
  2317. mock_get_root_folder = MagicMock()
  2318. with patch("salt.utils.vmware.get_root_folder", mock_get_root_folder):
  2319. salt.utils.vmware.create_datacenter(self.mock_si, "fake_dc")
  2320. mock_get_root_folder.assert_called_once_with(self.mock_si)
  2321. def test_create_datacenter_call(self):
  2322. with patch(
  2323. "salt.utils.vmware.get_root_folder",
  2324. MagicMock(return_value=self.mock_root_folder),
  2325. ):
  2326. salt.utils.vmware.create_datacenter(self.mock_si, "fake_dc")
  2327. self.mock_create_datacenter.assert_called_once_with("fake_dc")
  2328. def test_create_datacenter_raise_no_permission(self):
  2329. exc = vim.fault.NoPermission()
  2330. exc.privilegeId = "Fake privilege"
  2331. self.mock_root_folder = MagicMock(CreateDatacenter=MagicMock(side_effect=exc))
  2332. with patch(
  2333. "salt.utils.vmware.get_root_folder",
  2334. MagicMock(return_value=self.mock_root_folder),
  2335. ):
  2336. with self.assertRaises(VMwareApiError) as excinfo:
  2337. salt.utils.vmware.create_datacenter(self.mock_si, "fake_dc")
  2338. self.assertEqual(
  2339. excinfo.exception.strerror,
  2340. "Not enough permissions. Required privilege: " "Fake privilege",
  2341. )
  2342. def test_create_datacenter_raise_vim_fault(self):
  2343. exc = vim.VimFault()
  2344. exc.msg = "VimFault msg"
  2345. self.mock_root_folder = MagicMock(CreateDatacenter=MagicMock(side_effect=exc))
  2346. with patch(
  2347. "salt.utils.vmware.get_root_folder",
  2348. MagicMock(return_value=self.mock_root_folder),
  2349. ):
  2350. with self.assertRaises(VMwareApiError) as excinfo:
  2351. salt.utils.vmware.create_datacenter(self.mock_si, "fake_dc")
  2352. self.assertEqual(excinfo.exception.strerror, "VimFault msg")
  2353. def test_create_datacenter_runtime_fault(self):
  2354. exc = vmodl.RuntimeFault()
  2355. exc.msg = "RuntimeFault msg"
  2356. self.mock_root_folder = MagicMock(CreateDatacenter=MagicMock(side_effect=exc))
  2357. with patch(
  2358. "salt.utils.vmware.get_root_folder",
  2359. MagicMock(return_value=self.mock_root_folder),
  2360. ):
  2361. with self.assertRaises(VMwareRuntimeError) as excinfo:
  2362. salt.utils.vmware.create_datacenter(self.mock_si, "fake_dc")
  2363. self.assertEqual(excinfo.exception.strerror, "RuntimeFault msg")
  2364. def test_datastore_successfully_created(self):
  2365. with patch(
  2366. "salt.utils.vmware.get_root_folder",
  2367. MagicMock(return_value=self.mock_root_folder),
  2368. ):
  2369. res = salt.utils.vmware.create_datacenter(self.mock_si, "fake_dc")
  2370. self.assertEqual(res, self.mock_dc)
  2371. class FakeTaskClass(object):
  2372. pass
  2373. @skipIf(not HAS_PYVMOMI, "The 'pyvmomi' library is missing")
  2374. class GetDvssTestCase(TestCase):
  2375. def setUp(self):
  2376. self.mock_si = MagicMock()
  2377. self.mock_dc_ref = MagicMock()
  2378. self.mock_traversal_spec = MagicMock()
  2379. self.mock_items = [
  2380. {"object": MagicMock(), "name": "fake_dvs1"},
  2381. {"object": MagicMock(), "name": "fake_dvs2"},
  2382. {"object": MagicMock(), "name": "fake_dvs3"},
  2383. ]
  2384. self.mock_get_mors = MagicMock(return_value=self.mock_items)
  2385. patches = (
  2386. ("salt.utils.vmware.get_managed_object_name", MagicMock()),
  2387. ("salt.utils.vmware.get_mors_with_properties", self.mock_get_mors),
  2388. (
  2389. "salt.utils.vmware.get_service_instance_from_managed_object",
  2390. MagicMock(return_value=self.mock_si),
  2391. ),
  2392. (
  2393. "salt.utils.vmware.vmodl.query.PropertyCollector.TraversalSpec",
  2394. MagicMock(return_value=self.mock_traversal_spec),
  2395. ),
  2396. )
  2397. for mod, mock in patches:
  2398. patcher = patch(mod, mock)
  2399. patcher.start()
  2400. self.addCleanup(patcher.stop)
  2401. def tearDown(self):
  2402. for attr in (
  2403. "mock_si",
  2404. "mock_dc_ref",
  2405. "mock_traversal_spec",
  2406. "mock_items",
  2407. "mock_get_mors",
  2408. ):
  2409. delattr(self, attr)
  2410. def test_get_managed_object_name_call(self):
  2411. mock_get_managed_object_name = MagicMock()
  2412. with patch(
  2413. "salt.utils.vmware.get_managed_object_name", mock_get_managed_object_name
  2414. ):
  2415. salt.utils.vmware.get_dvss(self.mock_dc_ref)
  2416. mock_get_managed_object_name.assert_called_once_with(self.mock_dc_ref)
  2417. def test_traversal_spec(self):
  2418. mock_traversal_spec = MagicMock(return_value="traversal_spec")
  2419. with patch(
  2420. "salt.utils.vmware.vmodl.query.PropertyCollector.TraversalSpec",
  2421. mock_traversal_spec,
  2422. ):
  2423. salt.utils.vmware.get_dvss(self.mock_dc_ref)
  2424. mock_traversal_spec.assert_has_calls(
  2425. [
  2426. call(path="childEntity", skip=False, type=vim.Folder),
  2427. call(
  2428. path="networkFolder",
  2429. skip=True,
  2430. type=vim.Datacenter,
  2431. selectSet=["traversal_spec"],
  2432. ),
  2433. ]
  2434. )
  2435. def test_get_mors_with_properties(self):
  2436. salt.utils.vmware.get_dvss(self.mock_dc_ref)
  2437. self.mock_get_mors.assert_called_once_with(
  2438. self.mock_si,
  2439. vim.DistributedVirtualSwitch,
  2440. container_ref=self.mock_dc_ref,
  2441. property_list=["name"],
  2442. traversal_spec=self.mock_traversal_spec,
  2443. )
  2444. def test_get_no_dvss(self):
  2445. ret = salt.utils.vmware.get_dvss(self.mock_dc_ref)
  2446. self.assertEqual(ret, [])
  2447. def test_get_all_dvss(self):
  2448. ret = salt.utils.vmware.get_dvss(self.mock_dc_ref, get_all_dvss=True)
  2449. self.assertEqual(ret, [i["object"] for i in self.mock_items])
  2450. def test_filtered_all_dvss(self):
  2451. ret = salt.utils.vmware.get_dvss(
  2452. self.mock_dc_ref, dvs_names=["fake_dvs1", "fake_dvs3", "no_dvs"]
  2453. )
  2454. self.assertEqual(
  2455. ret, [self.mock_items[0]["object"], self.mock_items[2]["object"]]
  2456. )
  2457. @skipIf(not HAS_PYVMOMI, "The 'pyvmomi' library is missing")
  2458. class GetNetworkFolderTestCase(TestCase):
  2459. def setUp(self):
  2460. self.mock_si = MagicMock()
  2461. self.mock_dc_ref = MagicMock()
  2462. self.mock_traversal_spec = MagicMock()
  2463. self.mock_entries = [{"object": MagicMock(), "name": "fake_netw_folder"}]
  2464. self.mock_get_mors = MagicMock(return_value=self.mock_entries)
  2465. patches = (
  2466. (
  2467. "salt.utils.vmware.get_managed_object_name",
  2468. MagicMock(return_value="fake_dc"),
  2469. ),
  2470. (
  2471. "salt.utils.vmware.get_service_instance_from_managed_object",
  2472. MagicMock(return_value=self.mock_si),
  2473. ),
  2474. (
  2475. "salt.utils.vmware.vmodl.query.PropertyCollector.TraversalSpec",
  2476. MagicMock(return_value=self.mock_traversal_spec),
  2477. ),
  2478. ("salt.utils.vmware.get_mors_with_properties", self.mock_get_mors),
  2479. )
  2480. for mod, mock in patches:
  2481. patcher = patch(mod, mock)
  2482. patcher.start()
  2483. self.addCleanup(patcher.stop)
  2484. def tearDown(self):
  2485. for attr in (
  2486. "mock_si",
  2487. "mock_dc_ref",
  2488. "mock_traversal_spec",
  2489. "mock_entries",
  2490. "mock_get_mors",
  2491. ):
  2492. delattr(self, attr)
  2493. def test_get_managed_object_name_call(self):
  2494. mock_get_managed_object_name = MagicMock()
  2495. with patch(
  2496. "salt.utils.vmware.get_managed_object_name", mock_get_managed_object_name
  2497. ):
  2498. salt.utils.vmware.get_network_folder(self.mock_dc_ref)
  2499. mock_get_managed_object_name.assert_called_once_with(self.mock_dc_ref)
  2500. def test_traversal_spec(self):
  2501. mock_traversal_spec = MagicMock(return_value="traversal_spec")
  2502. with patch(
  2503. "salt.utils.vmware.vmodl.query.PropertyCollector.TraversalSpec",
  2504. mock_traversal_spec,
  2505. ):
  2506. salt.utils.vmware.get_network_folder(self.mock_dc_ref)
  2507. mock_traversal_spec.assert_called_once_with(
  2508. path="networkFolder", skip=False, type=vim.Datacenter
  2509. )
  2510. def test_get_mors_with_properties(self):
  2511. salt.utils.vmware.get_network_folder(self.mock_dc_ref)
  2512. self.mock_get_mors.assert_called_once_with(
  2513. self.mock_si,
  2514. vim.Folder,
  2515. container_ref=self.mock_dc_ref,
  2516. property_list=["name"],
  2517. traversal_spec=self.mock_traversal_spec,
  2518. )
  2519. def test_get_no_network_folder(self):
  2520. with patch(
  2521. "salt.utils.vmware.get_mors_with_properties", MagicMock(return_value=[])
  2522. ):
  2523. with self.assertRaises(VMwareObjectRetrievalError) as excinfo:
  2524. salt.utils.vmware.get_network_folder(self.mock_dc_ref)
  2525. self.assertEqual(
  2526. excinfo.exception.strerror,
  2527. "Network folder in datacenter 'fake_dc' wasn't " "retrieved",
  2528. )
  2529. def test_get_network_folder(self):
  2530. ret = salt.utils.vmware.get_network_folder(self.mock_dc_ref)
  2531. self.assertEqual(ret, self.mock_entries[0]["object"])
  2532. @skipIf(not HAS_PYVMOMI, "The 'pyvmomi' library is missing")
  2533. class CreateDvsTestCase(TestCase):
  2534. def setUp(self):
  2535. self.mock_dc_ref = MagicMock()
  2536. self.mock_dvs_create_spec = MagicMock()
  2537. self.mock_task = MagicMock(spec=FakeTaskClass)
  2538. self.mock_netw_folder = MagicMock(
  2539. CreateDVS_Task=MagicMock(return_value=self.mock_task)
  2540. )
  2541. self.mock_wait_for_task = MagicMock()
  2542. patches = (
  2543. (
  2544. "salt.utils.vmware.get_managed_object_name",
  2545. MagicMock(return_value="fake_dc"),
  2546. ),
  2547. (
  2548. "salt.utils.vmware.get_network_folder",
  2549. MagicMock(return_value=self.mock_netw_folder),
  2550. ),
  2551. ("salt.utils.vmware.wait_for_task", self.mock_wait_for_task),
  2552. )
  2553. for mod, mock in patches:
  2554. patcher = patch(mod, mock)
  2555. patcher.start()
  2556. self.addCleanup(patcher.stop)
  2557. def tearDown(self):
  2558. for attr in (
  2559. "mock_dc_ref",
  2560. "mock_dvs_create_spec",
  2561. "mock_task",
  2562. "mock_netw_folder",
  2563. "mock_wait_for_task",
  2564. ):
  2565. delattr(self, attr)
  2566. def test_get_managed_object_name_call(self):
  2567. mock_get_managed_object_name = MagicMock()
  2568. with patch(
  2569. "salt.utils.vmware.get_managed_object_name", mock_get_managed_object_name
  2570. ):
  2571. salt.utils.vmware.create_dvs(self.mock_dc_ref, "fake_dvs")
  2572. mock_get_managed_object_name.assert_called_once_with(self.mock_dc_ref)
  2573. def test_no_dvs_create_spec(self):
  2574. mock_spec = MagicMock(configSpec=None)
  2575. mock_config_spec = MagicMock()
  2576. mock_dvs_create_spec = MagicMock(return_value=mock_spec)
  2577. mock_vmware_dvs_config_spec = MagicMock(return_value=mock_config_spec)
  2578. with patch("salt.utils.vmware.vim.DVSCreateSpec", mock_dvs_create_spec):
  2579. with patch(
  2580. "salt.utils.vmware.vim.VMwareDVSConfigSpec", mock_vmware_dvs_config_spec
  2581. ):
  2582. salt.utils.vmware.create_dvs(self.mock_dc_ref, "fake_dvs")
  2583. mock_dvs_create_spec.assert_called_once_with()
  2584. mock_vmware_dvs_config_spec.assert_called_once_with()
  2585. self.assertEqual(mock_spec.configSpec, mock_config_spec)
  2586. self.assertEqual(mock_config_spec.name, "fake_dvs")
  2587. self.mock_netw_folder.CreateDVS_Task.assert_called_once_with(mock_spec)
  2588. def test_get_network_folder(self):
  2589. mock_get_network_folder = MagicMock()
  2590. with patch("salt.utils.vmware.get_network_folder", mock_get_network_folder):
  2591. salt.utils.vmware.create_dvs(self.mock_dc_ref, "fake_dvs")
  2592. mock_get_network_folder.assert_called_once_with(self.mock_dc_ref)
  2593. def test_create_dvs_task_passed_in_spec(self):
  2594. salt.utils.vmware.create_dvs(
  2595. self.mock_dc_ref, "fake_dvs", dvs_create_spec=self.mock_dvs_create_spec
  2596. )
  2597. self.mock_netw_folder.CreateDVS_Task.assert_called_once_with(
  2598. self.mock_dvs_create_spec
  2599. )
  2600. def test_create_dvs_task_raises_no_permission(self):
  2601. exc = vim.fault.NoPermission()
  2602. exc.privilegeId = "Fake privilege"
  2603. self.mock_netw_folder.CreateDVS_Task = MagicMock(side_effect=exc)
  2604. with self.assertRaises(VMwareApiError) as excinfo:
  2605. salt.utils.vmware.create_dvs(
  2606. self.mock_dc_ref, "fake_dvs", dvs_create_spec=self.mock_dvs_create_spec
  2607. )
  2608. self.assertEqual(
  2609. excinfo.exception.strerror,
  2610. "Not enough permissions. Required privilege: " "Fake privilege",
  2611. )
  2612. def test_create_dvs_task_raises_vim_fault(self):
  2613. exc = vim.fault.VimFault()
  2614. exc.msg = "VimFault msg"
  2615. self.mock_netw_folder.CreateDVS_Task = MagicMock(side_effect=exc)
  2616. with self.assertRaises(VMwareApiError) as excinfo:
  2617. salt.utils.vmware.create_dvs(
  2618. self.mock_dc_ref, "fake_dvs", dvs_create_spec=self.mock_dvs_create_spec
  2619. )
  2620. self.assertEqual(excinfo.exception.strerror, "VimFault msg")
  2621. def test_create_dvs_task_raises_runtime_fault(self):
  2622. exc = vmodl.RuntimeFault()
  2623. exc.msg = "RuntimeFault msg"
  2624. self.mock_netw_folder.CreateDVS_Task = MagicMock(side_effect=exc)
  2625. with self.assertRaises(VMwareRuntimeError) as excinfo:
  2626. salt.utils.vmware.create_dvs(
  2627. self.mock_dc_ref, "fake_dvs", dvs_create_spec=self.mock_dvs_create_spec
  2628. )
  2629. self.assertEqual(excinfo.exception.strerror, "RuntimeFault msg")
  2630. def test_wait_for_tasks(self):
  2631. salt.utils.vmware.create_dvs(
  2632. self.mock_dc_ref, "fake_dvs", dvs_create_spec=self.mock_dvs_create_spec
  2633. )
  2634. self.mock_wait_for_task.assert_called_once_with(
  2635. self.mock_task,
  2636. "fake_dvs",
  2637. "<class '{}unit.utils.test_vmware.FakeTaskClass'>".format(
  2638. "tests." if RUNTIME_VARS.PYTEST_SESSION else ""
  2639. ),
  2640. )
  2641. @skipIf(not HAS_PYVMOMI, "The 'pyvmomi' library is missing")
  2642. class UpdateDvsTestCase(TestCase):
  2643. def setUp(self):
  2644. self.mock_task = MagicMock(spec=FakeTaskClass)
  2645. self.mock_dvs_ref = MagicMock(
  2646. ReconfigureDvs_Task=MagicMock(return_value=self.mock_task)
  2647. )
  2648. self.mock_dvs_spec = MagicMock()
  2649. self.mock_wait_for_task = MagicMock()
  2650. patches = (
  2651. (
  2652. "salt.utils.vmware.get_managed_object_name",
  2653. MagicMock(return_value="fake_dvs"),
  2654. ),
  2655. ("salt.utils.vmware.wait_for_task", self.mock_wait_for_task),
  2656. )
  2657. for mod, mock in patches:
  2658. patcher = patch(mod, mock)
  2659. patcher.start()
  2660. self.addCleanup(patcher.stop)
  2661. def tearDown(self):
  2662. for attr in (
  2663. "mock_dvs_ref",
  2664. "mock_task",
  2665. "mock_dvs_spec",
  2666. "mock_wait_for_task",
  2667. ):
  2668. delattr(self, attr)
  2669. def test_get_managed_object_name_call(self):
  2670. mock_get_managed_object_name = MagicMock()
  2671. with patch(
  2672. "salt.utils.vmware.get_managed_object_name", mock_get_managed_object_name
  2673. ):
  2674. salt.utils.vmware.update_dvs(self.mock_dvs_ref, self.mock_dvs_spec)
  2675. mock_get_managed_object_name.assert_called_once_with(self.mock_dvs_ref)
  2676. def test_reconfigure_dvs_task(self):
  2677. salt.utils.vmware.update_dvs(self.mock_dvs_ref, self.mock_dvs_spec)
  2678. self.mock_dvs_ref.ReconfigureDvs_Task.assert_called_once_with(
  2679. self.mock_dvs_spec
  2680. )
  2681. def test_reconfigure_dvs_task_raises_no_permission(self):
  2682. exc = vim.fault.NoPermission()
  2683. exc.privilegeId = "Fake privilege"
  2684. self.mock_dvs_ref.ReconfigureDvs_Task = MagicMock(side_effect=exc)
  2685. with self.assertRaises(VMwareApiError) as excinfo:
  2686. salt.utils.vmware.update_dvs(self.mock_dvs_ref, self.mock_dvs_spec)
  2687. self.assertEqual(
  2688. excinfo.exception.strerror,
  2689. "Not enough permissions. Required privilege: " "Fake privilege",
  2690. )
  2691. def test_reconfigure_dvs_task_raises_vim_fault(self):
  2692. exc = vim.fault.VimFault()
  2693. exc.msg = "VimFault msg"
  2694. self.mock_dvs_ref.ReconfigureDvs_Task = MagicMock(side_effect=exc)
  2695. with self.assertRaises(VMwareApiError) as excinfo:
  2696. salt.utils.vmware.update_dvs(self.mock_dvs_ref, self.mock_dvs_spec)
  2697. self.assertEqual(excinfo.exception.strerror, "VimFault msg")
  2698. def test_reconfigure_dvs_task_raises_runtime_fault(self):
  2699. exc = vmodl.RuntimeFault()
  2700. exc.msg = "RuntimeFault msg"
  2701. self.mock_dvs_ref.ReconfigureDvs_Task = MagicMock(side_effect=exc)
  2702. with self.assertRaises(VMwareRuntimeError) as excinfo:
  2703. salt.utils.vmware.update_dvs(self.mock_dvs_ref, self.mock_dvs_spec)
  2704. self.assertEqual(excinfo.exception.strerror, "RuntimeFault msg")
  2705. def test_wait_for_tasks(self):
  2706. salt.utils.vmware.update_dvs(self.mock_dvs_ref, self.mock_dvs_spec)
  2707. self.mock_wait_for_task.assert_called_once_with(
  2708. self.mock_task,
  2709. "fake_dvs",
  2710. "<class '{}unit.utils.test_vmware.FakeTaskClass'>".format(
  2711. "tests." if RUNTIME_VARS.PYTEST_SESSION else ""
  2712. ),
  2713. )
  2714. @skipIf(not HAS_PYVMOMI, "The 'pyvmomi' library is missing")
  2715. class SetDvsNetworkResourceManagementEnabledTestCase(TestCase):
  2716. def setUp(self):
  2717. self.mock_enabled = MagicMock()
  2718. self.mock_dvs_ref = MagicMock(EnableNetworkResourceManagement=MagicMock())
  2719. patches = (
  2720. (
  2721. "salt.utils.vmware.get_managed_object_name",
  2722. MagicMock(return_value="fake_dvs"),
  2723. ),
  2724. )
  2725. for mod, mock in patches:
  2726. patcher = patch(mod, mock)
  2727. patcher.start()
  2728. self.addCleanup(patcher.stop)
  2729. def tearDown(self):
  2730. for attr in ("mock_dvs_ref", "mock_enabled"):
  2731. delattr(self, attr)
  2732. def test_get_managed_object_name_call(self):
  2733. mock_get_managed_object_name = MagicMock()
  2734. with patch(
  2735. "salt.utils.vmware.get_managed_object_name", mock_get_managed_object_name
  2736. ):
  2737. salt.utils.vmware.set_dvs_network_resource_management_enabled(
  2738. self.mock_dvs_ref, self.mock_enabled
  2739. )
  2740. mock_get_managed_object_name.assert_called_once_with(self.mock_dvs_ref)
  2741. def test_enable_network_resource_management(self):
  2742. salt.utils.vmware.set_dvs_network_resource_management_enabled(
  2743. self.mock_dvs_ref, self.mock_enabled
  2744. )
  2745. self.mock_dvs_ref.EnableNetworkResourceManagement.assert_called_once_with(
  2746. enable=self.mock_enabled
  2747. )
  2748. def test_enable_network_resource_management_raises_no_permission(self):
  2749. exc = vim.fault.NoPermission()
  2750. exc.privilegeId = "Fake privilege"
  2751. self.mock_dvs_ref.EnableNetworkResourceManagement = MagicMock(side_effect=exc)
  2752. with self.assertRaises(VMwareApiError) as excinfo:
  2753. salt.utils.vmware.set_dvs_network_resource_management_enabled(
  2754. self.mock_dvs_ref, self.mock_enabled
  2755. )
  2756. self.assertEqual(
  2757. excinfo.exception.strerror,
  2758. "Not enough permissions. Required privilege: " "Fake privilege",
  2759. )
  2760. def test_enable_network_resource_management_raises_vim_fault(self):
  2761. exc = vim.fault.VimFault()
  2762. exc.msg = "VimFault msg"
  2763. self.mock_dvs_ref.EnableNetworkResourceManagement = MagicMock(side_effect=exc)
  2764. with self.assertRaises(VMwareApiError) as excinfo:
  2765. salt.utils.vmware.set_dvs_network_resource_management_enabled(
  2766. self.mock_dvs_ref, self.mock_enabled
  2767. )
  2768. def test_enable_network_resource_management_raises_runtime_fault(self):
  2769. exc = vmodl.RuntimeFault()
  2770. exc.msg = "RuntimeFault msg"
  2771. self.mock_dvs_ref.EnableNetworkResourceManagement = MagicMock(side_effect=exc)
  2772. with self.assertRaises(VMwareRuntimeError) as excinfo:
  2773. salt.utils.vmware.set_dvs_network_resource_management_enabled(
  2774. self.mock_dvs_ref, self.mock_enabled
  2775. )
  2776. self.assertEqual(excinfo.exception.strerror, "RuntimeFault msg")
  2777. @skipIf(not HAS_PYVMOMI, "The 'pyvmomi' library is missing")
  2778. class GetDvportgroupsTestCase(TestCase):
  2779. def setUp(self):
  2780. self.mock_si = MagicMock()
  2781. self.mock_dc_ref = MagicMock(spec=vim.Datacenter)
  2782. self.mock_dvs_ref = MagicMock(spec=vim.DistributedVirtualSwitch)
  2783. self.mock_traversal_spec = MagicMock()
  2784. self.mock_items = [
  2785. {"object": MagicMock(), "name": "fake_pg1"},
  2786. {"object": MagicMock(), "name": "fake_pg2"},
  2787. {"object": MagicMock(), "name": "fake_pg3"},
  2788. ]
  2789. self.mock_get_mors = MagicMock(return_value=self.mock_items)
  2790. patches = (
  2791. ("salt.utils.vmware.get_managed_object_name", MagicMock()),
  2792. ("salt.utils.vmware.get_mors_with_properties", self.mock_get_mors),
  2793. (
  2794. "salt.utils.vmware.get_service_instance_from_managed_object",
  2795. MagicMock(return_value=self.mock_si),
  2796. ),
  2797. (
  2798. "salt.utils.vmware.vmodl.query.PropertyCollector.TraversalSpec",
  2799. MagicMock(return_value=self.mock_traversal_spec),
  2800. ),
  2801. )
  2802. for mod, mock in patches:
  2803. patcher = patch(mod, mock)
  2804. patcher.start()
  2805. self.addCleanup(patcher.stop)
  2806. def tearDown(self):
  2807. for attr in (
  2808. "mock_si",
  2809. "mock_dc_ref",
  2810. "mock_dvs_ref",
  2811. "mock_traversal_spec",
  2812. "mock_items",
  2813. "mock_get_mors",
  2814. ):
  2815. delattr(self, attr)
  2816. def test_unsupported_parrent(self):
  2817. with self.assertRaises(ArgumentValueError) as excinfo:
  2818. salt.utils.vmware.get_dvportgroups(MagicMock())
  2819. self.assertEqual(
  2820. excinfo.exception.strerror,
  2821. "Parent has to be either a datacenter, or a " "distributed virtual switch",
  2822. )
  2823. def test_get_managed_object_name_call(self):
  2824. mock_get_managed_object_name = MagicMock()
  2825. with patch(
  2826. "salt.utils.vmware.get_managed_object_name", mock_get_managed_object_name
  2827. ):
  2828. salt.utils.vmware.get_dvportgroups(self.mock_dc_ref)
  2829. mock_get_managed_object_name.assert_called_once_with(self.mock_dc_ref)
  2830. def test_traversal_spec_datacenter_parent(self):
  2831. mock_traversal_spec = MagicMock(return_value="traversal_spec")
  2832. with patch(
  2833. "salt.utils.vmware.vmodl.query.PropertyCollector.TraversalSpec",
  2834. mock_traversal_spec,
  2835. ):
  2836. salt.utils.vmware.get_dvportgroups(self.mock_dc_ref)
  2837. mock_traversal_spec.assert_has_calls(
  2838. [
  2839. call(path="childEntity", skip=False, type=vim.Folder),
  2840. call(
  2841. path="networkFolder",
  2842. skip=True,
  2843. type=vim.Datacenter,
  2844. selectSet=["traversal_spec"],
  2845. ),
  2846. ]
  2847. )
  2848. def test_traversal_spec_dvs_parent(self):
  2849. mock_traversal_spec = MagicMock(return_value="traversal_spec")
  2850. with patch(
  2851. "salt.utils.vmware.vmodl.query.PropertyCollector.TraversalSpec",
  2852. mock_traversal_spec,
  2853. ):
  2854. salt.utils.vmware.get_dvportgroups(self.mock_dvs_ref)
  2855. mock_traversal_spec.assert_called_once_with(
  2856. path="portgroup", skip=False, type=vim.DistributedVirtualSwitch
  2857. )
  2858. def test_get_mors_with_properties(self):
  2859. salt.utils.vmware.get_dvportgroups(self.mock_dvs_ref)
  2860. self.mock_get_mors.assert_called_once_with(
  2861. self.mock_si,
  2862. vim.DistributedVirtualPortgroup,
  2863. container_ref=self.mock_dvs_ref,
  2864. property_list=["name"],
  2865. traversal_spec=self.mock_traversal_spec,
  2866. )
  2867. def test_get_no_pgs(self):
  2868. ret = salt.utils.vmware.get_dvportgroups(self.mock_dvs_ref)
  2869. self.assertEqual(ret, [])
  2870. def test_get_all_pgs(self):
  2871. ret = salt.utils.vmware.get_dvportgroups(
  2872. self.mock_dvs_ref, get_all_portgroups=True
  2873. )
  2874. self.assertEqual(ret, [i["object"] for i in self.mock_items])
  2875. def test_filtered_pgs(self):
  2876. ret = salt.utils.vmware.get_dvss(
  2877. self.mock_dc_ref, dvs_names=["fake_pg1", "fake_pg3", "no_pg"]
  2878. )
  2879. self.assertEqual(
  2880. ret, [self.mock_items[0]["object"], self.mock_items[2]["object"]]
  2881. )
  2882. @skipIf(not HAS_PYVMOMI, "The 'pyvmomi' library is missing")
  2883. class GetUplinkDvportgroupTestCase(TestCase):
  2884. def setUp(self):
  2885. self.mock_si = MagicMock()
  2886. self.mock_dvs_ref = MagicMock(spec=vim.DistributedVirtualSwitch)
  2887. self.mock_traversal_spec = MagicMock()
  2888. self.mock_items = [
  2889. {"object": MagicMock(), "tag": [MagicMock(key="fake_tag")]},
  2890. {"object": MagicMock(), "tag": [MagicMock(key="SYSTEM/DVS.UPLINKPG")]},
  2891. ]
  2892. self.mock_get_mors = MagicMock(return_value=self.mock_items)
  2893. patches = (
  2894. (
  2895. "salt.utils.vmware.get_managed_object_name",
  2896. MagicMock(return_value="fake_dvs"),
  2897. ),
  2898. ("salt.utils.vmware.get_mors_with_properties", self.mock_get_mors),
  2899. (
  2900. "salt.utils.vmware.get_service_instance_from_managed_object",
  2901. MagicMock(return_value=self.mock_si),
  2902. ),
  2903. (
  2904. "salt.utils.vmware.vmodl.query.PropertyCollector.TraversalSpec",
  2905. MagicMock(return_value=self.mock_traversal_spec),
  2906. ),
  2907. )
  2908. for mod, mock in patches:
  2909. patcher = patch(mod, mock)
  2910. patcher.start()
  2911. self.addCleanup(patcher.stop)
  2912. def tearDown(self):
  2913. for attr in (
  2914. "mock_si",
  2915. "mock_dvs_ref",
  2916. "mock_traversal_spec",
  2917. "mock_items",
  2918. "mock_get_mors",
  2919. ):
  2920. delattr(self, attr)
  2921. def test_get_managed_object_name_call(self):
  2922. mock_get_managed_object_name = MagicMock()
  2923. with patch(
  2924. "salt.utils.vmware.get_managed_object_name", mock_get_managed_object_name
  2925. ):
  2926. salt.utils.vmware.get_uplink_dvportgroup(self.mock_dvs_ref)
  2927. mock_get_managed_object_name.assert_called_once_with(self.mock_dvs_ref)
  2928. def test_traversal_spec(self):
  2929. mock_traversal_spec = MagicMock(return_value="traversal_spec")
  2930. with patch(
  2931. "salt.utils.vmware.vmodl.query.PropertyCollector.TraversalSpec",
  2932. mock_traversal_spec,
  2933. ):
  2934. salt.utils.vmware.get_uplink_dvportgroup(self.mock_dvs_ref)
  2935. mock_traversal_spec.assert_called_once_with(
  2936. path="portgroup", skip=False, type=vim.DistributedVirtualSwitch
  2937. )
  2938. def test_get_mors_with_properties(self):
  2939. salt.utils.vmware.get_uplink_dvportgroup(self.mock_dvs_ref)
  2940. self.mock_get_mors.assert_called_once_with(
  2941. self.mock_si,
  2942. vim.DistributedVirtualPortgroup,
  2943. container_ref=self.mock_dvs_ref,
  2944. property_list=["tag"],
  2945. traversal_spec=self.mock_traversal_spec,
  2946. )
  2947. def test_get_no_uplink_pg(self):
  2948. with patch(
  2949. "salt.utils.vmware.get_mors_with_properties", MagicMock(return_value=[])
  2950. ):
  2951. with self.assertRaises(VMwareObjectRetrievalError) as excinfo:
  2952. salt.utils.vmware.get_uplink_dvportgroup(self.mock_dvs_ref)
  2953. self.assertEqual(
  2954. excinfo.exception.strerror,
  2955. "Uplink portgroup of DVS 'fake_dvs' wasn't found",
  2956. )
  2957. def test_get_uplink_pg(self):
  2958. ret = salt.utils.vmware.get_uplink_dvportgroup(self.mock_dvs_ref)
  2959. self.assertEqual(ret, self.mock_items[1]["object"])
  2960. @skipIf(not HAS_PYVMOMI, "The 'pyvmomi' library is missing")
  2961. class CreateDvportgroupTestCase(TestCase):
  2962. def setUp(self):
  2963. self.mock_pg_spec = MagicMock()
  2964. self.mock_task = MagicMock(spec=FakeTaskClass)
  2965. self.mock_dvs_ref = MagicMock(
  2966. CreateDVPortgroup_Task=MagicMock(return_value=self.mock_task)
  2967. )
  2968. self.mock_wait_for_task = MagicMock()
  2969. patches = (
  2970. (
  2971. "salt.utils.vmware.get_managed_object_name",
  2972. MagicMock(return_value="fake_dvs"),
  2973. ),
  2974. ("salt.utils.vmware.wait_for_task", self.mock_wait_for_task),
  2975. )
  2976. for mod, mock in patches:
  2977. patcher = patch(mod, mock)
  2978. patcher.start()
  2979. self.addCleanup(patcher.stop)
  2980. def tearDown(self):
  2981. for attr in ("mock_pg_spec", "mock_dvs_ref", "mock_task", "mock_wait_for_task"):
  2982. delattr(self, attr)
  2983. def test_get_managed_object_name_call(self):
  2984. mock_get_managed_object_name = MagicMock()
  2985. with patch(
  2986. "salt.utils.vmware.get_managed_object_name", mock_get_managed_object_name
  2987. ):
  2988. salt.utils.vmware.create_dvportgroup(self.mock_dvs_ref, self.mock_pg_spec)
  2989. mock_get_managed_object_name.assert_called_once_with(self.mock_dvs_ref)
  2990. def test_create_dvporgroup_task(self):
  2991. salt.utils.vmware.create_dvportgroup(self.mock_dvs_ref, self.mock_pg_spec)
  2992. self.mock_dvs_ref.CreateDVPortgroup_Task.assert_called_once_with(
  2993. self.mock_pg_spec
  2994. )
  2995. def test_create_dvporgroup_task_raises_no_permission(self):
  2996. exc = vim.fault.NoPermission()
  2997. exc.privilegeId = "Fake privilege"
  2998. self.mock_dvs_ref.CreateDVPortgroup_Task = MagicMock(side_effect=exc)
  2999. with self.assertRaises(VMwareApiError) as excinfo:
  3000. salt.utils.vmware.create_dvportgroup(self.mock_dvs_ref, self.mock_pg_spec)
  3001. self.assertEqual(
  3002. excinfo.exception.strerror,
  3003. "Not enough permissions. Required privilege: " "Fake privilege",
  3004. )
  3005. def test_create_dvporgroup_task_raises_vim_fault(self):
  3006. exc = vim.fault.VimFault()
  3007. exc.msg = "VimFault msg"
  3008. self.mock_dvs_ref.CreateDVPortgroup_Task = MagicMock(side_effect=exc)
  3009. with self.assertRaises(VMwareApiError) as excinfo:
  3010. salt.utils.vmware.create_dvportgroup(self.mock_dvs_ref, self.mock_pg_spec)
  3011. self.assertEqual(excinfo.exception.strerror, "VimFault msg")
  3012. def test_create_dvporgroup_task_raises_runtime_fault(self):
  3013. exc = vmodl.RuntimeFault()
  3014. exc.msg = "RuntimeFault msg"
  3015. self.mock_dvs_ref.CreateDVPortgroup_Task = MagicMock(side_effect=exc)
  3016. with self.assertRaises(VMwareRuntimeError) as excinfo:
  3017. salt.utils.vmware.create_dvportgroup(self.mock_dvs_ref, self.mock_pg_spec)
  3018. self.assertEqual(excinfo.exception.strerror, "RuntimeFault msg")
  3019. def test_wait_for_tasks(self):
  3020. salt.utils.vmware.create_dvportgroup(self.mock_dvs_ref, self.mock_pg_spec)
  3021. self.mock_wait_for_task.assert_called_once_with(
  3022. self.mock_task,
  3023. "fake_dvs",
  3024. "<class '{}unit.utils.test_vmware.FakeTaskClass'>".format(
  3025. "tests." if RUNTIME_VARS.PYTEST_SESSION else ""
  3026. ),
  3027. )
  3028. @skipIf(not HAS_PYVMOMI, "The 'pyvmomi' library is missing")
  3029. class UpdateDvportgroupTestCase(TestCase):
  3030. def setUp(self):
  3031. self.mock_pg_spec = MagicMock()
  3032. self.mock_task = MagicMock(spec=FakeTaskClass)
  3033. self.mock_pg_ref = MagicMock(
  3034. ReconfigureDVPortgroup_Task=MagicMock(return_value=self.mock_task)
  3035. )
  3036. self.mock_wait_for_task = MagicMock()
  3037. patches = (
  3038. (
  3039. "salt.utils.vmware.get_managed_object_name",
  3040. MagicMock(return_value="fake_pg"),
  3041. ),
  3042. ("salt.utils.vmware.wait_for_task", self.mock_wait_for_task),
  3043. )
  3044. for mod, mock in patches:
  3045. patcher = patch(mod, mock)
  3046. patcher.start()
  3047. self.addCleanup(patcher.stop)
  3048. def tearDown(self):
  3049. for attr in ("mock_pg_spec", "mock_pg_ref", "mock_task", "mock_wait_for_task"):
  3050. delattr(self, attr)
  3051. def test_get_managed_object_name_call(self):
  3052. mock_get_managed_object_name = MagicMock()
  3053. with patch(
  3054. "salt.utils.vmware.get_managed_object_name", mock_get_managed_object_name
  3055. ):
  3056. salt.utils.vmware.update_dvportgroup(self.mock_pg_ref, self.mock_pg_spec)
  3057. mock_get_managed_object_name.assert_called_once_with(self.mock_pg_ref)
  3058. def test_reconfigure_dvporgroup_task(self):
  3059. salt.utils.vmware.update_dvportgroup(self.mock_pg_ref, self.mock_pg_spec)
  3060. self.mock_pg_ref.ReconfigureDVPortgroup_Task.assert_called_once_with(
  3061. self.mock_pg_spec
  3062. )
  3063. def test_reconfigure_dvporgroup_task_raises_no_permission(self):
  3064. exc = vim.fault.NoPermission()
  3065. exc.privilegeId = "Fake privilege"
  3066. self.mock_pg_ref.ReconfigureDVPortgroup_Task = MagicMock(side_effect=exc)
  3067. with self.assertRaises(VMwareApiError) as excinfo:
  3068. salt.utils.vmware.update_dvportgroup(self.mock_pg_ref, self.mock_pg_spec)
  3069. self.assertEqual(
  3070. excinfo.exception.strerror,
  3071. "Not enough permissions. Required privilege: " "Fake privilege",
  3072. )
  3073. def test_reconfigure_dvporgroup_task_raises_vim_fault(self):
  3074. exc = vim.fault.VimFault()
  3075. exc.msg = "VimFault msg"
  3076. self.mock_pg_ref.ReconfigureDVPortgroup_Task = MagicMock(side_effect=exc)
  3077. with self.assertRaises(VMwareApiError) as excinfo:
  3078. salt.utils.vmware.update_dvportgroup(self.mock_pg_ref, self.mock_pg_spec)
  3079. self.assertEqual(excinfo.exception.strerror, "VimFault msg")
  3080. def test_reconfigure_dvporgroup_task_raises_runtime_fault(self):
  3081. exc = vmodl.RuntimeFault()
  3082. exc.msg = "RuntimeFault msg"
  3083. self.mock_pg_ref.ReconfigureDVPortgroup_Task = MagicMock(side_effect=exc)
  3084. with self.assertRaises(VMwareRuntimeError) as excinfo:
  3085. salt.utils.vmware.update_dvportgroup(self.mock_pg_ref, self.mock_pg_spec)
  3086. self.assertEqual(excinfo.exception.strerror, "RuntimeFault msg")
  3087. def test_wait_for_tasks(self):
  3088. salt.utils.vmware.update_dvportgroup(self.mock_pg_ref, self.mock_pg_spec)
  3089. self.mock_wait_for_task.assert_called_once_with(
  3090. self.mock_task,
  3091. "fake_pg",
  3092. "<class '{}unit.utils.test_vmware.FakeTaskClass'>".format(
  3093. "tests." if RUNTIME_VARS.PYTEST_SESSION else ""
  3094. ),
  3095. )
  3096. @skipIf(not HAS_PYVMOMI, "The 'pyvmomi' library is missing")
  3097. class RemoveDvportgroupTestCase(TestCase):
  3098. def setUp(self):
  3099. self.mock_task = MagicMock(spec=FakeTaskClass)
  3100. self.mock_pg_ref = MagicMock(
  3101. Destroy_Task=MagicMock(return_value=self.mock_task)
  3102. )
  3103. self.mock_wait_for_task = MagicMock()
  3104. patches = (
  3105. (
  3106. "salt.utils.vmware.get_managed_object_name",
  3107. MagicMock(return_value="fake_pg"),
  3108. ),
  3109. ("salt.utils.vmware.wait_for_task", self.mock_wait_for_task),
  3110. )
  3111. for mod, mock in patches:
  3112. patcher = patch(mod, mock)
  3113. patcher.start()
  3114. self.addCleanup(patcher.stop)
  3115. def tearDown(self):
  3116. for attr in ("mock_pg_ref", "mock_task", "mock_wait_for_task"):
  3117. delattr(self, attr)
  3118. def test_get_managed_object_name_call(self):
  3119. mock_get_managed_object_name = MagicMock()
  3120. with patch(
  3121. "salt.utils.vmware.get_managed_object_name", mock_get_managed_object_name
  3122. ):
  3123. salt.utils.vmware.remove_dvportgroup(self.mock_pg_ref)
  3124. mock_get_managed_object_name.assert_called_once_with(self.mock_pg_ref)
  3125. def test_destroy_task(self):
  3126. salt.utils.vmware.remove_dvportgroup(self.mock_pg_ref)
  3127. self.mock_pg_ref.Destroy_Task.assert_called_once_with()
  3128. def test_destroy_task_raises_no_permission(self):
  3129. exc = vim.fault.NoPermission()
  3130. exc.privilegeId = "Fake privilege"
  3131. self.mock_pg_ref.Destroy_Task = MagicMock(side_effect=exc)
  3132. with self.assertRaises(VMwareApiError) as excinfo:
  3133. salt.utils.vmware.remove_dvportgroup(self.mock_pg_ref)
  3134. self.assertEqual(
  3135. excinfo.exception.strerror,
  3136. "Not enough permissions. Required privilege: " "Fake privilege",
  3137. )
  3138. def test_destroy_treconfigure_dvporgroup_task_raises_vim_fault(self):
  3139. exc = vim.fault.VimFault()
  3140. exc.msg = "VimFault msg"
  3141. self.mock_pg_ref.Destroy_Task = MagicMock(side_effect=exc)
  3142. with self.assertRaises(VMwareApiError) as excinfo:
  3143. salt.utils.vmware.remove_dvportgroup(self.mock_pg_ref)
  3144. self.assertEqual(excinfo.exception.strerror, "VimFault msg")
  3145. def test_destroy_treconfigure_dvporgroup_task_raises_runtime_fault(self):
  3146. exc = vmodl.RuntimeFault()
  3147. exc.msg = "RuntimeFault msg"
  3148. self.mock_pg_ref.Destroy_Task = MagicMock(side_effect=exc)
  3149. with self.assertRaises(VMwareRuntimeError) as excinfo:
  3150. salt.utils.vmware.remove_dvportgroup(self.mock_pg_ref)
  3151. self.assertEqual(excinfo.exception.strerror, "RuntimeFault msg")
  3152. def test_wait_for_tasks(self):
  3153. salt.utils.vmware.remove_dvportgroup(self.mock_pg_ref)
  3154. self.mock_wait_for_task.assert_called_once_with(
  3155. self.mock_task,
  3156. "fake_pg",
  3157. "<class '{}unit.utils.test_vmware.FakeTaskClass'>".format(
  3158. "tests." if RUNTIME_VARS.PYTEST_SESSION else ""
  3159. ),
  3160. )
  3161. @skipIf(not HAS_PYVMOMI, "The 'pyvmomi' library is missing")
  3162. class GetHostsTestCase(TestCase):
  3163. """
  3164. Tests for salt.utils.vmware.get_hosts
  3165. """
  3166. def setUp(self):
  3167. patches = (
  3168. ("salt.utils.vmware.get_mors_with_properties", MagicMock(return_value=[])),
  3169. ("salt.utils.vmware.get_datacenter", MagicMock(return_value=None)),
  3170. ("salt.utils.vmware.get_cluster", MagicMock(return_value=None)),
  3171. )
  3172. for mod, mock in patches:
  3173. patcher = patch(mod, mock)
  3174. patcher.start()
  3175. self.addCleanup(patcher.stop)
  3176. self.mock_root_folder = MagicMock()
  3177. self.mock_si = MagicMock()
  3178. self.mock_host1, self.mock_host2, self.mock_host3 = (
  3179. MagicMock(),
  3180. MagicMock(),
  3181. MagicMock(),
  3182. )
  3183. self.mock_prop_host1 = {"name": "fake_hostname1", "object": self.mock_host1}
  3184. self.mock_prop_host2 = {"name": "fake_hostname2", "object": self.mock_host2}
  3185. self.mock_prop_host3 = {"name": "fake_hostname3", "object": self.mock_host3}
  3186. self.mock_prop_hosts = [
  3187. self.mock_prop_host1,
  3188. self.mock_prop_host2,
  3189. self.mock_prop_host3,
  3190. ]
  3191. def test_cluster_no_datacenter(self):
  3192. with self.assertRaises(ArgumentValueError) as excinfo:
  3193. salt.utils.vmware.get_hosts(self.mock_si, cluster_name="fake_cluster")
  3194. self.assertEqual(
  3195. excinfo.exception.strerror,
  3196. "Must specify the datacenter when specifying the " "cluster",
  3197. )
  3198. def test_get_si_no_datacenter_no_cluster(self):
  3199. mock_get_mors = MagicMock()
  3200. mock_get_root_folder = MagicMock(return_value=self.mock_root_folder)
  3201. with patch("salt.utils.vmware.get_root_folder", mock_get_root_folder):
  3202. with patch("salt.utils.vmware.get_mors_with_properties", mock_get_mors):
  3203. salt.utils.vmware.get_hosts(self.mock_si)
  3204. mock_get_root_folder.assert_called_once_with(self.mock_si)
  3205. mock_get_mors.assert_called_once_with(
  3206. self.mock_si,
  3207. vim.HostSystem,
  3208. container_ref=self.mock_root_folder,
  3209. property_list=["name"],
  3210. )
  3211. def test_get_si_datacenter_name_no_cluster_name(self):
  3212. mock_dc = MagicMock()
  3213. mock_get_dc = MagicMock(return_value=mock_dc)
  3214. mock_get_mors = MagicMock()
  3215. with patch("salt.utils.vmware.get_datacenter", mock_get_dc):
  3216. with patch("salt.utils.vmware.get_mors_with_properties", mock_get_mors):
  3217. salt.utils.vmware.get_hosts(
  3218. self.mock_si, datacenter_name="fake_datacenter"
  3219. )
  3220. mock_get_dc.assert_called_once_with(self.mock_si, "fake_datacenter")
  3221. mock_get_mors.assert_called_once_with(
  3222. self.mock_si, vim.HostSystem, container_ref=mock_dc, property_list=["name"]
  3223. )
  3224. def test_get_si_datacenter_name_and_cluster_name(self):
  3225. mock_dc = MagicMock()
  3226. mock_get_dc = MagicMock(return_value=mock_dc)
  3227. mock_get_cl = MagicMock()
  3228. mock_get_mors = MagicMock()
  3229. with patch("salt.utils.vmware.get_datacenter", mock_get_dc):
  3230. with patch("salt.utils.vmware.get_cluster", mock_get_cl):
  3231. with patch("salt.utils.vmware.get_mors_with_properties", mock_get_mors):
  3232. salt.utils.vmware.get_hosts(
  3233. self.mock_si,
  3234. datacenter_name="fake_datacenter",
  3235. cluster_name="fake_cluster",
  3236. )
  3237. mock_get_dc.assert_called_once_with(self.mock_si, "fake_datacenter")
  3238. mock_get_mors.assert_called_once_with(
  3239. self.mock_si,
  3240. vim.HostSystem,
  3241. container_ref=mock_dc,
  3242. property_list=["name", "parent"],
  3243. )
  3244. def test_host_get_all_hosts(self):
  3245. with patch(
  3246. "salt.utils.vmware.get_root_folder",
  3247. MagicMock(return_value=self.mock_root_folder),
  3248. ):
  3249. with patch(
  3250. "salt.utils.vmware.get_mors_with_properties",
  3251. MagicMock(return_value=self.mock_prop_hosts),
  3252. ):
  3253. res = salt.utils.vmware.get_hosts(self.mock_si, get_all_hosts=True)
  3254. self.assertEqual(res, [self.mock_host1, self.mock_host2, self.mock_host3])
  3255. def test_filter_hostname(self):
  3256. with patch(
  3257. "salt.utils.vmware.get_mors_with_properties",
  3258. MagicMock(return_value=self.mock_prop_hosts),
  3259. ):
  3260. res = salt.utils.vmware.get_hosts(
  3261. self.mock_si, host_names=["fake_hostname1", "fake_hostname2"]
  3262. )
  3263. self.assertEqual(res, [self.mock_host1, self.mock_host2])
  3264. def test_get_all_host_flag_not_set_and_no_host_names(self):
  3265. with patch(
  3266. "salt.utils.vmware.get_mors_with_properties",
  3267. MagicMock(return_value=self.mock_prop_hosts),
  3268. ):
  3269. res = salt.utils.vmware.get_hosts(self.mock_si)
  3270. self.assertEqual(res, [])
  3271. def test_filter_cluster(self):
  3272. self.mock_prop_host1["parent"] = vim.ClusterComputeResource("cluster")
  3273. self.mock_prop_host2["parent"] = vim.ClusterComputeResource("cluster")
  3274. self.mock_prop_host3["parent"] = vim.Datacenter("dc")
  3275. mock_get_cl_name = MagicMock(
  3276. side_effect=["fake_bad_cluster", "fake_good_cluster"]
  3277. )
  3278. with patch(
  3279. "salt.utils.vmware.get_mors_with_properties",
  3280. MagicMock(return_value=self.mock_prop_hosts),
  3281. ):
  3282. with patch("salt.utils.vmware.get_managed_object_name", mock_get_cl_name):
  3283. res = salt.utils.vmware.get_hosts(
  3284. self.mock_si,
  3285. datacenter_name="fake_datacenter",
  3286. cluster_name="fake_good_cluster",
  3287. get_all_hosts=True,
  3288. )
  3289. self.assertEqual(mock_get_cl_name.call_count, 2)
  3290. self.assertEqual(res, [self.mock_host2])
  3291. def test_no_hosts(self):
  3292. with patch(
  3293. "salt.utils.vmware.get_mors_with_properties", MagicMock(return_value=[])
  3294. ):
  3295. res = salt.utils.vmware.get_hosts(self.mock_si, get_all_hosts=True)
  3296. self.assertEqual(res, [])
  3297. def test_one_host_returned(self):
  3298. with patch(
  3299. "salt.utils.vmware.get_mors_with_properties",
  3300. MagicMock(return_value=[self.mock_prop_host1]),
  3301. ):
  3302. res = salt.utils.vmware.get_hosts(self.mock_si, get_all_hosts=True)
  3303. self.assertEqual(res, [self.mock_host1])
  3304. @skipIf(not HAS_PYVMOMI, "The 'pyvmomi' library is missing")
  3305. class GetLicenseManagerTestCase(TestCase):
  3306. """
  3307. Tests for salt.utils.vmware.get_license_manager
  3308. """
  3309. def setUp(self):
  3310. self.mock_si = MagicMock()
  3311. self.mock_lic_mgr = MagicMock()
  3312. type(self.mock_si.content).licenseManager = PropertyMock(
  3313. return_value=self.mock_lic_mgr
  3314. )
  3315. def tearDown(self):
  3316. for attr in ("mock_si", "mock_lic_mgr"):
  3317. delattr(self, attr)
  3318. def test_raise_no_permission(self):
  3319. exc = vim.fault.NoPermission()
  3320. exc.privilegeId = "Fake privilege"
  3321. type(self.mock_si.content).licenseManager = PropertyMock(side_effect=exc)
  3322. with self.assertRaises(VMwareApiError) as excinfo:
  3323. salt.utils.vmware.get_license_manager(self.mock_si)
  3324. self.assertEqual(
  3325. excinfo.exception.strerror,
  3326. "Not enough permissions. Required privilege: " "Fake privilege",
  3327. )
  3328. def test_raise_vim_fault(self):
  3329. exc = vim.fault.VimFault()
  3330. exc.msg = "VimFault msg"
  3331. type(self.mock_si.content).licenseManager = PropertyMock(side_effect=exc)
  3332. with self.assertRaises(VMwareApiError) as excinfo:
  3333. salt.utils.vmware.get_license_manager(self.mock_si)
  3334. self.assertEqual(excinfo.exception.strerror, "VimFault msg")
  3335. def test_raise_runtime_fault(self):
  3336. exc = vmodl.RuntimeFault()
  3337. exc.msg = "RuntimeFault msg"
  3338. type(self.mock_si.content).licenseManager = PropertyMock(side_effect=exc)
  3339. with self.assertRaises(VMwareRuntimeError) as excinfo:
  3340. salt.utils.vmware.get_license_manager(self.mock_si)
  3341. self.assertEqual(excinfo.exception.strerror, "RuntimeFault msg")
  3342. def test_valid_assignment_manager(self):
  3343. ret = salt.utils.vmware.get_license_manager(self.mock_si)
  3344. self.assertEqual(ret, self.mock_lic_mgr)
  3345. @skipIf(not HAS_PYVMOMI, "The 'pyvmomi' library is missing")
  3346. class GetLicenseAssignmentManagerTestCase(TestCase):
  3347. """
  3348. Tests for salt.utils.vmware.get_license_assignment_manager
  3349. """
  3350. def setUp(self):
  3351. self.mock_si = MagicMock()
  3352. self.mock_lic_assign_mgr = MagicMock()
  3353. type(
  3354. self.mock_si.content.licenseManager
  3355. ).licenseAssignmentManager = PropertyMock(return_value=self.mock_lic_assign_mgr)
  3356. def tearDown(self):
  3357. for attr in ("mock_si", "mock_lic_assign_mgr"):
  3358. delattr(self, attr)
  3359. def test_raise_no_permission(self):
  3360. exc = vim.fault.NoPermission()
  3361. exc.privilegeId = "Fake privilege"
  3362. type(
  3363. self.mock_si.content.licenseManager
  3364. ).licenseAssignmentManager = PropertyMock(side_effect=exc)
  3365. with self.assertRaises(VMwareApiError) as excinfo:
  3366. salt.utils.vmware.get_license_assignment_manager(self.mock_si)
  3367. self.assertEqual(
  3368. excinfo.exception.strerror,
  3369. "Not enough permissions. Required privilege: " "Fake privilege",
  3370. )
  3371. def test_raise_vim_fault(self):
  3372. exc = vim.fault.VimFault()
  3373. exc.msg = "VimFault msg"
  3374. type(
  3375. self.mock_si.content.licenseManager
  3376. ).licenseAssignmentManager = PropertyMock(side_effect=exc)
  3377. with self.assertRaises(VMwareApiError) as excinfo:
  3378. salt.utils.vmware.get_license_assignment_manager(self.mock_si)
  3379. self.assertEqual(excinfo.exception.strerror, "VimFault msg")
  3380. def test_raise_runtime_fault(self):
  3381. exc = vmodl.RuntimeFault()
  3382. exc.msg = "RuntimeFault msg"
  3383. type(
  3384. self.mock_si.content.licenseManager
  3385. ).licenseAssignmentManager = PropertyMock(side_effect=exc)
  3386. with self.assertRaises(VMwareRuntimeError) as excinfo:
  3387. salt.utils.vmware.get_license_assignment_manager(self.mock_si)
  3388. self.assertEqual(excinfo.exception.strerror, "RuntimeFault msg")
  3389. def test_empty_license_assignment_manager(self):
  3390. type(
  3391. self.mock_si.content.licenseManager
  3392. ).licenseAssignmentManager = PropertyMock(return_value=None)
  3393. with self.assertRaises(VMwareObjectRetrievalError) as excinfo:
  3394. salt.utils.vmware.get_license_assignment_manager(self.mock_si)
  3395. self.assertEqual(
  3396. excinfo.exception.strerror, "License assignment manager was not retrieved"
  3397. )
  3398. def test_valid_assignment_manager(self):
  3399. ret = salt.utils.vmware.get_license_assignment_manager(self.mock_si)
  3400. self.assertEqual(ret, self.mock_lic_assign_mgr)
  3401. @skipIf(not HAS_PYVMOMI, "The 'pyvmomi' library is missing")
  3402. class GetLicensesTestCase(TestCase):
  3403. """
  3404. Tests for salt.utils.vmware.get_licenses
  3405. """
  3406. def setUp(self):
  3407. self.mock_si = MagicMock()
  3408. self.mock_licenses = [MagicMock(), MagicMock()]
  3409. self.mock_lic_mgr = MagicMock()
  3410. type(self.mock_lic_mgr).licenses = PropertyMock(return_value=self.mock_licenses)
  3411. patches = (
  3412. (
  3413. "salt.utils.vmware.get_license_manager",
  3414. MagicMock(return_value=self.mock_lic_mgr),
  3415. ),
  3416. )
  3417. for mod, mock in patches:
  3418. patcher = patch(mod, mock)
  3419. patcher.start()
  3420. self.addCleanup(patcher.stop)
  3421. def tearDown(self):
  3422. for attr in ("mock_si", "mock_lic_mgr", "mock_licenses"):
  3423. delattr(self, attr)
  3424. def test_no_license_manager_passed_in(self):
  3425. mock_get_license_manager = MagicMock()
  3426. with patch("salt.utils.vmware.get_license_manager", mock_get_license_manager):
  3427. salt.utils.vmware.get_licenses(self.mock_si)
  3428. mock_get_license_manager.assert_called_once_with(self.mock_si)
  3429. def test_license_manager_passed_in(self):
  3430. mock_licenses = PropertyMock()
  3431. mock_lic_mgr = MagicMock()
  3432. type(mock_lic_mgr).licenses = mock_licenses
  3433. mock_get_license_manager = MagicMock()
  3434. with patch("salt.utils.vmware.get_license_manager", mock_get_license_manager):
  3435. salt.utils.vmware.get_licenses(self.mock_si, license_manager=mock_lic_mgr)
  3436. self.assertEqual(mock_get_license_manager.call_count, 0)
  3437. self.assertEqual(mock_licenses.call_count, 1)
  3438. def test_raise_no_permission(self):
  3439. exc = vim.fault.NoPermission()
  3440. exc.privilegeId = "Fake privilege"
  3441. type(self.mock_lic_mgr).licenses = PropertyMock(side_effect=exc)
  3442. with self.assertRaises(VMwareApiError) as excinfo:
  3443. salt.utils.vmware.get_licenses(self.mock_si)
  3444. self.assertEqual(
  3445. excinfo.exception.strerror,
  3446. "Not enough permissions. Required privilege: " "Fake privilege",
  3447. )
  3448. def test_raise_vim_fault(self):
  3449. exc = vim.fault.VimFault()
  3450. exc.msg = "VimFault msg"
  3451. type(self.mock_lic_mgr).licenses = PropertyMock(side_effect=exc)
  3452. with self.assertRaises(VMwareApiError) as excinfo:
  3453. salt.utils.vmware.get_licenses(self.mock_si)
  3454. self.assertEqual(excinfo.exception.strerror, "VimFault msg")
  3455. def test_raise_runtime_fault(self):
  3456. exc = vmodl.RuntimeFault()
  3457. exc.msg = "RuntimeFault msg"
  3458. type(self.mock_lic_mgr).licenses = PropertyMock(side_effect=exc)
  3459. with self.assertRaises(VMwareRuntimeError) as excinfo:
  3460. salt.utils.vmware.get_licenses(self.mock_si)
  3461. self.assertEqual(excinfo.exception.strerror, "RuntimeFault msg")
  3462. def test_valid_licenses(self):
  3463. ret = salt.utils.vmware.get_licenses(self.mock_si)
  3464. self.assertEqual(ret, self.mock_licenses)
  3465. @skipIf(not HAS_PYVMOMI, "The 'pyvmomi' library is missing")
  3466. class AddLicenseTestCase(TestCase):
  3467. """
  3468. Tests for salt.utils.vmware.add_license
  3469. """
  3470. def setUp(self):
  3471. self.mock_si = MagicMock()
  3472. self.mock_license = MagicMock()
  3473. self.mock_add_license = MagicMock(return_value=self.mock_license)
  3474. self.mock_lic_mgr = MagicMock(AddLicense=self.mock_add_license)
  3475. self.mock_label = MagicMock()
  3476. patches = (
  3477. (
  3478. "salt.utils.vmware.get_license_manager",
  3479. MagicMock(return_value=self.mock_lic_mgr),
  3480. ),
  3481. ("salt.utils.vmware.vim.KeyValue", MagicMock(return_value=self.mock_label)),
  3482. )
  3483. for mod, mock in patches:
  3484. patcher = patch(mod, mock)
  3485. patcher.start()
  3486. self.addCleanup(patcher.stop)
  3487. def tearDown(self):
  3488. for attr in (
  3489. "mock_si",
  3490. "mock_lic_mgr",
  3491. "mock_license",
  3492. "mock_add_license",
  3493. "mock_label",
  3494. ):
  3495. delattr(self, attr)
  3496. def test_no_license_manager_passed_in(self):
  3497. mock_get_license_manager = MagicMock()
  3498. with patch("salt.utils.vmware.get_license_manager", mock_get_license_manager):
  3499. salt.utils.vmware.add_license(
  3500. self.mock_si, "fake_license_key", "fake_license_description"
  3501. )
  3502. mock_get_license_manager.assert_called_once_with(self.mock_si)
  3503. def test_license_manager_passed_in(self):
  3504. mock_get_license_manager = MagicMock()
  3505. with patch("salt.utils.vmware.get_license_manager", mock_get_license_manager):
  3506. salt.utils.vmware.add_license(
  3507. self.mock_si,
  3508. "fake_license_key",
  3509. "fake_license_description",
  3510. license_manager=self.mock_lic_mgr,
  3511. )
  3512. self.assertEqual(mock_get_license_manager.call_count, 0)
  3513. self.assertEqual(self.mock_add_license.call_count, 1)
  3514. def test_label_settings(self):
  3515. salt.utils.vmware.add_license(
  3516. self.mock_si, "fake_license_key", "fake_license_description"
  3517. )
  3518. self.assertEqual(self.mock_label.key, "VpxClientLicenseLabel")
  3519. self.assertEqual(self.mock_label.value, "fake_license_description")
  3520. def test_add_license_arguments(self):
  3521. salt.utils.vmware.add_license(
  3522. self.mock_si, "fake_license_key", "fake_license_description"
  3523. )
  3524. self.mock_add_license.assert_called_once_with(
  3525. "fake_license_key", [self.mock_label]
  3526. )
  3527. def test_add_license_raises_no_permission(self):
  3528. exc = vim.fault.NoPermission()
  3529. exc.privilegeId = "Fake privilege"
  3530. self.mock_lic_mgr.AddLicense = MagicMock(side_effect=exc)
  3531. with self.assertRaises(VMwareApiError) as excinfo:
  3532. salt.utils.vmware.add_license(
  3533. self.mock_si, "fake_license_key", "fake_license_description"
  3534. )
  3535. self.assertEqual(
  3536. excinfo.exception.strerror,
  3537. "Not enough permissions. Required privilege: " "Fake privilege",
  3538. )
  3539. def test_add_license_raises_vim_fault(self):
  3540. exc = vim.fault.VimFault()
  3541. exc.msg = "VimFault msg"
  3542. self.mock_lic_mgr.AddLicense = MagicMock(side_effect=exc)
  3543. with self.assertRaises(VMwareApiError) as excinfo:
  3544. salt.utils.vmware.add_license(
  3545. self.mock_si, "fake_license_key", "fake_license_description"
  3546. )
  3547. self.assertEqual(excinfo.exception.strerror, "VimFault msg")
  3548. def test_add_license_raises_runtime_fault(self):
  3549. exc = vmodl.RuntimeFault()
  3550. exc.msg = "RuntimeFault msg"
  3551. self.mock_lic_mgr.AddLicense = MagicMock(side_effect=exc)
  3552. with self.assertRaises(VMwareRuntimeError) as excinfo:
  3553. salt.utils.vmware.add_license(
  3554. self.mock_si, "fake_license_key", "fake_license_description"
  3555. )
  3556. self.assertEqual(excinfo.exception.strerror, "RuntimeFault msg")
  3557. def test_valid_license_added(self):
  3558. ret = salt.utils.vmware.add_license(
  3559. self.mock_si, "fake_license_key", "fake_license_description"
  3560. )
  3561. self.assertEqual(ret, self.mock_license)
  3562. @skipIf(not HAS_PYVMOMI, "The 'pyvmomi' library is missing")
  3563. class GetAssignedLicensesTestCase(TestCase):
  3564. """
  3565. Tests for salt.utils.vmware.get_assigned_licenses
  3566. """
  3567. def setUp(self):
  3568. self.mock_ent_id = MagicMock()
  3569. self.mock_si = MagicMock()
  3570. type(self.mock_si.content.about).instanceUuid = PropertyMock(
  3571. return_value=self.mock_ent_id
  3572. )
  3573. self.mock_moid = MagicMock()
  3574. self.prop_mock_moid = PropertyMock(return_value=self.mock_moid)
  3575. self.mock_entity_ref = MagicMock()
  3576. type(self.mock_entity_ref)._moId = self.prop_mock_moid
  3577. self.mock_assignments = [
  3578. MagicMock(entityDisplayName="fake_ent1"),
  3579. MagicMock(entityDisplayName="fake_ent2"),
  3580. ]
  3581. self.mock_query_assigned_licenses = MagicMock(
  3582. return_value=[
  3583. MagicMock(assignedLicense=self.mock_assignments[0]),
  3584. MagicMock(assignedLicense=self.mock_assignments[1]),
  3585. ]
  3586. )
  3587. self.mock_lic_assign_mgr = MagicMock(
  3588. QueryAssignedLicenses=self.mock_query_assigned_licenses
  3589. )
  3590. patches = (
  3591. (
  3592. "salt.utils.vmware.get_license_assignment_manager",
  3593. MagicMock(return_value=self.mock_lic_assign_mgr),
  3594. ),
  3595. )
  3596. for mod, mock in patches:
  3597. patcher = patch(mod, mock)
  3598. patcher.start()
  3599. self.addCleanup(patcher.stop)
  3600. def tearDown(self):
  3601. for attr in (
  3602. "mock_ent_id",
  3603. "mock_si",
  3604. "mock_moid",
  3605. "prop_mock_moid",
  3606. "mock_entity_ref",
  3607. "mock_assignments",
  3608. "mock_query_assigned_licenses",
  3609. "mock_lic_assign_mgr",
  3610. ):
  3611. delattr(self, attr)
  3612. def test_no_license_assignment_manager_passed_in(self):
  3613. mock_get_license_assign_manager = MagicMock()
  3614. with patch(
  3615. "salt.utils.vmware.get_license_assignment_manager",
  3616. mock_get_license_assign_manager,
  3617. ):
  3618. salt.utils.vmware.get_assigned_licenses(
  3619. self.mock_si, self.mock_entity_ref, "fake_entity_name"
  3620. )
  3621. mock_get_license_assign_manager.assert_called_once_with(self.mock_si)
  3622. def test_license_assignment_manager_passed_in(self):
  3623. mock_get_license_assign_manager = MagicMock()
  3624. with patch(
  3625. "salt.utils.vmware.get_license_assignment_manager",
  3626. mock_get_license_assign_manager,
  3627. ):
  3628. salt.utils.vmware.get_assigned_licenses(
  3629. self.mock_si,
  3630. self.mock_entity_ref,
  3631. "fake_entity_name",
  3632. license_assignment_manager=self.mock_lic_assign_mgr,
  3633. )
  3634. self.assertEqual(mock_get_license_assign_manager.call_count, 0)
  3635. def test_entity_name(self):
  3636. mock_trace = MagicMock()
  3637. with patch("salt._logging.impl.SaltLoggingClass.trace", mock_trace):
  3638. salt.utils.vmware.get_assigned_licenses(
  3639. self.mock_si, self.mock_entity_ref, "fake_entity_name"
  3640. )
  3641. mock_trace.assert_called_once_with(
  3642. "Retrieving licenses assigned to '%s'", "fake_entity_name"
  3643. )
  3644. def test_instance_uuid(self):
  3645. mock_instance_uuid_prop = PropertyMock()
  3646. type(self.mock_si.content.about).instanceUuid = mock_instance_uuid_prop
  3647. self.mock_lic_assign_mgr.QueryAssignedLicenses = MagicMock(
  3648. return_value=[MagicMock(entityDisplayName="fake_vcenter")]
  3649. )
  3650. salt.utils.vmware.get_assigned_licenses(
  3651. self.mock_si, entity_name="fake_vcenter"
  3652. )
  3653. self.assertEqual(mock_instance_uuid_prop.call_count, 1)
  3654. def test_instance_uuid_raises_no_permission(self):
  3655. exc = vim.fault.NoPermission()
  3656. exc.privilegeId = "Fake privilege"
  3657. type(self.mock_si.content.about).instanceUuid = PropertyMock(side_effect=exc)
  3658. with self.assertRaises(VMwareApiError) as excinfo:
  3659. salt.utils.vmware.get_assigned_licenses(
  3660. self.mock_si, entity_name="fake_vcenter"
  3661. )
  3662. self.assertEqual(
  3663. excinfo.exception.strerror,
  3664. "Not enough permissions. Required privilege: " "Fake privilege",
  3665. )
  3666. def test_instance_uuid_raises_vim_fault(self):
  3667. exc = vim.fault.VimFault()
  3668. exc.msg = "VimFault msg"
  3669. type(self.mock_si.content.about).instanceUuid = PropertyMock(side_effect=exc)
  3670. with self.assertRaises(VMwareApiError) as excinfo:
  3671. salt.utils.vmware.get_assigned_licenses(
  3672. self.mock_si, entity_name="fake_vcenter"
  3673. )
  3674. self.assertEqual(excinfo.exception.strerror, "VimFault msg")
  3675. def test_instance_uuid_raises_runtime_fault(self):
  3676. exc = vmodl.RuntimeFault()
  3677. exc.msg = "RuntimeFault msg"
  3678. type(self.mock_si.content.about).instanceUuid = PropertyMock(side_effect=exc)
  3679. with self.assertRaises(VMwareRuntimeError) as excinfo:
  3680. salt.utils.vmware.get_assigned_licenses(
  3681. self.mock_si, entity_name="fake_vcenter"
  3682. )
  3683. self.assertEqual(excinfo.exception.strerror, "RuntimeFault msg")
  3684. def test_vcenter_entity_too_many_assignements(self):
  3685. self.mock_lic_assign_mgr.QueryAssignedLicenses = MagicMock(
  3686. return_value=[MagicMock(), MagicMock()]
  3687. )
  3688. with self.assertRaises(VMwareObjectRetrievalError) as excinfo:
  3689. salt.utils.vmware.get_assigned_licenses(
  3690. self.mock_si, entity_name="fake_vcenter"
  3691. )
  3692. self.assertEqual(
  3693. excinfo.exception.strerror,
  3694. "Unexpected return. Expect only a single assignment",
  3695. )
  3696. def test_wrong_vcenter_name(self):
  3697. self.mock_lic_assign_mgr.QueryAssignedLicenses = MagicMock(
  3698. return_value=[MagicMock(entityDisplayName="bad_vcenter")]
  3699. )
  3700. with self.assertRaises(VMwareObjectRetrievalError) as excinfo:
  3701. salt.utils.vmware.get_assigned_licenses(
  3702. self.mock_si, entity_name="fake_vcenter"
  3703. )
  3704. self.assertEqual(
  3705. excinfo.exception.strerror,
  3706. "Got license assignment info for a different vcenter",
  3707. )
  3708. def test_query_assigned_licenses_vcenter(self):
  3709. with self.assertRaises(VMwareObjectRetrievalError) as excinfo:
  3710. salt.utils.vmware.get_assigned_licenses(
  3711. self.mock_si, entity_name="fake_vcenter"
  3712. )
  3713. self.mock_query_assigned_licenses.assert_called_once_with(self.mock_ent_id)
  3714. def test_query_assigned_licenses_with_entity(self):
  3715. salt.utils.vmware.get_assigned_licenses(
  3716. self.mock_si, self.mock_entity_ref, "fake_entity_name"
  3717. )
  3718. self.mock_query_assigned_licenses.assert_called_once_with(self.mock_moid)
  3719. def test_query_assigned_licenses_raises_no_permission(self):
  3720. exc = vim.fault.NoPermission()
  3721. exc.privilegeId = "Fake privilege"
  3722. self.mock_lic_assign_mgr.QueryAssignedLicenses = MagicMock(side_effect=exc)
  3723. with self.assertRaises(VMwareApiError) as excinfo:
  3724. salt.utils.vmware.get_assigned_licenses(
  3725. self.mock_si, self.mock_entity_ref, "fake_entity_name"
  3726. )
  3727. self.assertEqual(
  3728. excinfo.exception.strerror,
  3729. "Not enough permissions. Required privilege: " "Fake privilege",
  3730. )
  3731. def test_query_assigned_licenses_raises_vim_fault(self):
  3732. exc = vim.fault.VimFault()
  3733. exc.msg = "VimFault msg"
  3734. self.mock_lic_assign_mgr.QueryAssignedLicenses = MagicMock(side_effect=exc)
  3735. with self.assertRaises(VMwareApiError) as excinfo:
  3736. salt.utils.vmware.get_assigned_licenses(
  3737. self.mock_si, self.mock_entity_ref, "fake_entity_name"
  3738. )
  3739. self.assertEqual(excinfo.exception.strerror, "VimFault msg")
  3740. def test_query_assigned_licenses_raises_runtime_fault(self):
  3741. exc = vmodl.RuntimeFault()
  3742. exc.msg = "RuntimeFault msg"
  3743. self.mock_lic_assign_mgr.QueryAssignedLicenses = MagicMock(side_effect=exc)
  3744. with self.assertRaises(VMwareRuntimeError) as excinfo:
  3745. salt.utils.vmware.get_assigned_licenses(
  3746. self.mock_si, self.mock_entity_ref, "fake_entity_name"
  3747. )
  3748. self.assertEqual(excinfo.exception.strerror, "RuntimeFault msg")
  3749. def test_valid_assignments(self):
  3750. ret = salt.utils.vmware.get_assigned_licenses(
  3751. self.mock_si, self.mock_entity_ref, "fake_entity_name"
  3752. )
  3753. self.assertEqual(ret, self.mock_assignments)
  3754. @skipIf(not HAS_PYVMOMI, "The 'pyvmomi' library is missing")
  3755. class AssignLicenseTestCase(TestCase):
  3756. """
  3757. Tests for salt.utils.vmware.assign_license
  3758. """
  3759. def setUp(self):
  3760. self.mock_ent_id = MagicMock()
  3761. self.mock_si = MagicMock()
  3762. type(self.mock_si.content.about).instanceUuid = PropertyMock(
  3763. return_value=self.mock_ent_id
  3764. )
  3765. self.mock_lic_key = MagicMock()
  3766. self.mock_moid = MagicMock()
  3767. self.prop_mock_moid = PropertyMock(return_value=self.mock_moid)
  3768. self.mock_entity_ref = MagicMock()
  3769. type(self.mock_entity_ref)._moId = self.prop_mock_moid
  3770. self.mock_license = MagicMock()
  3771. self.mock_update_assigned_license = MagicMock(return_value=self.mock_license)
  3772. self.mock_lic_assign_mgr = MagicMock(
  3773. UpdateAssignedLicense=self.mock_update_assigned_license
  3774. )
  3775. patches = (
  3776. (
  3777. "salt.utils.vmware.get_license_assignment_manager",
  3778. MagicMock(return_value=self.mock_lic_assign_mgr),
  3779. ),
  3780. )
  3781. for mod, mock in patches:
  3782. patcher = patch(mod, mock)
  3783. patcher.start()
  3784. self.addCleanup(patcher.stop)
  3785. def test_no_license_assignment_manager_passed_in(self):
  3786. mock_get_license_assign_manager = MagicMock()
  3787. with patch(
  3788. "salt.utils.vmware.get_license_assignment_manager",
  3789. mock_get_license_assign_manager,
  3790. ):
  3791. salt.utils.vmware.assign_license(
  3792. self.mock_si,
  3793. self.mock_lic_key,
  3794. "fake_license_name",
  3795. self.mock_entity_ref,
  3796. "fake_entity_name",
  3797. )
  3798. mock_get_license_assign_manager.assert_called_once_with(self.mock_si)
  3799. def test_license_assignment_manager_passed_in(self):
  3800. mock_get_license_assign_manager = MagicMock()
  3801. with patch(
  3802. "salt.utils.vmware.get_license_assignment_manager",
  3803. mock_get_license_assign_manager,
  3804. ):
  3805. salt.utils.vmware.assign_license(
  3806. self.mock_si,
  3807. self.mock_lic_key,
  3808. "fake_license_name",
  3809. self.mock_entity_ref,
  3810. "fake_entity_name",
  3811. license_assignment_manager=self.mock_lic_assign_mgr,
  3812. )
  3813. self.assertEqual(mock_get_license_assign_manager.call_count, 0)
  3814. self.assertEqual(self.mock_update_assigned_license.call_count, 1)
  3815. def test_entity_name(self):
  3816. mock_trace = MagicMock()
  3817. with patch("salt._logging.impl.SaltLoggingClass.trace", mock_trace):
  3818. salt.utils.vmware.assign_license(
  3819. self.mock_si,
  3820. self.mock_lic_key,
  3821. "fake_license_name",
  3822. self.mock_entity_ref,
  3823. "fake_entity_name",
  3824. )
  3825. mock_trace.assert_called_once_with(
  3826. "Assigning license to '%s'", "fake_entity_name"
  3827. )
  3828. def test_instance_uuid(self):
  3829. mock_instance_uuid_prop = PropertyMock()
  3830. type(self.mock_si.content.about).instanceUuid = mock_instance_uuid_prop
  3831. self.mock_lic_assign_mgr.UpdateAssignedLicense = MagicMock(
  3832. return_value=[MagicMock(entityDisplayName="fake_vcenter")]
  3833. )
  3834. salt.utils.vmware.assign_license(
  3835. self.mock_si,
  3836. self.mock_lic_key,
  3837. "fake_license_name",
  3838. entity_name="fake_entity_name",
  3839. )
  3840. self.assertEqual(mock_instance_uuid_prop.call_count, 1)
  3841. def test_instance_uuid_raises_no_permission(self):
  3842. exc = vim.fault.NoPermission()
  3843. exc.privilegeId = "Fake privilege"
  3844. type(self.mock_si.content.about).instanceUuid = PropertyMock(side_effect=exc)
  3845. with self.assertRaises(VMwareApiError) as excinfo:
  3846. salt.utils.vmware.assign_license(
  3847. self.mock_si,
  3848. self.mock_lic_key,
  3849. "fake_license_name",
  3850. entity_name="fake_entity_name",
  3851. )
  3852. self.assertEqual(
  3853. excinfo.exception.strerror,
  3854. "Not enough permissions. Required privilege: " "Fake privilege",
  3855. )
  3856. def test_instance_uuid_raises_vim_fault(self):
  3857. exc = vim.fault.VimFault()
  3858. exc.msg = "VimFault msg"
  3859. type(self.mock_si.content.about).instanceUuid = PropertyMock(side_effect=exc)
  3860. with self.assertRaises(VMwareApiError) as excinfo:
  3861. salt.utils.vmware.assign_license(
  3862. self.mock_si,
  3863. self.mock_lic_key,
  3864. "fake_license_name",
  3865. entity_name="fake_entity_name",
  3866. )
  3867. self.assertEqual(excinfo.exception.strerror, "VimFault msg")
  3868. def test_instance_uuid_raises_runtime_fault(self):
  3869. exc = vmodl.RuntimeFault()
  3870. exc.msg = "RuntimeFault msg"
  3871. type(self.mock_si.content.about).instanceUuid = PropertyMock(side_effect=exc)
  3872. with self.assertRaises(VMwareRuntimeError) as excinfo:
  3873. salt.utils.vmware.assign_license(
  3874. self.mock_si,
  3875. self.mock_lic_key,
  3876. "fake_license_name",
  3877. entity_name="fake_entity_name",
  3878. )
  3879. self.assertEqual(excinfo.exception.strerror, "RuntimeFault msg")
  3880. def test_update_assigned_licenses_vcenter(self):
  3881. salt.utils.vmware.assign_license(
  3882. self.mock_si,
  3883. self.mock_lic_key,
  3884. "fake_license_name",
  3885. entity_name="fake_entity_name",
  3886. )
  3887. self.mock_update_assigned_license.assert_called_once_with(
  3888. self.mock_ent_id, self.mock_lic_key, "fake_license_name"
  3889. )
  3890. def test_update_assigned_licenses_call_with_entity(self):
  3891. salt.utils.vmware.assign_license(
  3892. self.mock_si,
  3893. self.mock_lic_key,
  3894. "fake_license_name",
  3895. self.mock_entity_ref,
  3896. "fake_entity_name",
  3897. )
  3898. self.mock_update_assigned_license.assert_called_once_with(
  3899. self.mock_moid, self.mock_lic_key, "fake_license_name"
  3900. )
  3901. def test_update_assigned_licenses_raises_no_permission(self):
  3902. exc = vim.fault.NoPermission()
  3903. exc.privilegeId = "Fake privilege"
  3904. self.mock_lic_assign_mgr.UpdateAssignedLicense = MagicMock(side_effect=exc)
  3905. with self.assertRaises(VMwareApiError) as excinfo:
  3906. salt.utils.vmware.assign_license(
  3907. self.mock_si,
  3908. self.mock_lic_key,
  3909. "fake_license_name",
  3910. self.mock_entity_ref,
  3911. "fake_entity_name",
  3912. )
  3913. self.assertEqual(
  3914. excinfo.exception.strerror,
  3915. "Not enough permissions. Required privilege: " "Fake privilege",
  3916. )
  3917. def test_update_assigned_licenses_raises_vim_fault(self):
  3918. exc = vim.fault.VimFault()
  3919. exc.msg = "VimFault msg"
  3920. self.mock_lic_assign_mgr.UpdateAssignedLicense = MagicMock(side_effect=exc)
  3921. with self.assertRaises(VMwareApiError) as excinfo:
  3922. salt.utils.vmware.assign_license(
  3923. self.mock_si,
  3924. self.mock_lic_key,
  3925. "fake_license_name",
  3926. self.mock_entity_ref,
  3927. "fake_entity_name",
  3928. )
  3929. self.assertEqual(excinfo.exception.strerror, "VimFault msg")
  3930. def test_update_assigned_licenses_raises_runtime_fault(self):
  3931. exc = vmodl.RuntimeFault()
  3932. exc.msg = "RuntimeFault msg"
  3933. self.mock_lic_assign_mgr.UpdateAssignedLicense = MagicMock(side_effect=exc)
  3934. with self.assertRaises(VMwareRuntimeError) as excinfo:
  3935. salt.utils.vmware.assign_license(
  3936. self.mock_si,
  3937. self.mock_lic_key,
  3938. "fake_license_name",
  3939. self.mock_entity_ref,
  3940. "fake_entity_name",
  3941. )
  3942. self.assertEqual(excinfo.exception.strerror, "RuntimeFault msg")
  3943. def test_valid_assignments(self):
  3944. ret = salt.utils.vmware.assign_license(
  3945. self.mock_si,
  3946. self.mock_lic_key,
  3947. "fake_license_name",
  3948. self.mock_entity_ref,
  3949. "fake_entity_name",
  3950. )
  3951. self.assertEqual(ret, self.mock_license)
  3952. @skipIf(not HAS_PYVMOMI, "The 'pyvmomi' library is missing")
  3953. class GetStorageSystemTestCase(TestCase):
  3954. """
  3955. Tests for salt.utils.vmware.get_storage_system
  3956. """
  3957. def setUp(self):
  3958. self.mock_si = MagicMock(content=MagicMock())
  3959. self.mock_host_ref = MagicMock()
  3960. self.mock_get_managed_object_name = MagicMock(return_value="fake_host")
  3961. self.mock_traversal_spec = MagicMock()
  3962. self.mock_obj = MagicMock()
  3963. self.mock_get_mors = MagicMock(return_value=[{"object": self.mock_obj}])
  3964. patches = (
  3965. (
  3966. "salt.utils.vmware.get_managed_object_name",
  3967. self.mock_get_managed_object_name,
  3968. ),
  3969. ("salt.utils.vmware.get_mors_with_properties", self.mock_get_mors),
  3970. (
  3971. "salt.utils.vmware.vmodl.query.PropertyCollector.TraversalSpec",
  3972. MagicMock(return_value=self.mock_traversal_spec),
  3973. ),
  3974. )
  3975. for mod, mock in patches:
  3976. patcher = patch(mod, mock)
  3977. patcher.start()
  3978. self.addCleanup(patcher.stop)
  3979. def tearDown(self):
  3980. for attr in (
  3981. "mock_si",
  3982. "mock_host_ref",
  3983. "mock_get_managed_object_name",
  3984. "mock_traversal_spec",
  3985. "mock_obj",
  3986. ):
  3987. delattr(self, attr)
  3988. def test_no_hostname_argument(self):
  3989. salt.utils.vmware.get_storage_system(self.mock_si, self.mock_host_ref)
  3990. self.mock_get_managed_object_name.assert_called_once_with(self.mock_host_ref)
  3991. def test_hostname_argument(self):
  3992. salt.utils.vmware.get_storage_system(
  3993. self.mock_si, self.mock_host_ref, hostname="fake_host"
  3994. )
  3995. self.assertEqual(self.mock_get_managed_object_name.call_count, 0)
  3996. def test_traversal_spec(self):
  3997. mock_traversal_spec = MagicMock(return_value=[{"object": self.mock_obj}])
  3998. with patch(
  3999. "salt.utils.vmware.vmodl.query.PropertyCollector.TraversalSpec",
  4000. mock_traversal_spec,
  4001. ):
  4002. salt.utils.vmware.get_storage_system(self.mock_si, self.mock_host_ref)
  4003. mock_traversal_spec.assert_called_once_with(
  4004. path="configManager.storageSystem", type=vim.HostSystem, skip=False
  4005. )
  4006. def test_get_mors_with_properties(self):
  4007. salt.utils.vmware.get_storage_system(self.mock_si, self.mock_host_ref)
  4008. self.mock_get_mors.assert_called_once_with(
  4009. self.mock_si,
  4010. vim.HostStorageSystem,
  4011. property_list=["systemFile"],
  4012. container_ref=self.mock_host_ref,
  4013. traversal_spec=self.mock_traversal_spec,
  4014. )
  4015. def test_empty_mors_result(self):
  4016. with patch(
  4017. "salt.utils.vmware.get_mors_with_properties", MagicMock(return_value=[])
  4018. ):
  4019. with self.assertRaises(VMwareObjectRetrievalError) as excinfo:
  4020. salt.utils.vmware.get_storage_system(self.mock_si, self.mock_host_ref)
  4021. self.assertEqual(
  4022. excinfo.exception.strerror,
  4023. "Host's 'fake_host' storage system was " "not retrieved",
  4024. )
  4025. def test_valid_mors_result(self):
  4026. res = salt.utils.vmware.get_storage_system(self.mock_si, self.mock_host_ref)
  4027. self.assertEqual(res, self.mock_obj)
  4028. @skipIf(not HAS_PYVMOMI, "The 'pyvmomi' library is missing")
  4029. class GetDatastoresTestCase(TestCase):
  4030. """
  4031. Tests for salt.utils.vmware.get_datastores
  4032. """
  4033. def setUp(self):
  4034. self.mock_si = MagicMock()
  4035. self.mock_reference = MagicMock(spec=vim.HostSystem)
  4036. self.mock_mount_infos = [
  4037. MagicMock(
  4038. volume=MagicMock(
  4039. spec=vim.HostVmfsVolume, extent=[MagicMock(diskName="fake_disk2")]
  4040. )
  4041. ),
  4042. MagicMock(
  4043. volume=MagicMock(
  4044. spec=vim.HostVmfsVolume, extent=[MagicMock(diskName="fake_disk3")]
  4045. )
  4046. ),
  4047. ]
  4048. self.mock_mount_infos[0].volume.name = "fake_ds2"
  4049. self.mock_mount_infos[1].volume.name = "fake_ds3"
  4050. self.mock_entries = [
  4051. {"name": "fake_ds1", "object": MagicMock()},
  4052. {"name": "fake_ds2", "object": MagicMock()},
  4053. {"name": "fake_ds3", "object": MagicMock()},
  4054. ]
  4055. self.mock_storage_system = MagicMock()
  4056. self.mock_get_storage_system = MagicMock(return_value=self.mock_storage_system)
  4057. self.mock_get_managed_object_name = MagicMock(return_value="fake_host")
  4058. self.mock_traversal_spec = MagicMock()
  4059. patches = (
  4060. (
  4061. "salt.utils.vmware.get_managed_object_name",
  4062. self.mock_get_managed_object_name,
  4063. ),
  4064. ("salt.utils.vmware.get_storage_system", self.mock_get_storage_system),
  4065. (
  4066. "salt.utils.vmware.get_properties_of_managed_object",
  4067. MagicMock(
  4068. return_value={
  4069. "fileSystemVolumeInfo.mountInfo": self.mock_mount_infos
  4070. }
  4071. ),
  4072. ),
  4073. (
  4074. "salt.utils.vmware.get_mors_with_properties",
  4075. MagicMock(return_value=self.mock_entries),
  4076. ),
  4077. (
  4078. "salt.utils.vmware.vmodl.query.PropertyCollector.TraversalSpec",
  4079. MagicMock(return_value=self.mock_traversal_spec),
  4080. ),
  4081. )
  4082. for mod, mock in patches:
  4083. patcher = patch(mod, mock)
  4084. patcher.start()
  4085. self.addCleanup(patcher.stop)
  4086. def tearDown(self):
  4087. for attr in (
  4088. "mock_si",
  4089. "mock_reference",
  4090. "mock_storage_system",
  4091. "mock_get_storage_system",
  4092. "mock_mount_infos",
  4093. "mock_entries",
  4094. "mock_get_managed_object_name",
  4095. "mock_traversal_spec",
  4096. ):
  4097. delattr(self, attr)
  4098. def test_get_reference_name_call(self):
  4099. salt.utils.vmware.get_datastores(self.mock_si, self.mock_reference)
  4100. self.mock_get_managed_object_name.assert_called_once_with(self.mock_reference)
  4101. def test_get_no_datastores(self):
  4102. res = salt.utils.vmware.get_datastores(self.mock_si, self.mock_reference)
  4103. self.assertEqual(res, [])
  4104. def test_get_storage_system_call(self):
  4105. salt.utils.vmware.get_datastores(
  4106. self.mock_si, self.mock_reference, backing_disk_ids=["fake_disk1"]
  4107. )
  4108. self.mock_get_storage_system.assert_called_once_with(
  4109. self.mock_si, self.mock_reference, "fake_host"
  4110. )
  4111. def test_get_mount_info_call(self):
  4112. mock_get_properties_of_managed_object = MagicMock()
  4113. with patch(
  4114. "salt.utils.vmware.get_properties_of_managed_object",
  4115. mock_get_properties_of_managed_object,
  4116. ):
  4117. salt.utils.vmware.get_datastores(
  4118. self.mock_si, self.mock_reference, backing_disk_ids=["fake_disk1"]
  4119. )
  4120. mock_get_properties_of_managed_object.assert_called_once_with(
  4121. self.mock_storage_system, ["fileSystemVolumeInfo.mountInfo"]
  4122. )
  4123. def test_backing_disks_no_mount_info(self):
  4124. with patch(
  4125. "salt.utils.vmware.get_properties_of_managed_object",
  4126. MagicMock(return_value={}),
  4127. ):
  4128. res = salt.utils.vmware.get_datastores(
  4129. self.mock_si, self.mock_reference, backing_disk_ids=["fake_disk_id"]
  4130. )
  4131. self.assertEqual(res, [])
  4132. def test_host_traversal_spec(self):
  4133. # Reference is of type vim.HostSystem
  4134. mock_traversal_spec_init = MagicMock()
  4135. with patch(
  4136. "salt.utils.vmware.vmodl.query.PropertyCollector.TraversalSpec",
  4137. mock_traversal_spec_init,
  4138. ):
  4139. salt.utils.vmware.get_datastores(
  4140. self.mock_si, self.mock_reference, get_all_datastores=True
  4141. )
  4142. mock_traversal_spec_init.assert_called_once_with(
  4143. name="host_datastore_traversal",
  4144. path="datastore",
  4145. skip=False,
  4146. type=vim.HostSystem,
  4147. )
  4148. def test_cluster_traversal_spec(self):
  4149. mock_traversal_spec_init = MagicMock()
  4150. # Reference is of type vim.ClusterComputeResource
  4151. mock_reference = MagicMock(spec=vim.ClusterComputeResource)
  4152. with patch(
  4153. "salt.utils.vmware.vmodl.query.PropertyCollector.TraversalSpec",
  4154. mock_traversal_spec_init,
  4155. ):
  4156. salt.utils.vmware.get_datastores(
  4157. self.mock_si, mock_reference, get_all_datastores=True
  4158. )
  4159. mock_traversal_spec_init.assert_called_once_with(
  4160. name="cluster_datastore_traversal",
  4161. path="datastore",
  4162. skip=False,
  4163. type=vim.ClusterComputeResource,
  4164. )
  4165. def test_datacenter_traversal_spec(self):
  4166. mock_traversal_spec_init = MagicMock()
  4167. # Reference is of type vim.ClusterComputeResource
  4168. mock_reference = MagicMock(spec=vim.Datacenter)
  4169. with patch(
  4170. "salt.utils.vmware.vmodl.query.PropertyCollector.TraversalSpec",
  4171. mock_traversal_spec_init,
  4172. ):
  4173. salt.utils.vmware.get_datastores(
  4174. self.mock_si, mock_reference, get_all_datastores=True
  4175. )
  4176. mock_traversal_spec_init.assert_called_once_with(
  4177. name="datacenter_datastore_traversal",
  4178. path="datastore",
  4179. skip=False,
  4180. type=vim.Datacenter,
  4181. )
  4182. def test_root_folder_traversal_spec(self):
  4183. mock_traversal_spec_init = MagicMock(return_value="traversal")
  4184. mock_reference = MagicMock(spec=vim.Folder)
  4185. with patch(
  4186. "salt.utils.vmware.get_managed_object_name",
  4187. MagicMock(side_effect=["fake_host", "Datacenters"]),
  4188. ):
  4189. with patch(
  4190. "salt.utils.vmware.vmodl.query.PropertyCollector.TraversalSpec",
  4191. mock_traversal_spec_init,
  4192. ):
  4193. salt.utils.vmware.get_datastores(
  4194. self.mock_si, mock_reference, get_all_datastores=True
  4195. )
  4196. mock_traversal_spec_init.assert_has_calls(
  4197. [
  4198. call(path="datastore", skip=False, type=vim.Datacenter),
  4199. call(
  4200. path="childEntity",
  4201. selectSet=["traversal"],
  4202. skip=False,
  4203. type=vim.Folder,
  4204. ),
  4205. ]
  4206. )
  4207. def test_unsupported_reference_type(self):
  4208. class FakeClass(object):
  4209. pass
  4210. mock_reference = MagicMock(spec=FakeClass)
  4211. with self.assertRaises(ArgumentValueError) as excinfo:
  4212. salt.utils.vmware.get_datastores(
  4213. self.mock_si, mock_reference, get_all_datastores=True
  4214. )
  4215. self.assertEqual(
  4216. excinfo.exception.strerror, "Unsupported reference type 'FakeClass'"
  4217. )
  4218. def test_get_mors_with_properties(self):
  4219. mock_get_mors_with_properties = MagicMock()
  4220. with patch(
  4221. "salt.utils.vmware.get_mors_with_properties", mock_get_mors_with_properties
  4222. ):
  4223. salt.utils.vmware.get_datastores(
  4224. self.mock_si, self.mock_reference, get_all_datastores=True
  4225. )
  4226. mock_get_mors_with_properties.assert_called_once_with(
  4227. self.mock_si,
  4228. object_type=vim.Datastore,
  4229. property_list=["name"],
  4230. container_ref=self.mock_reference,
  4231. traversal_spec=self.mock_traversal_spec,
  4232. )
  4233. def test_get_all_datastores(self):
  4234. res = salt.utils.vmware.get_datastores(
  4235. self.mock_si, self.mock_reference, get_all_datastores=True
  4236. )
  4237. self.assertEqual(
  4238. res,
  4239. [
  4240. self.mock_entries[0]["object"],
  4241. self.mock_entries[1]["object"],
  4242. self.mock_entries[2]["object"],
  4243. ],
  4244. )
  4245. def test_get_datastores_filtered_by_name(self):
  4246. res = salt.utils.vmware.get_datastores(
  4247. self.mock_si, self.mock_reference, datastore_names=["fake_ds1", "fake_ds2"]
  4248. )
  4249. self.assertEqual(
  4250. res, [self.mock_entries[0]["object"], self.mock_entries[1]["object"]]
  4251. )
  4252. def test_get_datastores_filtered_by_backing_disk(self):
  4253. res = salt.utils.vmware.get_datastores(
  4254. self.mock_si,
  4255. self.mock_reference,
  4256. backing_disk_ids=["fake_disk2", "fake_disk3"],
  4257. )
  4258. self.assertEqual(
  4259. res, [self.mock_entries[1]["object"], self.mock_entries[2]["object"]]
  4260. )
  4261. def test_get_datastores_filtered_by_both_name_and_backing_disk(self):
  4262. # Simulate VMware data model for volumes fake_ds2, fake_ds3
  4263. res = salt.utils.vmware.get_datastores(
  4264. self.mock_si,
  4265. self.mock_reference,
  4266. datastore_names=["fake_ds1"],
  4267. backing_disk_ids=["fake_disk3"],
  4268. )
  4269. self.assertEqual(
  4270. res, [self.mock_entries[0]["object"], self.mock_entries[2]["object"]]
  4271. )
  4272. @skipIf(not HAS_PYVMOMI, "The 'pyvmomi' library is missing")
  4273. class RenameDatastoreTestCase(TestCase):
  4274. """
  4275. Tests for salt.utils.vmware.rename_datastore
  4276. """
  4277. def setUp(self):
  4278. self.mock_ds_ref = MagicMock()
  4279. self.mock_get_managed_object_name = MagicMock(return_value="fake_ds")
  4280. patches = (
  4281. (
  4282. "salt.utils.vmware.get_managed_object_name",
  4283. self.mock_get_managed_object_name,
  4284. ),
  4285. )
  4286. for mod, mock in patches:
  4287. patcher = patch(mod, mock)
  4288. patcher.start()
  4289. self.addCleanup(patcher.stop)
  4290. def tearDown(self):
  4291. for attr in ("mock_ds_ref", "mock_get_managed_object_name"):
  4292. delattr(self, attr)
  4293. def test_datastore_name_call(self):
  4294. salt.utils.vmware.rename_datastore(self.mock_ds_ref, "fake_new_name")
  4295. self.mock_get_managed_object_name.assert_called_once_with(self.mock_ds_ref)
  4296. def test_rename_datastore_raise_no_permission(self):
  4297. exc = vim.fault.NoPermission()
  4298. exc.privilegeId = "Fake privilege"
  4299. type(self.mock_ds_ref).RenameDatastore = MagicMock(side_effect=exc)
  4300. with self.assertRaises(VMwareApiError) as excinfo:
  4301. salt.utils.vmware.rename_datastore(self.mock_ds_ref, "fake_new_name")
  4302. self.assertEqual(
  4303. excinfo.exception.strerror,
  4304. "Not enough permissions. Required privilege: " "Fake privilege",
  4305. )
  4306. def test_rename_datastore_raise_vim_fault(self):
  4307. exc = vim.VimFault()
  4308. exc.msg = "vim_fault"
  4309. type(self.mock_ds_ref).RenameDatastore = MagicMock(side_effect=exc)
  4310. with self.assertRaises(VMwareApiError) as excinfo:
  4311. salt.utils.vmware.rename_datastore(self.mock_ds_ref, "fake_new_name")
  4312. self.assertEqual(excinfo.exception.strerror, "vim_fault")
  4313. def test_rename_datastore_raise_runtime_fault(self):
  4314. exc = vmodl.RuntimeFault()
  4315. exc.msg = "runtime_fault"
  4316. type(self.mock_ds_ref).RenameDatastore = MagicMock(side_effect=exc)
  4317. with self.assertRaises(VMwareRuntimeError) as excinfo:
  4318. salt.utils.vmware.rename_datastore(self.mock_ds_ref, "fake_new_name")
  4319. self.assertEqual(excinfo.exception.strerror, "runtime_fault")
  4320. def test_rename_datastore(self):
  4321. salt.utils.vmware.rename_datastore(self.mock_ds_ref, "fake_new_name")
  4322. self.mock_ds_ref.RenameDatastore.assert_called_once_with("fake_new_name")
  4323. class ConvertToKbTestCase(TestCase):
  4324. """
  4325. Tests for converting units
  4326. """
  4327. def setUp(self):
  4328. pass
  4329. def test_gb_conversion_call(self):
  4330. self.assertEqual(
  4331. salt.utils.vmware.convert_to_kb("Gb", 10),
  4332. {"size": int(10485760), "unit": "KB"},
  4333. )
  4334. def test_mb_conversion_call(self):
  4335. self.assertEqual(
  4336. salt.utils.vmware.convert_to_kb("Mb", 10),
  4337. {"size": int(10240), "unit": "KB"},
  4338. )
  4339. def test_kb_conversion_call(self):
  4340. self.assertEqual(
  4341. salt.utils.vmware.convert_to_kb("Kb", 10), {"size": int(10), "unit": "KB"}
  4342. )
  4343. def test_conversion_bad_input_argument_fault(self):
  4344. self.assertRaises(
  4345. ArgumentValueError, salt.utils.vmware.convert_to_kb, "test", 10
  4346. )
  4347. @skipIf(not HAS_PYVMOMI, "The 'pyvmomi' library is missing")
  4348. @patch("salt.utils.vmware.get_managed_object_name", MagicMock())
  4349. @patch("salt.utils.vmware.wait_for_task", MagicMock())
  4350. class CreateVirtualMachineTestCase(TestCase):
  4351. """
  4352. Tests for salt.utils.vmware.create_vm
  4353. """
  4354. def setUp(self):
  4355. self.vm_name = "fake_vm"
  4356. self.mock_task = MagicMock()
  4357. self.mock_config_spec = MagicMock()
  4358. self.mock_resourcepool_object = MagicMock()
  4359. self.mock_host_object = MagicMock()
  4360. self.mock_vm_create_task = MagicMock(return_value=self.mock_task)
  4361. self.mock_folder_object = MagicMock(CreateVM_Task=self.mock_vm_create_task)
  4362. def test_create_vm_pool_task_call(self):
  4363. salt.utils.vmware.create_vm(
  4364. self.vm_name,
  4365. self.mock_config_spec,
  4366. self.mock_folder_object,
  4367. self.mock_resourcepool_object,
  4368. )
  4369. self.assert_called_once(self.mock_vm_create_task)
  4370. def test_create_vm_host_task_call(self):
  4371. salt.utils.vmware.create_vm(
  4372. self.vm_name,
  4373. self.mock_config_spec,
  4374. self.mock_folder_object,
  4375. self.mock_resourcepool_object,
  4376. host_object=self.mock_host_object,
  4377. )
  4378. self.assert_called_once(self.mock_vm_create_task)
  4379. def test_create_vm_raise_no_permission(self):
  4380. exception = vim.fault.NoPermission()
  4381. exception.msg = "vim.fault.NoPermission msg"
  4382. self.mock_folder_object.CreateVM_Task = MagicMock(side_effect=exception)
  4383. with self.assertRaises(VMwareApiError) as exc:
  4384. salt.utils.vmware.create_vm(
  4385. self.vm_name,
  4386. self.mock_config_spec,
  4387. self.mock_folder_object,
  4388. self.mock_resourcepool_object,
  4389. )
  4390. self.assertEqual(
  4391. exc.exception.strerror, "Not enough permissions. Required privilege: "
  4392. )
  4393. def test_create_vm_raise_vim_fault(self):
  4394. exception = vim.fault.VimFault()
  4395. exception.msg = "vim.fault.VimFault msg"
  4396. self.mock_folder_object.CreateVM_Task = MagicMock(side_effect=exception)
  4397. with self.assertRaises(VMwareApiError) as exc:
  4398. salt.utils.vmware.create_vm(
  4399. self.vm_name,
  4400. self.mock_config_spec,
  4401. self.mock_folder_object,
  4402. self.mock_resourcepool_object,
  4403. )
  4404. self.assertEqual(exc.exception.strerror, "vim.fault.VimFault msg")
  4405. def test_create_vm_raise_runtime_fault(self):
  4406. exception = vmodl.RuntimeFault()
  4407. exception.msg = "vmodl.RuntimeFault msg"
  4408. self.mock_folder_object.CreateVM_Task = MagicMock(side_effect=exception)
  4409. with self.assertRaises(VMwareRuntimeError) as exc:
  4410. salt.utils.vmware.create_vm(
  4411. self.vm_name,
  4412. self.mock_config_spec,
  4413. self.mock_folder_object,
  4414. self.mock_resourcepool_object,
  4415. )
  4416. self.assertEqual(exc.exception.strerror, "vmodl.RuntimeFault msg")
  4417. def test_create_vm_wait_for_task(self):
  4418. mock_wait_for_task = MagicMock()
  4419. with patch("salt.utils.vmware.wait_for_task", mock_wait_for_task):
  4420. salt.utils.vmware.create_vm(
  4421. self.vm_name,
  4422. self.mock_config_spec,
  4423. self.mock_folder_object,
  4424. self.mock_resourcepool_object,
  4425. )
  4426. mock_wait_for_task.assert_called_once_with(
  4427. self.mock_task, self.vm_name, "CreateVM Task", 10, "info"
  4428. )
  4429. @skipIf(not HAS_PYVMOMI, "The 'pyvmomi' library is missing")
  4430. @patch("salt.utils.vmware.get_managed_object_name", MagicMock())
  4431. @patch("salt.utils.vmware.wait_for_task", MagicMock())
  4432. class RegisterVirtualMachineTestCase(TestCase):
  4433. """
  4434. Tests for salt.utils.vmware.register_vm
  4435. """
  4436. def setUp(self):
  4437. self.vm_name = "fake_vm"
  4438. self.mock_task = MagicMock()
  4439. self.mock_vmx_path = MagicMock()
  4440. self.mock_resourcepool_object = MagicMock()
  4441. self.mock_host_object = MagicMock()
  4442. self.mock_vm_register_task = MagicMock(return_value=self.mock_task)
  4443. self.vm_folder_object = MagicMock(RegisterVM_Task=self.mock_vm_register_task)
  4444. self.datacenter = MagicMock(vmFolder=self.vm_folder_object)
  4445. def test_register_vm_pool_task_call(self):
  4446. salt.utils.vmware.register_vm(
  4447. self.datacenter,
  4448. self.vm_name,
  4449. self.mock_vmx_path,
  4450. self.mock_resourcepool_object,
  4451. )
  4452. self.assert_called_once(self.mock_vm_register_task)
  4453. def test_register_vm_host_task_call(self):
  4454. salt.utils.vmware.register_vm(
  4455. self.datacenter,
  4456. self.vm_name,
  4457. self.mock_vmx_path,
  4458. self.mock_resourcepool_object,
  4459. host_object=self.mock_host_object,
  4460. )
  4461. self.assert_called_once(self.mock_vm_register_task)
  4462. def test_register_vm_raise_no_permission(self):
  4463. exception = vim.fault.NoPermission()
  4464. self.vm_folder_object.RegisterVM_Task = MagicMock(side_effect=exception)
  4465. with self.assertRaises(VMwareApiError) as exc:
  4466. salt.utils.vmware.register_vm(
  4467. self.datacenter,
  4468. self.vm_name,
  4469. self.mock_vmx_path,
  4470. self.mock_resourcepool_object,
  4471. )
  4472. self.assertEqual(
  4473. exc.exception.strerror, "Not enough permissions. Required privilege: "
  4474. )
  4475. def test_register_vm_raise_vim_fault(self):
  4476. exception = vim.fault.VimFault()
  4477. exception.msg = "vim.fault.VimFault msg"
  4478. self.vm_folder_object.RegisterVM_Task = MagicMock(side_effect=exception)
  4479. with self.assertRaises(VMwareApiError) as exc:
  4480. salt.utils.vmware.register_vm(
  4481. self.datacenter,
  4482. self.vm_name,
  4483. self.mock_vmx_path,
  4484. self.mock_resourcepool_object,
  4485. )
  4486. self.assertEqual(exc.exception.strerror, "vim.fault.VimFault msg")
  4487. def test_register_vm_raise_runtime_fault(self):
  4488. exception = vmodl.RuntimeFault()
  4489. exception.msg = "vmodl.RuntimeFault msg"
  4490. self.vm_folder_object.RegisterVM_Task = MagicMock(side_effect=exception)
  4491. with self.assertRaises(VMwareRuntimeError) as exc:
  4492. salt.utils.vmware.register_vm(
  4493. self.datacenter,
  4494. self.vm_name,
  4495. self.mock_vmx_path,
  4496. self.mock_resourcepool_object,
  4497. )
  4498. self.assertEqual(exc.exception.strerror, "vmodl.RuntimeFault msg")
  4499. def test_register_vm_wait_for_task(self):
  4500. mock_wait_for_task = MagicMock()
  4501. with patch("salt.utils.vmware.wait_for_task", mock_wait_for_task):
  4502. salt.utils.vmware.register_vm(
  4503. self.datacenter,
  4504. self.vm_name,
  4505. self.mock_vmx_path,
  4506. self.mock_resourcepool_object,
  4507. )
  4508. mock_wait_for_task.assert_called_once_with(
  4509. self.mock_task, self.vm_name, "RegisterVM Task"
  4510. )
  4511. @skipIf(not HAS_PYVMOMI, "The 'pyvmomi' library is missing")
  4512. @patch("salt.utils.vmware.get_managed_object_name", MagicMock())
  4513. @patch("salt.utils.vmware.wait_for_task", MagicMock())
  4514. class UpdateVirtualMachineTestCase(TestCase):
  4515. """
  4516. Tests for salt.utils.vmware.update_vm
  4517. """
  4518. def setUp(self):
  4519. self.mock_task = MagicMock()
  4520. self.mock_config_spec = MagicMock()
  4521. self.mock_vm_update_task = MagicMock(return_value=self.mock_task)
  4522. self.mock_vm_ref = MagicMock(ReconfigVM_Task=self.mock_vm_update_task)
  4523. def test_update_vm_task_call(self):
  4524. salt.utils.vmware.update_vm(self.mock_vm_ref, self.mock_config_spec)
  4525. self.assert_called_once(self.mock_vm_update_task)
  4526. def test_update_vm_raise_vim_fault(self):
  4527. exception = vim.fault.VimFault()
  4528. exception.msg = "vim.fault.VimFault"
  4529. self.mock_vm_ref.ReconfigVM_Task = MagicMock(side_effect=exception)
  4530. with self.assertRaises(VMwareApiError) as exc:
  4531. salt.utils.vmware.update_vm(self.mock_vm_ref, self.mock_config_spec)
  4532. self.assertEqual(exc.exception.strerror, "vim.fault.VimFault")
  4533. def test_update_vm_raise_runtime_fault(self):
  4534. exception = vmodl.RuntimeFault()
  4535. exception.msg = "vmodl.RuntimeFault"
  4536. self.mock_vm_ref.ReconfigVM_Task = MagicMock(side_effect=exception)
  4537. with self.assertRaises(VMwareRuntimeError) as exc:
  4538. salt.utils.vmware.update_vm(self.mock_vm_ref, self.mock_config_spec)
  4539. self.assertEqual(exc.exception.strerror, "vmodl.RuntimeFault")
  4540. def test_update_vm_wait_for_task(self):
  4541. mock_wait_for_task = MagicMock()
  4542. with patch(
  4543. "salt.utils.vmware.get_managed_object_name", MagicMock(return_value="my_vm")
  4544. ):
  4545. with patch("salt.utils.vmware.wait_for_task", mock_wait_for_task):
  4546. salt.utils.vmware.update_vm(self.mock_vm_ref, self.mock_config_spec)
  4547. mock_wait_for_task.assert_called_once_with(
  4548. self.mock_task, "my_vm", "ReconfigureVM Task"
  4549. )
  4550. @skipIf(not HAS_PYVMOMI, "The 'pyvmomi' library is missing")
  4551. @patch("salt.utils.vmware.get_managed_object_name", MagicMock())
  4552. @patch("salt.utils.vmware.wait_for_task", MagicMock())
  4553. class DeleteVirtualMachineTestCase(TestCase):
  4554. """
  4555. Tests for salt.utils.vmware.delete_vm
  4556. """
  4557. def setUp(self):
  4558. self.mock_task = MagicMock()
  4559. self.mock_vm_destroy_task = MagicMock(return_value=self.mock_task)
  4560. self.mock_vm_ref = MagicMock(Destroy_Task=self.mock_vm_destroy_task)
  4561. def test_destroy_vm_task_call(self):
  4562. salt.utils.vmware.delete_vm(self.mock_vm_ref)
  4563. self.assert_called_once(self.mock_vm_destroy_task)
  4564. def test_destroy_vm_raise_vim_fault(self):
  4565. exception = vim.fault.VimFault()
  4566. exception.msg = "vim.fault.VimFault"
  4567. self.mock_vm_ref.Destroy_Task = MagicMock(side_effect=exception)
  4568. with self.assertRaises(VMwareApiError) as exc:
  4569. salt.utils.vmware.delete_vm(self.mock_vm_ref)
  4570. self.assertEqual(exc.exception.strerror, "vim.fault.VimFault")
  4571. def test_destroy_vm_raise_runtime_fault(self):
  4572. exception = vmodl.RuntimeFault()
  4573. exception.msg = "vmodl.RuntimeFault"
  4574. self.mock_vm_ref.Destroy_Task = MagicMock(side_effect=exception)
  4575. with self.assertRaises(VMwareRuntimeError) as exc:
  4576. salt.utils.vmware.delete_vm(self.mock_vm_ref)
  4577. self.assertEqual(exc.exception.strerror, "vmodl.RuntimeFault")
  4578. def test_destroy_vm_wait_for_task(self):
  4579. mock_wait_for_task = MagicMock()
  4580. with patch(
  4581. "salt.utils.vmware.get_managed_object_name", MagicMock(return_value="my_vm")
  4582. ):
  4583. with patch("salt.utils.vmware.wait_for_task", mock_wait_for_task):
  4584. salt.utils.vmware.delete_vm(self.mock_vm_ref)
  4585. mock_wait_for_task.assert_called_once_with(
  4586. self.mock_task, "my_vm", "Destroy Task"
  4587. )
  4588. @skipIf(not HAS_PYVMOMI, "The 'pyvmomi' library is missing")
  4589. @patch("salt.utils.vmware.get_managed_object_name", MagicMock())
  4590. class UnregisterVirtualMachineTestCase(TestCase):
  4591. """
  4592. Tests for salt.utils.vmware.unregister_vm
  4593. """
  4594. def setUp(self):
  4595. self.mock_vm_unregister = MagicMock()
  4596. self.mock_vm_ref = MagicMock(UnregisterVM=self.mock_vm_unregister)
  4597. def test_unregister_vm_task_call(self):
  4598. salt.utils.vmware.unregister_vm(self.mock_vm_ref)
  4599. self.assert_called_once(self.mock_vm_unregister)
  4600. def test_unregister_vm_raise_vim_fault(self):
  4601. exception = vim.fault.VimFault()
  4602. exception.msg = "vim.fault.VimFault"
  4603. self.mock_vm_ref.UnregisterVM = MagicMock(side_effect=exception)
  4604. with self.assertRaises(VMwareApiError) as exc:
  4605. salt.utils.vmware.unregister_vm(self.mock_vm_ref)
  4606. self.assertEqual(exc.exception.strerror, "vim.fault.VimFault")
  4607. def test_unregister_vm_raise_runtime_fault(self):
  4608. exception = vmodl.RuntimeFault()
  4609. exception.msg = "vmodl.RuntimeFault"
  4610. self.mock_vm_ref.UnregisterVM = MagicMock(side_effect=exception)
  4611. with self.assertRaises(VMwareRuntimeError) as exc:
  4612. salt.utils.vmware.unregister_vm(self.mock_vm_ref)
  4613. self.assertEqual(exc.exception.strerror, "vmodl.RuntimeFault")