test_models.py 213 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162
  1. import os
  2. import tempfile
  3. import uuid
  4. from decimal import Decimal
  5. from unittest.mock import patch
  6. from django.core.exceptions import ValidationError
  7. from django.db import IntegrityError, connection, transaction
  8. from django.db.models import ProtectedError
  9. from django.db.models.signals import post_save
  10. from django.test import RequestFactory, TestCase, override_settings, tag
  11. from django.test.utils import CaptureQueriesContext
  12. from django.utils.text import slugify
  13. from netaddr import EUI
  14. from circuits.models import *
  15. from core.choices import ObjectChangeActionChoices
  16. from core.models import ObjectChange, ObjectType
  17. from dcim.choices import *
  18. from dcim.models import *
  19. from dcim.utils import resolve_module_placeholder
  20. from extras.events import serialize_for_event
  21. from extras.models import CustomField
  22. from ipam.models import IPAddress, Prefix
  23. from netbox.choices import DiameterUnitChoices, FlowRateUnitChoices, WeightUnitChoices
  24. from netbox.context_managers import event_tracking
  25. from tenancy.models import Tenant
  26. from users.models import User
  27. from utilities.data import drange
  28. from utilities.exceptions import AbortRequest
  29. from utilities.testing import create_test_device, create_test_image
  30. from virtualization.models import Cluster, ClusterType
  31. class MACAddressTestCase(TestCase):
  32. @classmethod
  33. def setUpTestData(cls):
  34. site = Site.objects.create(name='Test Site 1', slug='test-site-1')
  35. manufacturer = Manufacturer.objects.create(name='Test Manufacturer 1', slug='test-manufacturer-1')
  36. device_type = DeviceType.objects.create(
  37. manufacturer=manufacturer, model='Test Device Type 1', slug='test-device-type-1'
  38. )
  39. device_role = DeviceRole.objects.create(name='Test Role 1', slug='test-role-1')
  40. device = Device.objects.create(
  41. name='Device 1', device_type=device_type, role=device_role, site=site,
  42. )
  43. cls.interface = Interface.objects.create(
  44. device=device,
  45. name='Interface 1',
  46. type=InterfaceTypeChoices.TYPE_1GE_FIXED,
  47. mgmt_only=True
  48. )
  49. cls.mac_a = MACAddress.objects.create(mac_address='1234567890ab', assigned_object=cls.interface)
  50. cls.mac_b = MACAddress.objects.create(mac_address='1234567890ba', assigned_object=cls.interface)
  51. cls.interface.primary_mac_address = cls.mac_a
  52. cls.interface.save()
  53. @tag('regression')
  54. def test_clean_will_not_allow_removal_of_assigned_object_if_primary(self):
  55. self.mac_a.assigned_object = None
  56. with self.assertRaisesMessage(ValidationError, 'Cannot unassign MAC Address while'):
  57. self.mac_a.clean()
  58. @tag('regression')
  59. def test_clean_will_allow_removal_of_assigned_object_if_not_primary(self):
  60. self.mac_b.assigned_object = None
  61. self.mac_b.clean()
  62. def test_set_primary_mac_address_assigns(self):
  63. self.interface.set_primary_mac_address(self.mac_b)
  64. self.interface.refresh_from_db()
  65. self.assertEqual(self.interface.primary_mac_address_id, self.mac_b.pk)
  66. def test_set_primary_mac_address_clears(self):
  67. self.interface.set_primary_mac_address(None)
  68. self.interface.refresh_from_db()
  69. self.assertIsNone(self.interface.primary_mac_address_id)
  70. def test_set_primary_mac_address_noop_when_already_primary(self):
  71. # mac_a is already primary; re-setting it changes nothing and doesn't error.
  72. self.interface.set_primary_mac_address(self.mac_a)
  73. self.interface.refresh_from_db()
  74. self.assertEqual(self.interface.primary_mac_address_id, self.mac_a.pk)
  75. def test_set_primary_mac_address_from_value_finds_existing(self):
  76. # A value already present on the interface is promoted, not duplicated.
  77. count_before = self.interface.mac_addresses.count()
  78. self.interface.set_primary_mac_address_from_value(str(self.mac_b.mac_address))
  79. self.interface.refresh_from_db()
  80. self.assertEqual(self.interface.primary_mac_address_id, self.mac_b.pk)
  81. self.assertEqual(self.interface.mac_addresses.count(), count_before)
  82. def test_set_primary_mac_address_from_value_creates(self):
  83. count_before = self.interface.mac_addresses.count()
  84. self.interface.set_primary_mac_address_from_value('aabbccddeeff')
  85. self.interface.refresh_from_db()
  86. self.assertEqual(self.interface.mac_addresses.count(), count_before + 1)
  87. self.assertEqual(str(self.interface.primary_mac_address.mac_address).lower(), 'aa:bb:cc:dd:ee:ff')
  88. def test_set_primary_mac_address_rejects_foreign_mac(self):
  89. # A MAC assigned to a different interface can't be made primary here.
  90. other = Interface.objects.create(
  91. device=self.interface.device,
  92. name='Interface 2',
  93. type=InterfaceTypeChoices.TYPE_1GE_FIXED,
  94. )
  95. foreign_mac = MACAddress.objects.create(mac_address='ffeeddccbbaa', assigned_object=other)
  96. with self.assertRaises(ValidationError):
  97. self.interface.set_primary_mac_address(foreign_mac)
  98. def test_clean_rejects_unassigned_primary_mac_on_update(self):
  99. # An existing interface can't point its primary at a MAC that isn't assigned to it.
  100. unassigned = MACAddress.objects.create(mac_address='aabbccdd0099')
  101. self.interface.primary_mac_address = unassigned
  102. with self.assertRaises(ValidationError):
  103. self.interface.full_clean()
  104. def test_clean_allows_unassigned_primary_mac_on_create(self):
  105. # On create the MAC is assigned by a post_save signal after clean(), so an as-yet-unassigned
  106. # primary MAC must pass validation on a new (adding) instance.
  107. mac = MACAddress.objects.create(mac_address='aabbccdd00aa')
  108. new_iface = Interface(
  109. device=self.interface.device,
  110. name='Interface Create Heal',
  111. type=InterfaceTypeChoices.TYPE_1GE_FIXED,
  112. primary_mac_address=mac,
  113. )
  114. new_iface.full_clean() # must not raise
  115. class MACBlockTestCase(TestCase):
  116. def test_prefix_normalized(self):
  117. mac_block = MACBlock.objects.create(prefix='BC:24:11:12:34:56', prefix_length=24)
  118. mac_block.refresh_from_db()
  119. self.assertEqual(str(mac_block.prefix), 'BC:24:11:00:00:00')
  120. self.assertEqual(str(mac_block.last_address), 'BC:24:11:FF:FF:FF')
  121. self.assertEqual(str(mac_block._last_address), 'BC:24:11:FF:FF:FF')
  122. self.assertEqual(str(mac_block), 'BC:24:11:00:00:00/24')
  123. def test_invalid_prefix(self):
  124. for prefix, prefix_length in (('invalid', 24), ('BC:24:11:00:00:00', 49), ('BC:24:11:00:00:00', 'x')):
  125. mac_block = MACBlock(prefix=prefix, prefix_length=prefix_length, enforce_unique=True)
  126. self.assertIsNone(mac_block.first_address)
  127. with self.assertRaises(ValidationError):
  128. mac_block.full_clean()
  129. def test_duplicate_prefix_with_host_bits(self):
  130. MACBlock.objects.create(prefix='BC:24:11:00:00:00', prefix_length=24)
  131. mac_block = MACBlock(prefix='BC:24:11:AA:BB:CC', prefix_length=24)
  132. with self.assertRaises(ValidationError):
  133. mac_block.full_clean()
  134. def test_save_invalid_prefix(self):
  135. with self.assertRaisesMessage(ValueError, 'Invalid MAC address block'):
  136. MACBlock.objects.create(prefix='BC:24:11:00:00:00', prefix_length=0)
  137. def test_size(self):
  138. self.assertEqual(MACBlock(prefix='BC:24:11:00:00:00', prefix_length=24).size, 2 ** 24)
  139. self.assertEqual(MACBlock(prefix='BC:24:11:50:00:00', prefix_length=28).size, 2 ** 20)
  140. self.assertEqual(MACBlock(prefix='BC:24:11:00:00:01', prefix_length=48).size, 1)
  141. def test_duplicate_prefix(self):
  142. MACBlock.objects.create(prefix='BC:24:11:00:00:00', prefix_length=24)
  143. mac_block = MACBlock(prefix='BC:24:11:00:00:00', prefix_length=24)
  144. with self.assertRaises(ValidationError):
  145. mac_block.full_clean()
  146. # A block of a different length may share the same first address
  147. MACBlock(prefix='BC:24:11:00:00:00', prefix_length=28).full_clean()
  148. def test_get_mac_addresses(self):
  149. mac_block = MACBlock.objects.create(prefix='BC:24:11:50:00:00', prefix_length=28)
  150. MACAddress.objects.bulk_create((
  151. MACAddress(mac_address='BC:24:11:4F:FF:FF'),
  152. MACAddress(mac_address='BC:24:11:50:00:00'),
  153. MACAddress(mac_address='BC:24:11:5F:FF:FF'),
  154. MACAddress(mac_address='BC:24:11:60:00:00'),
  155. ))
  156. self.assertEqual(
  157. sorted(str(mac.mac_address) for mac in mac_block.get_mac_addresses()),
  158. ['BC:24:11:50:00:00', 'BC:24:11:5F:FF:FF']
  159. )
  160. def test_get_child_blocks(self):
  161. mac_blocks = (
  162. MACBlock.objects.create(prefix='BC:24:11:00:00:00', prefix_length=24),
  163. MACBlock.objects.create(prefix='BC:24:11:00:00:00', prefix_length=28),
  164. MACBlock.objects.create(prefix='BC:24:11:F0:00:00', prefix_length=28),
  165. MACBlock.objects.create(prefix='BC:24:12:00:00:00', prefix_length=28),
  166. )
  167. self.assertEqual(list(mac_blocks[0].get_child_blocks()), [mac_blocks[1], mac_blocks[2]])
  168. self.assertEqual(list(mac_blocks[1].get_child_blocks()), [])
  169. def test_mac_address_mac_block(self):
  170. mac_blocks = (
  171. MACBlock.objects.create(prefix='BC:24:11:00:00:00', prefix_length=24),
  172. MACBlock.objects.create(prefix='BC:24:11:50:00:00', prefix_length=28),
  173. )
  174. self.assertEqual(MACAddress(mac_address='BC:24:11:51:00:00').mac_block, mac_blocks[1])
  175. self.assertEqual(MACAddress(mac_address='BC:24:11:61:00:00').mac_block, mac_blocks[0])
  176. self.assertIsNone(MACAddress(mac_address='BC:24:12:00:00:00').mac_block)
  177. def test_available_mac_addresses(self):
  178. mac_block = MACBlock.objects.create(prefix='BC:24:11:00:00:00', prefix_length=45)
  179. self.assertEqual(str(mac_block.get_first_available_mac_address()), 'BC:24:11:00:00:00')
  180. MACAddress.objects.bulk_create((
  181. MACAddress(mac_address='BC:24:11:00:00:00'),
  182. MACAddress(mac_address='BC:24:11:00:00:01'),
  183. MACAddress(mac_address='BC:24:11:00:00:01'), # Duplicate
  184. MACAddress(mac_address='BC:24:11:00:00:03'),
  185. MACAddress(mac_address='BC:24:11:00:00:07'),
  186. MACAddress(mac_address='BC:24:11:00:00:08'), # Outside the block
  187. ))
  188. self.assertEqual(str(mac_block.get_first_available_mac_address()), 'BC:24:11:00:00:02')
  189. self.assertEqual(
  190. [str(mac) for mac in mac_block.iter_available_mac_addresses()],
  191. ['BC:24:11:00:00:02', 'BC:24:11:00:00:04', 'BC:24:11:00:00:05', 'BC:24:11:00:00:06']
  192. )
  193. # Fetching occupied addresses in batches finds the same gaps
  194. self.assertEqual(
  195. list(mac_block._iter_occupied(batch_size=2)),
  196. [int(EUI(mac)) for mac in ('BC:24:11:00:00:00', 'BC:24:11:00:00:01', 'BC:24:11:00:00:03',
  197. 'BC:24:11:00:00:07')]
  198. )
  199. def test_no_available_mac_addresses(self):
  200. mac_block = MACBlock.objects.create(prefix='BC:24:11:00:00:00', prefix_length=47)
  201. MACAddress.objects.bulk_create((
  202. MACAddress(mac_address='BC:24:11:00:00:00'),
  203. MACAddress(mac_address='BC:24:11:00:00:01'),
  204. ))
  205. self.assertIsNone(mac_block.get_first_available_mac_address())
  206. self.assertEqual(mac_block.utilization, 100)
  207. def test_utilization(self):
  208. mac_block = MACBlock.objects.create(prefix='BC:24:11:00:00:00', prefix_length=46)
  209. MACAddress.objects.bulk_create((
  210. MACAddress(mac_address='BC:24:11:00:00:00'),
  211. MACAddress(mac_address='BC:24:11:00:00:00'), # Duplicate
  212. MACAddress(mac_address='BC:24:11:00:00:02'),
  213. ))
  214. self.assertEqual(mac_block.utilization, 50)
  215. annotated = MACBlock.objects.annotate_mac_address_count().get(pk=mac_block.pk)
  216. self.assertEqual(annotated.mac_address_count, 2)
  217. self.assertEqual(annotated.utilization, 50)
  218. def test_enforce_unique(self):
  219. MACBlock.objects.create(prefix='BC:24:11:00:00:00', prefix_length=24, enforce_unique=True)
  220. MACAddress.objects.create(mac_address='BC:24:11:00:00:01')
  221. MACAddress.objects.create(mac_address='BC:24:12:00:00:01')
  222. # A duplicate within the block is rejected
  223. with self.assertRaisesMessage(ValidationError, 'BC:24:11:00:00:00/24'):
  224. MACAddress(mac_address='BC:24:11:00:00:01').full_clean()
  225. # A duplicate Outside the block is permitted
  226. MACAddress(mac_address='BC:24:12:00:00:01').full_clean()
  227. # Saving an existing MAC address does not count it as its own duplicate
  228. MACAddress.objects.get(mac_address='BC:24:11:00:00:01').full_clean()
  229. def test_enforce_unique_with_duplicates(self):
  230. MACAddress.objects.bulk_create((
  231. MACAddress(mac_address='BC:24:11:00:00:01'),
  232. MACAddress(mac_address='BC:24:11:00:00:01'),
  233. ))
  234. mac_block = MACBlock(prefix='BC:24:11:00:00:00', prefix_length=24, enforce_unique=True)
  235. with self.assertRaisesMessage(ValidationError, 'BC:24:11:00:00:01'):
  236. mac_block.full_clean()
  237. # Uniqueness is not enforced by default
  238. mac_block.enforce_unique = False
  239. mac_block.full_clean()
  240. class LocationTestCase(TestCase):
  241. def test_change_location_site(self):
  242. """
  243. Check that all child Locations and Racks get updated when a Location is moved to a new Site. Topology:
  244. Site A
  245. - Location A1
  246. - Location A2
  247. - Rack 2
  248. - Device 2
  249. - Rack 1
  250. - Device 1
  251. """
  252. manufacturer = Manufacturer.objects.create(name='Manufacturer 1', slug='manufacturer-1')
  253. device_type = DeviceType.objects.create(
  254. manufacturer=manufacturer, model='Device Type 1', slug='device-type-1'
  255. )
  256. role = DeviceRole.objects.create(
  257. name='Device Role 1', slug='device-role-1', color='ff0000'
  258. )
  259. site_a = Site.objects.create(name='Site A', slug='site-a')
  260. site_b = Site.objects.create(name='Site B', slug='site-b')
  261. location_a1 = Location(site=site_a, name='Location A1', slug='location-a1')
  262. location_a1.save()
  263. location_a2 = Location(site=site_a, parent=location_a1, name='Location A2', slug='location-a2')
  264. location_a2.save()
  265. rack1 = Rack.objects.create(site=site_a, location=location_a1, name='Rack 1')
  266. rack2 = Rack.objects.create(site=site_a, location=location_a2, name='Rack 2')
  267. device1 = Device.objects.create(
  268. site=site_a,
  269. location=location_a1,
  270. name='Device 1',
  271. device_type=device_type,
  272. role=role
  273. )
  274. device2 = Device.objects.create(
  275. site=site_a,
  276. location=location_a2,
  277. name='Device 2',
  278. device_type=device_type,
  279. role=role
  280. )
  281. powerpanel1 = PowerPanel.objects.create(site=site_a, location=location_a1, name='Power Panel 1')
  282. # Move Location A1 to Site B
  283. location_a1.site = site_b
  284. location_a1.save()
  285. # Check that all objects within Location A1 now belong to Site B
  286. self.assertEqual(Location.objects.get(pk=location_a1.pk).site, site_b)
  287. self.assertEqual(Location.objects.get(pk=location_a2.pk).site, site_b)
  288. self.assertEqual(Rack.objects.get(pk=rack1.pk).site, site_b)
  289. self.assertEqual(Rack.objects.get(pk=rack2.pk).site, site_b)
  290. self.assertEqual(Device.objects.get(pk=device1.pk).site, site_b)
  291. self.assertEqual(Device.objects.get(pk=device2.pk).site, site_b)
  292. self.assertEqual(PowerPanel.objects.get(pk=powerpanel1.pk).site, site_b)
  293. class DeviceTypeTestCase(TestCase):
  294. def test_component_template_counts(self):
  295. """
  296. DeviceType component template counters should track the addition and removal of templates.
  297. """
  298. manufacturer = Manufacturer.objects.create(name='Manufacturer 1', slug='manufacturer-1')
  299. device_type = DeviceType.objects.create(
  300. manufacturer=manufacturer, model='Device Type 1', slug='device-type-1'
  301. )
  302. # Counters should start at zero
  303. self.assertEqual(device_type.interface_template_count, 0)
  304. self.assertEqual(device_type.console_port_template_count, 0)
  305. self.assertEqual(device_type.module_bay_template_count, 0)
  306. self.assertEqual(device_type.device_bay_template_count, 0)
  307. # Adding templates should increment the relevant counters
  308. InterfaceTemplate.objects.create(device_type=device_type, name='Interface 1')
  309. InterfaceTemplate.objects.create(device_type=device_type, name='Interface 2')
  310. ConsolePortTemplate.objects.create(device_type=device_type, name='Console 1')
  311. ModuleBayTemplate.objects.create(device_type=device_type, name='Module Bay 1')
  312. DeviceBayTemplate.objects.create(device_type=device_type, name='Device Bay 1')
  313. device_type.refresh_from_db()
  314. self.assertEqual(device_type.interface_template_count, 2)
  315. self.assertEqual(device_type.console_port_template_count, 1)
  316. self.assertEqual(device_type.module_bay_template_count, 1)
  317. self.assertEqual(device_type.device_bay_template_count, 1)
  318. # Deleting a template should decrement the counter
  319. InterfaceTemplate.objects.get(device_type=device_type, name='Interface 1').delete()
  320. device_type.refresh_from_db()
  321. self.assertEqual(device_type.interface_template_count, 1)
  322. class DeviceTypeImageTestCase(TestCase):
  323. """
  324. Test the handling of DeviceType front/rear image files.
  325. """
  326. def setUp(self):
  327. media_root = self.enterContext(tempfile.TemporaryDirectory())
  328. self.enterContext(override_settings(MEDIA_ROOT=media_root))
  329. self.manufacturer = Manufacturer.objects.create(name='Manufacturer 1', slug='manufacturer-1')
  330. def _create_device_type(self, model='Device Type 1', **images):
  331. """
  332. Create a DeviceType with an uploaded image for each image field mapped to a filename.
  333. """
  334. return DeviceType.objects.create(
  335. manufacturer=self.manufacturer,
  336. model=model,
  337. slug=slugify(model),
  338. **{field_name: create_test_image(filename) for field_name, filename in images.items()},
  339. )
  340. def _save(self, device_type, **kwargs):
  341. # Execute the on-commit deletion of replaced image files, which TestCase otherwise discards
  342. with self.captureOnCommitCallbacks(execute=True):
  343. device_type.save(**kwargs)
  344. def test_create_with_images(self):
  345. device_type = self._create_device_type(front_image='front.png', rear_image='rear.png')
  346. self.assertTrue(os.path.exists(device_type.front_image.path))
  347. self.assertTrue(os.path.exists(device_type.rear_image.path))
  348. def test_replace_and_clear_images(self):
  349. device_type = self._create_device_type(front_image='front1.png', rear_image='rear.png')
  350. front_image_path = device_type.front_image.path
  351. rear_image_path = device_type.rear_image.path
  352. # Replacing an image should delete the original file
  353. device_type = DeviceType.objects.get(pk=device_type.pk)
  354. device_type.front_image = create_test_image('front2.png')
  355. self._save(device_type)
  356. self.assertFalse(os.path.exists(front_image_path))
  357. self.assertTrue(os.path.exists(device_type.front_image.path))
  358. # Clearing an image should delete its file
  359. device_type.rear_image = None
  360. self._save(device_type)
  361. self.assertFalse(os.path.exists(rear_image_path))
  362. def test_replace_image_on_same_instance(self):
  363. """
  364. Replacing an image repeatedly on the instance it was created with should delete each prior file.
  365. """
  366. device_type = self._create_device_type(front_image='front1.png')
  367. first_image_path = device_type.front_image.path
  368. device_type.front_image = create_test_image('front2.png')
  369. self._save(device_type)
  370. second_image_path = device_type.front_image.path
  371. self.assertFalse(os.path.exists(first_image_path))
  372. self.assertTrue(os.path.exists(second_image_path))
  373. device_type.front_image = create_test_image('front3.png')
  374. self._save(device_type)
  375. self.assertFalse(os.path.exists(second_image_path))
  376. self.assertTrue(os.path.exists(device_type.front_image.path))
  377. def test_replace_initial_image_path_before_first_save(self):
  378. """
  379. Replacing an image path assigned to a new DeviceType before its first save should not delete that file, which
  380. here belongs to another DeviceType.
  381. """
  382. device_type1 = self._create_device_type(front_image='front1.png')
  383. shared_image_path = device_type1.front_image.path
  384. device_type2 = DeviceType(
  385. manufacturer=self.manufacturer,
  386. model='Device Type 2',
  387. slug='device-type-2',
  388. front_image=device_type1.front_image.name,
  389. )
  390. device_type2.front_image = create_test_image('front2.png')
  391. self._save(device_type2)
  392. self.assertTrue(os.path.exists(shared_image_path))
  393. self.assertTrue(os.path.exists(device_type2.front_image.path))
  394. def test_update_fields_omitting_image(self):
  395. """
  396. Saving with update_fields which omits an image field should not delete its stored file, which a later full
  397. save then replaces.
  398. """
  399. device_type = self._create_device_type(front_image='front1.png')
  400. original_image_path = device_type.front_image.path
  401. device_type = DeviceType.objects.get(pk=device_type.pk)
  402. device_type.front_image = create_test_image('front2.png')
  403. device_type.description = 'New description'
  404. self._save(device_type, update_fields=['description'])
  405. self.assertTrue(os.path.exists(original_image_path))
  406. device_type.refresh_from_db(fields=['front_image'])
  407. self.assertEqual(device_type.front_image.path, original_image_path)
  408. device_type.front_image = create_test_image('front2.png')
  409. self._save(device_type)
  410. self.assertFalse(os.path.exists(original_image_path))
  411. self.assertTrue(os.path.exists(device_type.front_image.path))
  412. def test_update_fields_iterator(self):
  413. """
  414. Replacing an image via a save with iterator-valued update_fields should delete the original file.
  415. """
  416. device_type = self._create_device_type(front_image='front1.png')
  417. original_image_path = device_type.front_image.path
  418. device_type = DeviceType.objects.get(pk=device_type.pk)
  419. device_type.front_image = create_test_image('front2.png')
  420. self._save(device_type, update_fields=iter(['front_image']))
  421. self.assertFalse(os.path.exists(original_image_path))
  422. self.assertTrue(os.path.exists(device_type.front_image.path))
  423. def test_deferred_images(self):
  424. """
  425. Saving a DeviceType with deferred image fields should neither load them nor delete their stored files.
  426. """
  427. device_type = self._create_device_type(front_image='front.png', rear_image='rear.png')
  428. front_image_path = device_type.front_image.path
  429. rear_image_path = device_type.rear_image.path
  430. device_type = DeviceType.objects.defer('front_image', 'rear_image').get(pk=device_type.pk)
  431. device_type.description = 'New description'
  432. self._save(device_type)
  433. self.assertTrue({'front_image', 'rear_image'}.issubset(device_type.get_deferred_fields()))
  434. self.assertTrue(os.path.exists(front_image_path))
  435. self.assertTrue(os.path.exists(rear_image_path))
  436. def test_replace_deferred_image(self):
  437. """
  438. Replacing an image which was deferred when the DeviceType was loaded should delete the original file.
  439. """
  440. device_type = self._create_device_type(front_image='front1.png')
  441. original_image_path = device_type.front_image.path
  442. device_type = DeviceType.objects.defer('front_image').get(pk=device_type.pk)
  443. device_type.front_image = create_test_image('front2.png')
  444. self._save(device_type)
  445. self.assertFalse(os.path.exists(original_image_path))
  446. self.assertTrue(os.path.exists(device_type.front_image.path))
  447. def test_replace_image_on_stale_instance(self):
  448. """
  449. Replacing an image on an instance loaded before another change to that image should delete the file currently
  450. stored, not the one originally loaded.
  451. """
  452. device_type = self._create_device_type(front_image='front1.png')
  453. stale_instance = DeviceType.objects.get(pk=device_type.pk)
  454. device_type.front_image = create_test_image('front2.png')
  455. self._save(device_type)
  456. second_image_path = device_type.front_image.path
  457. stale_instance.front_image = create_test_image('front3.png')
  458. self._save(stale_instance)
  459. self.assertFalse(os.path.exists(second_image_path))
  460. self.assertTrue(os.path.exists(stale_instance.front_image.path))
  461. def test_replace_image_rolled_back(self):
  462. """
  463. Replacing an image within a transaction which is rolled back should not delete the original file.
  464. """
  465. device_type = self._create_device_type(front_image='front1.png')
  466. original_image_path = device_type.front_image.path
  467. device_type.front_image = create_test_image('front2.png')
  468. with self.captureOnCommitCallbacks(execute=True), self.assertRaises(RuntimeError):
  469. with transaction.atomic():
  470. device_type.save()
  471. raise RuntimeError('Roll back the transaction')
  472. self.assertTrue(os.path.exists(original_image_path))
  473. device_type.refresh_from_db()
  474. self.assertEqual(device_type.front_image.path, original_image_path)
  475. def test_replace_image_storage_error(self):
  476. """
  477. A failure to delete a replaced image file should be logged rather than raised, as the change itself has
  478. already been committed.
  479. """
  480. device_type = self._create_device_type(front_image='front1.png')
  481. original_image_name = device_type.front_image.name
  482. # A non-robust on-commit callback would re-raise the OSError here
  483. device_type.front_image = create_test_image('front2.png')
  484. with patch(
  485. 'dcim.models.devices.default_storage.delete', side_effect=OSError('Storage unavailable')
  486. ) as mock_delete:
  487. self._save(device_type)
  488. mock_delete.assert_called_once_with(original_image_name)
  489. device_type.refresh_from_db()
  490. self.assertTrue(os.path.exists(device_type.front_image.path))
  491. self.assertTrue(device_type.front_image.name.endswith('front2.png'))
  492. class ModuleTypeTestCase(TestCase):
  493. def test_component_template_counts(self):
  494. """
  495. ModuleType component template counters should track the addition and removal of templates.
  496. """
  497. manufacturer = Manufacturer.objects.create(name='Manufacturer 1', slug='manufacturer-1')
  498. module_type = ModuleType.objects.create(manufacturer=manufacturer, model='Module Type 1')
  499. # Counters should start at zero
  500. self.assertEqual(module_type.interface_template_count, 0)
  501. self.assertEqual(module_type.console_port_template_count, 0)
  502. self.assertEqual(module_type.module_bay_template_count, 0)
  503. # Adding templates should increment the relevant counters
  504. InterfaceTemplate.objects.create(module_type=module_type, name='Interface 1')
  505. InterfaceTemplate.objects.create(module_type=module_type, name='Interface 2')
  506. ConsolePortTemplate.objects.create(module_type=module_type, name='Console 1')
  507. ModuleBayTemplate.objects.create(module_type=module_type, name='Module Bay 1')
  508. module_type.refresh_from_db()
  509. self.assertEqual(module_type.interface_template_count, 2)
  510. self.assertEqual(module_type.console_port_template_count, 1)
  511. self.assertEqual(module_type.module_bay_template_count, 1)
  512. # Deleting a template should decrement the counter
  513. InterfaceTemplate.objects.get(module_type=module_type, name='Interface 1').delete()
  514. module_type.refresh_from_db()
  515. self.assertEqual(module_type.interface_template_count, 1)
  516. def test_module_bay_template_to_yaml_includes_module_bay_types(self):
  517. """
  518. ModuleBayTemplate.to_yaml() should export its assigned module bay types by name.
  519. """
  520. manufacturer = Manufacturer.objects.create(name='Manufacturer 1', slug='manufacturer-1')
  521. module_type = ModuleType.objects.create(manufacturer=manufacturer, model='Module Type 1')
  522. bay_type = ModuleBayType.objects.create(name='SFP28', slug='sfp28')
  523. module_bay_template = ModuleBayTemplate.objects.create(module_type=module_type, name='Module Bay 1')
  524. module_bay_template.module_bay_types.set([bay_type])
  525. data = module_bay_template.to_yaml()
  526. self.assertEqual(data['module_bay_types'], ['SFP28'])
  527. def test_module_bay_template_to_yaml_orders_module_bay_types(self):
  528. """
  529. Multiple module bay types should export in ModuleBayType's own ordering
  530. (manufacturer, name), independent of assignment order.
  531. """
  532. manufacturer = Manufacturer.objects.create(name='Manufacturer 1', slug='manufacturer-1')
  533. module_type = ModuleType.objects.create(manufacturer=manufacturer, model='Module Type 1')
  534. bay_type_b = ModuleBayType.objects.create(name='QSFP28', slug='qsfp28')
  535. bay_type_a = ModuleBayType.objects.create(name='SFP28', slug='sfp28')
  536. module_bay_template = ModuleBayTemplate.objects.create(module_type=module_type, name='Module Bay 1')
  537. module_bay_template.module_bay_types.set([bay_type_b, bay_type_a])
  538. data = module_bay_template.to_yaml()
  539. self.assertEqual(data['module_bay_types'], ['QSFP28', 'SFP28'])
  540. def test_attributes(self):
  541. """
  542. ModuleType.attributes should normalize iterable values into strings for presentation.
  543. """
  544. manufacturer = Manufacturer.objects.create(name='Manufacturer 1', slug='manufacturer-1')
  545. profile = ModuleTypeProfile.objects.create(
  546. name='Module Type Profile 1',
  547. schema={
  548. 'properties': {
  549. 'media': {
  550. 'title': 'Media',
  551. 'type': 'array',
  552. 'items': {'type': 'string'},
  553. },
  554. 'enabled': {
  555. 'title': 'Enabled',
  556. 'type': 'boolean',
  557. },
  558. },
  559. },
  560. )
  561. module_type = ModuleType.objects.create(
  562. manufacturer=manufacturer,
  563. model='Module Type 1',
  564. profile=profile,
  565. attribute_data={
  566. 'media': ['sfp', 'qsfp28'],
  567. 'enabled': True,
  568. },
  569. )
  570. self.assertEqual(
  571. module_type.attributes,
  572. {
  573. 'Enabled': True,
  574. 'Media': 'sfp, qsfp28',
  575. },
  576. )
  577. class RackTypeTestCase(TestCase):
  578. @classmethod
  579. def setUpTestData(cls):
  580. manufacturer = Manufacturer.objects.create(name='Manufacturer 1', slug='manufacturer-1')
  581. RackType.objects.create(
  582. manufacturer=manufacturer,
  583. model='RackType 1',
  584. slug='rack-type-1',
  585. width=11,
  586. u_height=22,
  587. starting_unit=3,
  588. desc_units=True,
  589. outer_width=444,
  590. outer_depth=5,
  591. outer_unit=RackDimensionUnitChoices.UNIT_MILLIMETER,
  592. weight=66,
  593. weight_unit=WeightUnitChoices.UNIT_POUND,
  594. max_weight=7777,
  595. mounting_depth=8,
  596. cooling_capability=RackCoolingCapabilityChoices.CAPABILITY_LIQUID_ONLY,
  597. cooling_capacity=80,
  598. )
  599. def test_rack_creation(self):
  600. rack_type = RackType.objects.first()
  601. sites = (
  602. Site(name='Site 1', slug='site-1'),
  603. )
  604. Site.objects.bulk_create(sites)
  605. locations = (
  606. Location(name='Location 1', slug='location-1', site=sites[0]),
  607. )
  608. for location in locations:
  609. location.save()
  610. rack = Rack.objects.create(
  611. name='Rack 1',
  612. facility_id='A101',
  613. site=sites[0],
  614. location=locations[0],
  615. rack_type=rack_type,
  616. )
  617. self.assertEqual(rack.width, rack_type.width)
  618. self.assertEqual(rack.u_height, rack_type.u_height)
  619. self.assertEqual(rack.starting_unit, rack_type.starting_unit)
  620. self.assertEqual(rack.desc_units, rack_type.desc_units)
  621. self.assertEqual(rack.outer_width, rack_type.outer_width)
  622. self.assertEqual(rack.outer_depth, rack_type.outer_depth)
  623. self.assertEqual(rack.outer_unit, rack_type.outer_unit)
  624. self.assertEqual(rack.weight, rack_type.weight)
  625. self.assertEqual(rack.weight_unit, rack_type.weight_unit)
  626. self.assertEqual(rack.max_weight, rack_type.max_weight)
  627. self.assertEqual(rack.mounting_depth, rack_type.mounting_depth)
  628. # Cooling capability/capacity are inherited from the rack type
  629. self.assertEqual(rack.cooling_capability, rack_type.cooling_capability)
  630. self.assertEqual(rack.cooling_capacity, rack_type.cooling_capacity)
  631. class RackTestCase(TestCase):
  632. @classmethod
  633. def setUpTestData(cls):
  634. sites = (
  635. Site(name='Site 1', slug='site-1'),
  636. Site(name='Site 2', slug='site-2'),
  637. )
  638. Site.objects.bulk_create(sites)
  639. locations = (
  640. Location(name='Location 1', slug='location-1', site=sites[0]),
  641. Location(name='Location 2', slug='location-2', site=sites[1]),
  642. )
  643. for location in locations:
  644. location.save()
  645. Rack.objects.create(
  646. name='Rack 1',
  647. facility_id='A101',
  648. site=sites[0],
  649. location=locations[0],
  650. u_height=42
  651. )
  652. manufacturer = Manufacturer.objects.create(name='Manufacturer 1', slug='manufacturer-1')
  653. device_types = (
  654. DeviceType(manufacturer=manufacturer, model='Device Type 1', slug='device-type-1', u_height=1),
  655. DeviceType(manufacturer=manufacturer, model='Device Type 2', slug='device-type-2', u_height=0),
  656. DeviceType(manufacturer=manufacturer, model='Device Type 3', slug='device-type-3', u_height=0.5),
  657. )
  658. DeviceType.objects.bulk_create(device_types)
  659. DeviceRole.objects.create(name='Device Role 1', slug='device-role-1')
  660. def test_rack_device_outside_height(self):
  661. site = Site.objects.first()
  662. rack = Rack.objects.first()
  663. device1 = Device(
  664. name='Device 1',
  665. device_type=DeviceType.objects.first(),
  666. role=DeviceRole.objects.first(),
  667. site=site,
  668. rack=rack,
  669. position=43,
  670. face=DeviceFaceChoices.FACE_FRONT,
  671. )
  672. device1.save()
  673. with self.assertRaises(ValidationError):
  674. rack.clean()
  675. def test_location_site(self):
  676. site1 = Site.objects.get(name='Site 1')
  677. location2 = Location.objects.get(name='Location 2')
  678. rack2 = Rack(
  679. name='Rack 2',
  680. site=site1,
  681. location=location2,
  682. u_height=42
  683. )
  684. rack2.save()
  685. with self.assertRaises(ValidationError):
  686. rack2.clean()
  687. def test_mount_single_device(self):
  688. site = Site.objects.first()
  689. rack = Rack.objects.first()
  690. device1 = Device(
  691. name='TestSwitch1',
  692. device_type=DeviceType.objects.first(),
  693. role=DeviceRole.objects.first(),
  694. site=site,
  695. rack=rack,
  696. position=10.0,
  697. face=DeviceFaceChoices.FACE_REAR,
  698. )
  699. device1.save()
  700. # Validate rack height
  701. self.assertEqual(list(rack.units), list(drange(42.5, 0.5, -0.5)))
  702. # Validate inventory (front face)
  703. rack1_inventory_front = {
  704. u['id']: u for u in rack.get_rack_units(face=DeviceFaceChoices.FACE_FRONT)
  705. }
  706. self.assertEqual(rack1_inventory_front[10.0]['device'], device1)
  707. self.assertEqual(rack1_inventory_front[10.5]['device'], device1)
  708. del rack1_inventory_front[10.0]
  709. del rack1_inventory_front[10.5]
  710. for u in rack1_inventory_front.values():
  711. self.assertIsNone(u['device'])
  712. # Validate inventory (rear face)
  713. rack1_inventory_rear = {
  714. u['id']: u for u in rack.get_rack_units(face=DeviceFaceChoices.FACE_REAR)
  715. }
  716. self.assertEqual(rack1_inventory_rear[10.0]['device'], device1)
  717. self.assertEqual(rack1_inventory_rear[10.5]['device'], device1)
  718. del rack1_inventory_rear[10.0]
  719. del rack1_inventory_rear[10.5]
  720. for u in rack1_inventory_rear.values():
  721. self.assertIsNone(u['device'])
  722. def test_mount_zero_ru(self):
  723. """
  724. Check that a 0RU device can be mounted in a rack with no face/position.
  725. """
  726. site = Site.objects.first()
  727. rack = Rack.objects.first()
  728. Device(
  729. name='Device 1',
  730. role=DeviceRole.objects.first(),
  731. device_type=DeviceType.objects.first(),
  732. site=site,
  733. rack=rack
  734. ).save()
  735. def test_mount_half_u_devices(self):
  736. """
  737. Check that two 0.5U devices can be mounted in the same rack unit.
  738. """
  739. rack = Rack.objects.first()
  740. attrs = {
  741. 'device_type': DeviceType.objects.get(u_height=0.5),
  742. 'role': DeviceRole.objects.first(),
  743. 'site': Site.objects.first(),
  744. 'rack': rack,
  745. 'face': DeviceFaceChoices.FACE_FRONT,
  746. }
  747. Device(name='Device 1', position=1, **attrs).save()
  748. Device(name='Device 2', position=1.5, **attrs).save()
  749. self.assertEqual(len(rack.get_available_units()), rack.u_height * 2 - 3)
  750. def test_change_rack_site(self):
  751. """
  752. Check that child Devices get updated when a Rack is moved to a new Site.
  753. """
  754. site_a = Site.objects.create(name='Site A', slug='site-a')
  755. site_b = Site.objects.create(name='Site B', slug='site-b')
  756. # Create Rack1 in Site A
  757. rack1 = Rack.objects.create(site=site_a, name='Rack 1')
  758. # Create Device1 in Rack1
  759. device1 = Device.objects.create(
  760. site=site_a,
  761. rack=rack1,
  762. device_type=DeviceType.objects.first(),
  763. role=DeviceRole.objects.first()
  764. )
  765. # Move Rack1 to Site B
  766. rack1.site = site_b
  767. rack1.save()
  768. # Check that Device1 is now assigned to Site B
  769. self.assertEqual(Device.objects.get(pk=device1.pk).site, site_b)
  770. def test_utilization(self):
  771. site = Site.objects.first()
  772. rack = Rack.objects.first()
  773. Device(
  774. name='Device 1',
  775. role=DeviceRole.objects.first(),
  776. device_type=DeviceType.objects.first(),
  777. site=site,
  778. rack=rack,
  779. position=1
  780. ).save()
  781. rack.refresh_from_db()
  782. self.assertEqual(rack.get_utilization(), 1 / 42 * 100)
  783. # create device excluded from utilization calculations
  784. dt = DeviceType.objects.create(
  785. manufacturer=Manufacturer.objects.first(),
  786. model='Device Type 4',
  787. slug='device-type-4',
  788. u_height=1,
  789. exclude_from_utilization=True
  790. )
  791. Device(
  792. name='Device 2',
  793. role=DeviceRole.objects.first(),
  794. device_type=dt,
  795. site=site,
  796. rack=rack,
  797. position=5
  798. ).save()
  799. rack.refresh_from_db()
  800. self.assertEqual(rack.get_utilization(), 1 / 42 * 100)
  801. class DeviceTestCase(TestCase):
  802. @classmethod
  803. def setUpTestData(cls):
  804. Site.objects.create(name='Test Site 1', slug='test-site-1')
  805. manufacturer = Manufacturer.objects.create(name='Test Manufacturer 1', slug='test-manufacturer-1')
  806. device_type = DeviceType.objects.create(
  807. manufacturer=manufacturer, model='Test Device Type 1', slug='test-device-type-1'
  808. )
  809. roles = (
  810. DeviceRole(name='Test Role 1', slug='test-role-1'),
  811. DeviceRole(name='Test Role 2', slug='test-role-2'),
  812. )
  813. for role in roles:
  814. role.save()
  815. # Create a CustomField with a default value & assign it to all component models
  816. cf1 = CustomField.objects.create(name='cf1', default='foo')
  817. cf1.object_types.set(
  818. ObjectType.objects.filter(app_label='dcim', model__in=[
  819. 'consoleport',
  820. 'consoleserverport',
  821. 'powerport',
  822. 'poweroutlet',
  823. 'interface',
  824. 'rearport',
  825. 'frontport',
  826. 'modulebay',
  827. 'devicebay',
  828. 'inventoryitem',
  829. ])
  830. )
  831. # Create DeviceType components
  832. ConsolePortTemplate(
  833. device_type=device_type,
  834. name='Console Port 1'
  835. ).save()
  836. ConsoleServerPortTemplate(
  837. device_type=device_type,
  838. name='Console Server Port 1'
  839. ).save()
  840. powerport = PowerPortTemplate(
  841. device_type=device_type,
  842. name='Power Port 1',
  843. maximum_draw=1000,
  844. allocated_draw=500
  845. )
  846. powerport.save()
  847. PowerOutletTemplate(
  848. device_type=device_type,
  849. name='Power Outlet 1',
  850. power_port=powerport,
  851. feed_leg=PowerOutletFeedLegChoices.FEED_LEG_A
  852. ).save()
  853. InterfaceTemplate(
  854. device_type=device_type,
  855. name='Interface 1',
  856. type=InterfaceTypeChoices.TYPE_1GE_FIXED,
  857. mgmt_only=True
  858. ).save()
  859. rearport = RearPortTemplate(
  860. device_type=device_type,
  861. name='Rear Port 1',
  862. type=PortTypeChoices.TYPE_8P8C,
  863. positions=8
  864. )
  865. rearport.save()
  866. frontport = FrontPortTemplate(
  867. device_type=device_type,
  868. name='Front Port 1',
  869. type=PortTypeChoices.TYPE_8P8C,
  870. )
  871. frontport.save()
  872. PortTemplateMapping.objects.create(
  873. device_type=device_type,
  874. front_port=frontport,
  875. rear_port=rearport,
  876. rear_port_position=2,
  877. )
  878. ModuleBayTemplate(
  879. device_type=device_type,
  880. name='Module Bay 1'
  881. ).save()
  882. DeviceBayTemplate(
  883. device_type=device_type,
  884. name='Device Bay 1'
  885. ).save()
  886. InventoryItemTemplate(
  887. device_type=device_type,
  888. name='Inventory Item 1'
  889. ).save()
  890. def test_device_creation(self):
  891. """
  892. Ensure that all Device components are copied automatically from the DeviceType.
  893. """
  894. device = Device(
  895. site=Site.objects.first(),
  896. device_type=DeviceType.objects.first(),
  897. role=DeviceRole.objects.first(),
  898. name='Test Device 1'
  899. )
  900. device.save()
  901. consoleport = ConsolePort.objects.get(
  902. device=device,
  903. name='Console Port 1'
  904. )
  905. self.assertEqual(consoleport.cf['cf1'], 'foo')
  906. consoleserverport = ConsoleServerPort.objects.get(
  907. device=device,
  908. name='Console Server Port 1'
  909. )
  910. self.assertEqual(consoleserverport.cf['cf1'], 'foo')
  911. powerport = PowerPort.objects.get(
  912. device=device,
  913. name='Power Port 1',
  914. maximum_draw=1000,
  915. allocated_draw=500
  916. )
  917. self.assertEqual(powerport.cf['cf1'], 'foo')
  918. poweroutlet = PowerOutlet.objects.get(
  919. device=device,
  920. name='Power Outlet 1',
  921. power_port=powerport,
  922. feed_leg=PowerOutletFeedLegChoices.FEED_LEG_A,
  923. status=PowerOutletStatusChoices.STATUS_ENABLED,
  924. )
  925. self.assertEqual(poweroutlet.cf['cf1'], 'foo')
  926. interface = Interface.objects.get(
  927. device=device,
  928. name='Interface 1',
  929. type=InterfaceTypeChoices.TYPE_1GE_FIXED,
  930. mgmt_only=True
  931. )
  932. self.assertEqual(interface.cf['cf1'], 'foo')
  933. rearport = RearPort.objects.get(
  934. device=device,
  935. name='Rear Port 1',
  936. type=PortTypeChoices.TYPE_8P8C,
  937. positions=8
  938. )
  939. self.assertEqual(rearport.cf['cf1'], 'foo')
  940. frontport = FrontPort.objects.get(
  941. device=device,
  942. name='Front Port 1',
  943. type=PortTypeChoices.TYPE_8P8C,
  944. positions=1
  945. )
  946. self.assertEqual(frontport.cf['cf1'], 'foo')
  947. self.assertTrue(PortMapping.objects.filter(front_port=frontport, rear_port=rearport).exists())
  948. modulebay = ModuleBay.objects.get(
  949. device=device,
  950. name='Module Bay 1'
  951. )
  952. self.assertEqual(modulebay.cf['cf1'], 'foo')
  953. devicebay = DeviceBay.objects.get(
  954. device=device,
  955. name='Device Bay 1'
  956. )
  957. self.assertEqual(devicebay.cf['cf1'], 'foo')
  958. inventoryitem = InventoryItem.objects.get(
  959. device=device,
  960. name='Inventory Item 1'
  961. )
  962. self.assertEqual(inventoryitem.cf['cf1'], 'foo')
  963. def test_device_creation_without_replication(self):
  964. """
  965. Ensure that no components are created when component replication has been disabled.
  966. """
  967. device = Device(
  968. site=Site.objects.first(),
  969. device_type=DeviceType.objects.first(),
  970. role=DeviceRole.objects.first(),
  971. name='Test Device 1',
  972. replicate_components=False
  973. )
  974. device.save()
  975. self.assertFalse(ConsolePort.objects.filter(device=device).exists())
  976. self.assertFalse(ConsoleServerPort.objects.filter(device=device).exists())
  977. self.assertFalse(PowerPort.objects.filter(device=device).exists())
  978. self.assertFalse(PowerOutlet.objects.filter(device=device).exists())
  979. self.assertFalse(Interface.objects.filter(device=device).exists())
  980. self.assertFalse(RearPort.objects.filter(device=device).exists())
  981. self.assertFalse(FrontPort.objects.filter(device=device).exists())
  982. self.assertFalse(ModuleBay.objects.filter(device=device).exists())
  983. self.assertFalse(DeviceBay.objects.filter(device=device).exists())
  984. self.assertFalse(InventoryItem.objects.filter(device=device).exists())
  985. def test_multiple_unnamed_devices(self):
  986. device1 = Device(
  987. site=Site.objects.first(),
  988. device_type=DeviceType.objects.first(),
  989. role=DeviceRole.objects.first(),
  990. name=None
  991. )
  992. device1.save()
  993. device2 = Device(
  994. site=device1.site,
  995. device_type=device1.device_type,
  996. role=device1.role,
  997. name=None
  998. )
  999. device2.full_clean()
  1000. device2.save()
  1001. self.assertEqual(Device.objects.filter(name__isnull=True).count(), 2)
  1002. def test_device_name_case_sensitivity(self):
  1003. device1 = Device(
  1004. site=Site.objects.first(),
  1005. device_type=DeviceType.objects.first(),
  1006. role=DeviceRole.objects.first(),
  1007. name='device 1'
  1008. )
  1009. device1.save()
  1010. device2 = Device(
  1011. site=device1.site,
  1012. device_type=device1.device_type,
  1013. role=device1.role,
  1014. name='DEVICE 1'
  1015. )
  1016. # Uniqueness validation for name should ignore case
  1017. with self.assertRaises(ValidationError):
  1018. device2.full_clean()
  1019. def test_device_duplicate_names(self):
  1020. device1 = Device(
  1021. site=Site.objects.first(),
  1022. device_type=DeviceType.objects.first(),
  1023. role=DeviceRole.objects.first(),
  1024. name='Test Device 1'
  1025. )
  1026. device1.save()
  1027. device2 = Device(
  1028. site=device1.site,
  1029. device_type=device1.device_type,
  1030. role=device1.role,
  1031. name=device1.name
  1032. )
  1033. # Two devices assigned to the same Site and no Tenant should fail validation
  1034. with self.assertRaises(ValidationError):
  1035. device2.full_clean()
  1036. tenant = Tenant.objects.create(name='Test Tenant 1', slug='test-tenant-1')
  1037. device1.tenant = tenant
  1038. device1.save()
  1039. device2.tenant = tenant
  1040. # Two devices assigned to the same Site and the same Tenant should fail validation
  1041. with self.assertRaises(ValidationError):
  1042. device2.full_clean()
  1043. device2.tenant = None
  1044. # Two devices assigned to the same Site and different Tenants should pass validation
  1045. device2.full_clean()
  1046. device2.save()
  1047. def test_empty_asset_tag_coerced_to_null_on_clean(self):
  1048. """
  1049. An empty string assigned to a unique nullable CharField (e.g. asset_tag) must be coerced
  1050. to None on save so that multiple objects can be saved without violating the unique
  1051. constraint. Test that this is done on clean().
  1052. """
  1053. common_kwargs = {
  1054. 'site': Site.objects.first(),
  1055. 'device_type': DeviceType.objects.first(),
  1056. 'role': DeviceRole.objects.first(),
  1057. }
  1058. device1 = Device(name='Device 1', asset_tag='', **common_kwargs)
  1059. device1.clean()
  1060. self.assertIsNone(device1.asset_tag)
  1061. def test_empty_asset_tag_coerced_to_null_on_save(self):
  1062. """
  1063. An empty string assigned to a unique nullable CharField (e.g. asset_tag) must be coerced
  1064. to None on save so that multiple objects can be saved without violating the unique
  1065. constraint. Test that this is done on save().
  1066. """
  1067. common_kwargs = {
  1068. 'site': Site.objects.first(),
  1069. 'device_type': DeviceType.objects.first(),
  1070. 'role': DeviceRole.objects.first(),
  1071. }
  1072. device1 = Device(name='Device 1', asset_tag='', **common_kwargs)
  1073. device1.save()
  1074. device2 = Device(name='Device 2', asset_tag='', **common_kwargs)
  1075. device2.save()
  1076. device1.refresh_from_db()
  1077. device2.refresh_from_db()
  1078. self.assertIsNone(device1.asset_tag)
  1079. self.assertIsNone(device2.asset_tag)
  1080. def test_device_label(self):
  1081. device1 = Device(
  1082. site=Site.objects.first(),
  1083. device_type=DeviceType.objects.first(),
  1084. role=DeviceRole.objects.first(),
  1085. name=None,
  1086. )
  1087. self.assertEqual(device1.label, None)
  1088. device1.name = 'Test Device 1'
  1089. self.assertEqual(device1.label, 'Test Device 1')
  1090. virtual_chassis = VirtualChassis.objects.create(name='VC 1')
  1091. device2 = Device(
  1092. site=Site.objects.first(),
  1093. device_type=DeviceType.objects.first(),
  1094. role=DeviceRole.objects.first(),
  1095. name=None,
  1096. virtual_chassis=virtual_chassis,
  1097. vc_position=2,
  1098. )
  1099. self.assertEqual(device2.label, 'VC 1:2')
  1100. device2.name = 'Test Device 2'
  1101. self.assertEqual(device2.label, 'Test Device 2')
  1102. def test_device_mismatched_site_cluster(self):
  1103. cluster_type = ClusterType.objects.create(name='Cluster Type 1', slug='cluster-type-1')
  1104. Cluster.objects.create(name='Cluster 1', type=cluster_type)
  1105. sites = (
  1106. Site(name='Site 1', slug='site-1'),
  1107. Site(name='Site 2', slug='site-2'),
  1108. )
  1109. Site.objects.bulk_create(sites)
  1110. clusters = (
  1111. Cluster(name='Cluster 1', type=cluster_type, scope=sites[0]),
  1112. Cluster(name='Cluster 2', type=cluster_type, scope=sites[1]),
  1113. Cluster(name='Cluster 3', type=cluster_type, scope=None),
  1114. )
  1115. for cluster in clusters:
  1116. cluster.save()
  1117. device_type = DeviceType.objects.first()
  1118. device_role = DeviceRole.objects.first()
  1119. # Device with site only should pass
  1120. Device(
  1121. name='device1',
  1122. site=sites[0],
  1123. device_type=device_type,
  1124. role=device_role
  1125. ).full_clean()
  1126. # Device with site, cluster non-site should pass
  1127. Device(
  1128. name='device1',
  1129. site=sites[0],
  1130. device_type=device_type,
  1131. role=device_role,
  1132. cluster=clusters[2]
  1133. ).full_clean()
  1134. # Device with mismatched site & cluster should fail
  1135. with self.assertRaises(ValidationError):
  1136. Device(
  1137. name='device1',
  1138. site=sites[0],
  1139. device_type=device_type,
  1140. role=device_role,
  1141. cluster=clusters[1]
  1142. ).full_clean()
  1143. @tag('regression') # Ref: #22717
  1144. def test_device_mismatched_location_cluster(self):
  1145. """
  1146. A cluster scoped to a different location than the device must be rejected
  1147. with a field validation error naming that location.
  1148. """
  1149. site = Site.objects.create(name='Site 1', slug='site-1')
  1150. locations = (
  1151. Location(site=site, name='Location A', slug='location-a'),
  1152. Location(site=site, name='Location B', slug='location-b'),
  1153. )
  1154. for location in locations:
  1155. location.save()
  1156. cluster_type = ClusterType.objects.create(name='Cluster Type 1', slug='cluster-type-1')
  1157. cluster = Cluster.objects.create(name='Cluster 1', type=cluster_type, scope=locations[0])
  1158. device_type = DeviceType.objects.first()
  1159. device_role = DeviceRole.objects.first()
  1160. # Device in the cluster's location should pass
  1161. Device(
  1162. name='device1',
  1163. site=site,
  1164. location=locations[0],
  1165. device_type=device_type,
  1166. role=device_role,
  1167. cluster=cluster
  1168. ).full_clean()
  1169. # Device in a different location of the same site should fail
  1170. with self.assertRaisesMessage(
  1171. ValidationError,
  1172. 'The assigned cluster belongs to a different location (Location A)'
  1173. ):
  1174. Device(
  1175. name='device1',
  1176. site=site,
  1177. location=locations[1],
  1178. device_type=device_type,
  1179. role=device_role,
  1180. cluster=cluster
  1181. ).full_clean()
  1182. @tag('regression') # Ref: #23274
  1183. def test_vc_interfaces_unsaved_device(self):
  1184. """An unsaved device outside a virtual chassis matches no interfaces and runs no query."""
  1185. device = create_test_device('Device 1')
  1186. Interface.objects.create(device=device, name='eth0', type=InterfaceTypeChoices.TYPE_OTHER)
  1187. unsaved = Device(name='Device 2', site=device.site, device_type=device.device_type, role=device.role)
  1188. for if_master in (True, False):
  1189. with self.subTest(if_master=if_master), self.assertNumQueries(0):
  1190. self.assertEqual(list(unsaved.vc_interfaces(if_master=if_master)), [])
  1191. @tag('regression') # Ref: #23274
  1192. def test_unsaved_device_rejects_ips_of_other_devices(self):
  1193. """An unsaved device rejects a primary or OOB IP assigned to another device's interface."""
  1194. device = create_test_device('Device 1')
  1195. interface = Interface.objects.create(device=device, name='eth0', type=InterfaceTypeChoices.TYPE_OTHER)
  1196. ip4 = IPAddress.objects.create(address='192.0.2.1/24', assigned_object=interface)
  1197. ip6 = IPAddress.objects.create(address='2001:db8::1/64', assigned_object=interface)
  1198. nat_ip4 = IPAddress.objects.create(address='198.51.100.1/24', nat_inside=ip4)
  1199. for field, ip in (('primary_ip4', ip4), ('primary_ip4', nat_ip4), ('primary_ip6', ip6), ('oob_ip', ip4)):
  1200. with self.subTest(field=field, ip=ip):
  1201. unsaved = Device(
  1202. name='Device 2', site=device.site, device_type=device.device_type, role=device.role,
  1203. **{field: ip}
  1204. )
  1205. with self.assertRaises(ValidationError) as cm:
  1206. unsaved.full_clean()
  1207. self.assertIn(field, cm.exception.message_dict)
  1208. @tag('regression') # Ref: #23274
  1209. def test_unsaved_device_accepts_ips_of_virtual_chassis_peers(self):
  1210. """An unsaved virtual chassis member accepts a peer's IP unless its interface is management-only."""
  1211. virtual_chassis = VirtualChassis.objects.create(name='Virtual Chassis 1')
  1212. peer = create_test_device('Device 1', virtual_chassis=virtual_chassis, vc_position=1)
  1213. interface = Interface.objects.create(device=peer, name='eth0', type=InterfaceTypeChoices.TYPE_OTHER)
  1214. mgmt_interface = Interface.objects.create(
  1215. device=peer, name='mgmt0', type=InterfaceTypeChoices.TYPE_OTHER, mgmt_only=True
  1216. )
  1217. ip4 = IPAddress.objects.create(address='192.0.2.1/24', assigned_object=interface)
  1218. ip6 = IPAddress.objects.create(address='2001:db8::1/64', assigned_object=interface)
  1219. mgmt_ip4 = IPAddress.objects.create(address='192.0.2.2/24', assigned_object=mgmt_interface)
  1220. common_kwargs = {
  1221. 'name': 'Device 2',
  1222. 'site': peer.site,
  1223. 'device_type': peer.device_type,
  1224. 'role': peer.role,
  1225. 'virtual_chassis': virtual_chassis,
  1226. 'vc_position': 2,
  1227. }
  1228. for field, ip in (('primary_ip4', ip4), ('primary_ip6', ip6), ('oob_ip', ip4)):
  1229. with self.subTest(field=field):
  1230. Device(**common_kwargs, **{field: ip}).full_clean()
  1231. with self.assertRaises(ValidationError) as cm:
  1232. Device(**common_kwargs, primary_ip4=mgmt_ip4).full_clean()
  1233. self.assertIn('primary_ip4', cm.exception.message_dict)
  1234. class DeviceBayTestCase(TestCase):
  1235. @classmethod
  1236. def setUpTestData(cls):
  1237. site = Site.objects.create(name='Test Site 1', slug='test-site-1')
  1238. manufacturer = Manufacturer.objects.create(name='Test Manufacturer 1', slug='test-manufacturer-1')
  1239. # Parent device type must support device bays (is_parent_device=True)
  1240. parent_device_type = DeviceType.objects.create(
  1241. manufacturer=manufacturer,
  1242. model='Parent Device Type',
  1243. slug='parent-device-type',
  1244. subdevice_role=SubdeviceRoleChoices.ROLE_PARENT
  1245. )
  1246. # Child device type for installation
  1247. child_device_type = DeviceType.objects.create(
  1248. manufacturer=manufacturer,
  1249. model='Child Device Type',
  1250. slug='child-device-type',
  1251. u_height=0,
  1252. subdevice_role=SubdeviceRoleChoices.ROLE_CHILD
  1253. )
  1254. device_role = DeviceRole.objects.create(name='Test Role 1', slug='test-role-1')
  1255. cls.parent_device = Device.objects.create(
  1256. name='Parent Device',
  1257. device_type=parent_device_type,
  1258. role=device_role,
  1259. site=site
  1260. )
  1261. cls.child_device = Device.objects.create(
  1262. name='Child Device',
  1263. device_type=child_device_type,
  1264. role=device_role,
  1265. site=site
  1266. )
  1267. cls.child_device_2 = Device.objects.create(
  1268. name='Child Device 2',
  1269. device_type=child_device_type,
  1270. role=device_role,
  1271. site=site
  1272. )
  1273. def test_cannot_install_device_in_disabled_bay(self):
  1274. """
  1275. Test that a device cannot be installed into a disabled DeviceBay.
  1276. """
  1277. # Create a disabled device bay with a device being installed
  1278. device_bay = DeviceBay(
  1279. device=self.parent_device,
  1280. name='Disabled Bay',
  1281. enabled=False,
  1282. installed_device=self.child_device
  1283. )
  1284. with self.assertRaises(ValidationError) as cm:
  1285. device_bay.clean()
  1286. self.assertIn('installed_device', cm.exception.message_dict)
  1287. self.assertIn('disabled device bay', str(cm.exception.message_dict['installed_device']))
  1288. def test_can_disable_bay_with_existing_device(self):
  1289. """
  1290. Test that disabling a bay that already has a device installed does NOT raise an error
  1291. (same installed_device_id).
  1292. """
  1293. # First, create an enabled device bay with a device installed
  1294. device_bay = DeviceBay.objects.create(
  1295. device=self.parent_device,
  1296. name='Bay To Disable',
  1297. enabled=True,
  1298. installed_device=self.child_device
  1299. )
  1300. # Now disable the bay while keeping the same installed device
  1301. device_bay.enabled = False
  1302. # This should NOT raise a ValidationError
  1303. device_bay.clean()
  1304. device_bay.save()
  1305. device_bay.refresh_from_db()
  1306. self.assertFalse(device_bay.enabled)
  1307. self.assertEqual(device_bay.installed_device, self.child_device)
  1308. def test_cannot_change_installed_device_in_disabled_bay(self):
  1309. """
  1310. Test that changing the installed device in a disabled bay raises a ValidationError.
  1311. """
  1312. # Create an enabled device bay with a device installed
  1313. device_bay = DeviceBay.objects.create(
  1314. device=self.parent_device,
  1315. name='Bay With Device',
  1316. enabled=True,
  1317. installed_device=self.child_device
  1318. )
  1319. # Disable the bay and try to change the installed device
  1320. device_bay.enabled = False
  1321. device_bay.installed_device = self.child_device_2
  1322. with self.assertRaises(ValidationError) as cm:
  1323. device_bay.clean()
  1324. self.assertIn('installed_device', cm.exception.message_dict)
  1325. class ModuleBayTestCase(TestCase):
  1326. @classmethod
  1327. def setUpTestData(cls):
  1328. site = Site.objects.create(name='Test Site 1', slug='test-site-1')
  1329. manufacturer = Manufacturer.objects.create(name='Test Manufacturer 1', slug='test-manufacturer-1')
  1330. device_type = DeviceType.objects.create(
  1331. manufacturer=manufacturer, model='Test Device Type 1', slug='test-device-type-1'
  1332. )
  1333. device_role = DeviceRole.objects.create(name='Test Role 1', slug='test-role-1')
  1334. # Create a CustomField with a default value & assign it to all component models
  1335. location = Location.objects.create(name='Location 1', slug='location-1', site=site)
  1336. rack = Rack.objects.create(name='Rack 1', site=site)
  1337. device = Device.objects.create(
  1338. name='Device 1', device_type=device_type, role=device_role, site=site, location=location, rack=rack
  1339. )
  1340. module_bays = (
  1341. ModuleBay(device=device, name='Module Bay 1', label='A', description='First'),
  1342. ModuleBay(device=device, name='Module Bay 2', label='B', description='Second'),
  1343. ModuleBay(device=device, name='Module Bay 3', label='C', description='Third'),
  1344. )
  1345. for module_bay in module_bays:
  1346. module_bay.save()
  1347. manufacturer = Manufacturer.objects.create(name='Manufacturer 1', slug='manufacturer-1')
  1348. module_type = ModuleType.objects.create(manufacturer=manufacturer, model='Module Type 1')
  1349. modules = (
  1350. Module(device=device, module_bay=module_bays[0], module_type=module_type),
  1351. Module(device=device, module_bay=module_bays[1], module_type=module_type),
  1352. Module(device=device, module_bay=module_bays[2], module_type=module_type),
  1353. )
  1354. # M3 -> MB3 -> M2 -> MB2 -> M1 -> MB1
  1355. Module.objects.bulk_create(modules)
  1356. module_bays[1].module = modules[0]
  1357. module_bays[1].clean()
  1358. module_bays[1].save()
  1359. module_bays[2].module = modules[1]
  1360. module_bays[2].clean()
  1361. module_bays[2].save()
  1362. def test_module_bay_recursion(self):
  1363. module_bay_1 = ModuleBay.objects.get(name='Module Bay 1')
  1364. module_bay_3 = ModuleBay.objects.get(name='Module Bay 3')
  1365. module_1 = Module.objects.get(module_bay=module_bay_1)
  1366. module_3 = Module.objects.get(module_bay=module_bay_3)
  1367. # Confirm error if ModuleBay recurses
  1368. with self.assertRaises(ValidationError):
  1369. module_bay_1.module = module_3
  1370. module_bay_1.clean()
  1371. module_bay_1.save()
  1372. # Confirm error if Module recurses (empty target bay, so the occupied-bay check cannot mask it)
  1373. module_bay_4 = ModuleBay.objects.create(device=module_1.device, name='Module Bay 4', module=module_3)
  1374. with self.assertRaisesMessage(ValidationError, 'cannot belong to a module installed within it'):
  1375. module_1.module_bay = module_bay_4
  1376. module_1.clean()
  1377. module_1.save()
  1378. @tag('regression') # #22146
  1379. def test_module_bay_ordering_after_recreate(self):
  1380. """
  1381. Module bays must remain in name order after a delete-and-recreate cycle,
  1382. even though MPTT no longer renumbers tree_ids on root insertion.
  1383. """
  1384. device_type = DeviceType.objects.first()
  1385. device_role = DeviceRole.objects.first()
  1386. site = Site.objects.first()
  1387. device = Device.objects.create(
  1388. name='Ordering Test Device',
  1389. device_type=device_type,
  1390. role=device_role,
  1391. site=site,
  1392. )
  1393. for name in ('Bay 1', 'Bay 2', 'Bay 3', 'Bay 4'):
  1394. ModuleBay.objects.create(device=device, name=name)
  1395. ModuleBay.objects.get(device=device, name='Bay 3').delete()
  1396. ModuleBay.objects.create(device=device, name='Bay 3')
  1397. names = list(ModuleBay.objects.filter(device=device).values_list('name', flat=True))
  1398. self.assertEqual(names, ['Bay 1', 'Bay 2', 'Bay 3', 'Bay 4'])
  1399. @tag('regression') # #22146
  1400. def test_module_bay_natural_ordering(self):
  1401. """
  1402. Module bays must be returned in natural (numeric-aware) order, e.g.
  1403. "Bay 2" before "Bay 10".
  1404. """
  1405. device_type = DeviceType.objects.first()
  1406. device_role = DeviceRole.objects.first()
  1407. site = Site.objects.first()
  1408. device = Device.objects.create(
  1409. name='Natural Sort Device',
  1410. device_type=device_type,
  1411. role=device_role,
  1412. site=site,
  1413. )
  1414. # Insert in non-natural order to confirm sort is not insertion-driven.
  1415. for name in ('Bay 10', 'Bay 1', 'Bay 2', 'Bay 11'):
  1416. ModuleBay.objects.create(device=device, name=name)
  1417. names = list(ModuleBay.objects.filter(device=device).values_list('name', flat=True))
  1418. self.assertEqual(names, ['Bay 1', 'Bay 2', 'Bay 10', 'Bay 11'])
  1419. @tag('regression') # #22146
  1420. def test_child_module_bay_ordering(self):
  1421. """
  1422. Child module bays inside a module must be returned in name order even
  1423. when inserted out of order.
  1424. """
  1425. device_type = DeviceType.objects.first()
  1426. device_role = DeviceRole.objects.first()
  1427. site = Site.objects.first()
  1428. device = Device.objects.create(
  1429. name='Child Ordering Device',
  1430. device_type=device_type,
  1431. role=device_role,
  1432. site=site,
  1433. )
  1434. root_bay = ModuleBay.objects.create(device=device, name='Bay 1')
  1435. manufacturer = Manufacturer.objects.first()
  1436. module_type = ModuleType.objects.create(
  1437. manufacturer=manufacturer, model='Child Ordering Type'
  1438. )
  1439. module = Module.objects.create(
  1440. device=device, module_bay=root_bay, module_type=module_type
  1441. )
  1442. # Insert children out of name order.
  1443. for name in ('Bay 1.1', 'Bay 1.3', 'Bay 1.2'):
  1444. ModuleBay.objects.create(device=device, module=module, name=name)
  1445. names = list(ModuleBay.objects.filter(device=device).values_list('name', flat=True))
  1446. self.assertEqual(names, ['Bay 1', 'Bay 1.1', 'Bay 1.2', 'Bay 1.3'])
  1447. @tag('regression') # #22146
  1448. def test_root_module_bay_rename_preserves_paths(self):
  1449. """
  1450. Renaming a root module bay must not rewrite any tree's path. Renaming
  1451. touches only sort_path (the display-ordering column), so every bay's
  1452. path — including the renamed bay's own — must be unchanged afterward.
  1453. """
  1454. device_type = DeviceType.objects.first()
  1455. device_role = DeviceRole.objects.first()
  1456. site = Site.objects.first()
  1457. device = Device.objects.create(
  1458. name='Rename Path Device',
  1459. device_type=device_type,
  1460. role=device_role,
  1461. site=site,
  1462. )
  1463. for name in ('Bay 1', 'Bay 2', 'Bay 3', 'Bay 4'):
  1464. ModuleBay.objects.create(device=device, name=name)
  1465. paths_before = {
  1466. bay.pk: str(bay.path)
  1467. for bay in ModuleBay.objects.filter(device=device)
  1468. }
  1469. bay = ModuleBay.objects.get(device=device, name='Bay 2')
  1470. bay.name = 'Bay 99'
  1471. bay.save()
  1472. paths_after = {
  1473. bay.pk: str(bay.path)
  1474. for bay in ModuleBay.objects.filter(device=device)
  1475. }
  1476. self.assertEqual(paths_after, paths_before)
  1477. @tag('regression') # #22146
  1478. def test_root_module_bay_rename_updates_display_order(self):
  1479. """
  1480. Even though renaming a root module bay does not rewrite its path,
  1481. the manager's _root_name annotation must reflect the new name so the
  1482. display ordering is correct.
  1483. """
  1484. device_type = DeviceType.objects.first()
  1485. device_role = DeviceRole.objects.first()
  1486. site = Site.objects.first()
  1487. device = Device.objects.create(
  1488. name='Rename Order Device',
  1489. device_type=device_type,
  1490. role=device_role,
  1491. site=site,
  1492. )
  1493. for name in ('Bay 1', 'Bay 2', 'Bay 3'):
  1494. ModuleBay.objects.create(device=device, name=name)
  1495. bay = ModuleBay.objects.get(device=device, name='Bay 1')
  1496. bay.name = 'Bay 4'
  1497. bay.save()
  1498. names = list(ModuleBay.objects.filter(device=device).values_list('name', flat=True))
  1499. self.assertEqual(names, ['Bay 2', 'Bay 3', 'Bay 4'])
  1500. @tag('regression') # #22146
  1501. def test_child_module_bay_rename_preserves_intra_tree_ordering(self):
  1502. """
  1503. Renaming a *child* module bay must still trigger MPTT's intra-tree
  1504. reorder, so siblings appear in name order after the rename. The
  1505. rename-bypass only covers root bays.
  1506. """
  1507. device_type = DeviceType.objects.first()
  1508. device_role = DeviceRole.objects.first()
  1509. site = Site.objects.first()
  1510. device = Device.objects.create(
  1511. name='Child Rename Device',
  1512. device_type=device_type,
  1513. role=device_role,
  1514. site=site,
  1515. )
  1516. root_bay = ModuleBay.objects.create(device=device, name='Bay 1')
  1517. manufacturer = Manufacturer.objects.first()
  1518. module_type = ModuleType.objects.create(
  1519. manufacturer=manufacturer, model='Child Rename Type'
  1520. )
  1521. module = Module.objects.create(
  1522. device=device, module_bay=root_bay, module_type=module_type
  1523. )
  1524. for name in ('Bay 1.1', 'Bay 1.2', 'Bay 1.3'):
  1525. ModuleBay.objects.create(device=device, module=module, name=name)
  1526. child = ModuleBay.objects.get(device=device, name='Bay 1.1')
  1527. child.name = 'Bay 1.4'
  1528. child.save()
  1529. names = list(ModuleBay.objects.filter(device=device).values_list('name', flat=True))
  1530. self.assertEqual(names, ['Bay 1', 'Bay 1.2', 'Bay 1.3', 'Bay 1.4'])
  1531. @tag('regression') # #22146
  1532. def test_root_to_child_transition_still_relocates(self):
  1533. """
  1534. Promoting an existing root module bay to a child (by assigning a
  1535. module) must still flow through MPTT's normal move logic. The
  1536. rename-bypass must not suppress legitimate parent changes.
  1537. """
  1538. device_type = DeviceType.objects.first()
  1539. device_role = DeviceRole.objects.first()
  1540. site = Site.objects.first()
  1541. device = Device.objects.create(
  1542. name='Root To Child Device',
  1543. device_type=device_type,
  1544. role=device_role,
  1545. site=site,
  1546. )
  1547. host_bay = ModuleBay.objects.create(device=device, name='Host Bay')
  1548. movable_bay = ModuleBay.objects.create(device=device, name='Movable Bay')
  1549. manufacturer = Manufacturer.objects.first()
  1550. module_type = ModuleType.objects.create(
  1551. manufacturer=manufacturer, model='Root To Child Type'
  1552. )
  1553. host_module = Module.objects.create(
  1554. device=device, module_bay=host_bay, module_type=module_type
  1555. )
  1556. movable_bay.module = host_module
  1557. movable_bay.save()
  1558. movable_bay.refresh_from_db()
  1559. host_bay.refresh_from_db()
  1560. self.assertEqual(movable_bay.parent_id, host_bay.pk)
  1561. # The trigger cascade must have re-rooted the moved bay into host_bay's
  1562. # tree: its path is now a strict descendant of host_bay's path.
  1563. self.assertTrue(str(movable_bay.path).startswith(f'{host_bay.path}.'))
  1564. @tag('regression') # #22251
  1565. def test_moving_module_reparents_child_module_bays(self):
  1566. """
  1567. When a module is moved to a different module bay, each child ModuleBay
  1568. (a bay that belongs to the module) must have its parent updated to the
  1569. new host bay. Without the fix the children stay parented to the old bay
  1570. even though Module.module_bay_id has changed.
  1571. """
  1572. device_type = DeviceType.objects.first()
  1573. device_role = DeviceRole.objects.first()
  1574. site = Site.objects.first()
  1575. device = Device.objects.create(
  1576. name='Move Module Device',
  1577. device_type=device_type,
  1578. role=device_role,
  1579. site=site,
  1580. )
  1581. bay_a = ModuleBay.objects.create(device=device, name='Bay A')
  1582. bay_b = ModuleBay.objects.create(device=device, name='Bay B')
  1583. manufacturer = Manufacturer.objects.first()
  1584. module_type = ModuleType.objects.create(
  1585. manufacturer=manufacturer, model='Move Module Type'
  1586. )
  1587. module = Module.objects.create(
  1588. device=device, module_bay=bay_a, module_type=module_type
  1589. )
  1590. child_1 = ModuleBay.objects.create(device=device, module=module, name='Child Bay 1')
  1591. child_2 = ModuleBay.objects.create(device=device, module=module, name='Child Bay 2')
  1592. self.assertEqual(child_1.parent_id, bay_a.pk)
  1593. self.assertEqual(child_2.parent_id, bay_a.pk)
  1594. # Move the module to bay_b.
  1595. module.module_bay = bay_b
  1596. module.save()
  1597. child_1.refresh_from_db()
  1598. child_2.refresh_from_db()
  1599. self.assertEqual(child_1.parent_id, bay_b.pk)
  1600. self.assertEqual(child_2.parent_id, bay_b.pk)
  1601. # Children must be re-rooted under bay_b in the ltree hierarchy.
  1602. bay_b.refresh_from_db()
  1603. self.assertTrue(str(child_1.path).startswith(f'{bay_b.path}.'))
  1604. self.assertTrue(str(child_2.path).startswith(f'{bay_b.path}.'))
  1605. @tag('regression') # #22251
  1606. def test_moving_module_reparents_grandchild_module_bays(self):
  1607. """
  1608. When a module is moved, grandchild ModuleBays (bays inside a module
  1609. that is itself installed inside a child bay of the moved module) must
  1610. also land in the new ltree subtree. The trigger cascade moves subtrees
  1611. atomically, so calling save() only on direct children is sufficient —
  1612. this test documents and preserves that invariant for future tree-backend
  1613. changes.
  1614. """
  1615. device_type = DeviceType.objects.first()
  1616. device_role = DeviceRole.objects.first()
  1617. site = Site.objects.first()
  1618. device = Device.objects.create(
  1619. name='Grandchild Move Device',
  1620. device_type=device_type,
  1621. role=device_role,
  1622. site=site,
  1623. )
  1624. bay_a = ModuleBay.objects.create(device=device, name='Bay A')
  1625. bay_b = ModuleBay.objects.create(device=device, name='Bay B')
  1626. manufacturer = Manufacturer.objects.first()
  1627. module_type = ModuleType.objects.create(
  1628. manufacturer=manufacturer, model='Grandchild Move Type'
  1629. )
  1630. # Depth-1: module installed in bay_a, with one child bay.
  1631. module_1 = Module.objects.create(device=device, module_bay=bay_a, module_type=module_type)
  1632. child_bay = ModuleBay.objects.create(device=device, module=module_1, name='Child Bay')
  1633. # Depth-2: module installed in child_bay, with one grandchild bay.
  1634. module_2 = Module.objects.create(device=device, module_bay=child_bay, module_type=module_type)
  1635. grandchild_bay = ModuleBay.objects.create(device=device, module=module_2, name='Grandchild Bay')
  1636. self.assertEqual(child_bay.parent_id, bay_a.pk)
  1637. self.assertEqual(grandchild_bay.parent_id, child_bay.pk)
  1638. bay_a.refresh_from_db()
  1639. self.assertTrue(str(grandchild_bay.path).startswith(f'{bay_a.path}.'))
  1640. # Move the top-level module to bay_b.
  1641. module_1.module_bay = bay_b
  1642. module_1.save()
  1643. child_bay.refresh_from_db()
  1644. grandchild_bay.refresh_from_db()
  1645. bay_b.refresh_from_db()
  1646. self.assertEqual(child_bay.parent_id, bay_b.pk)
  1647. self.assertTrue(str(child_bay.path).startswith(f'{bay_b.path}.'))
  1648. # Grandchild's direct parent (child_bay) is unchanged; only tree placement moves.
  1649. self.assertEqual(grandchild_bay.parent_id, child_bay.pk)
  1650. self.assertTrue(str(grandchild_bay.path).startswith(f'{bay_b.path}.'))
  1651. def test_single_module_token(self):
  1652. device_type = DeviceType.objects.first()
  1653. device_role = DeviceRole.objects.first()
  1654. site = Site.objects.first()
  1655. location = Location.objects.first()
  1656. rack = Rack.objects.first()
  1657. # Create DeviceType components
  1658. ConsolePortTemplate.objects.create(
  1659. device_type=device_type,
  1660. name='{module}',
  1661. label='{module}',
  1662. )
  1663. ModuleBayTemplate.objects.create(
  1664. device_type=device_type,
  1665. name='Module Bay 1'
  1666. )
  1667. device = Device.objects.create(
  1668. name='Device 2',
  1669. device_type=device_type,
  1670. role=device_role,
  1671. site=site,
  1672. location=location,
  1673. rack=rack
  1674. )
  1675. device.consoleports.first()
  1676. @tag('regression') # #19918
  1677. def test_nested_module_bay_label_resolution(self):
  1678. """Test that nested module bay labels properly resolve {module} placeholders"""
  1679. manufacturer = Manufacturer.objects.first()
  1680. site = Site.objects.first()
  1681. device_role = DeviceRole.objects.first()
  1682. # Create device type with module bay template (position='A')
  1683. device_type = DeviceType.objects.create(
  1684. manufacturer=manufacturer,
  1685. model='Device with Bays',
  1686. slug='device-with-bays'
  1687. )
  1688. ModuleBayTemplate.objects.create(
  1689. device_type=device_type,
  1690. name='Bay A',
  1691. position='A'
  1692. )
  1693. # Create module type with nested bay template using {module} placeholder
  1694. module_type = ModuleType.objects.create(
  1695. manufacturer=manufacturer,
  1696. model='Module with Nested Bays'
  1697. )
  1698. ModuleBayTemplate.objects.create(
  1699. module_type=module_type,
  1700. name='SFP {module}-21',
  1701. label='{module}-21',
  1702. position='21'
  1703. )
  1704. # Create device and install module
  1705. device = Device.objects.create(
  1706. name='Test Device',
  1707. device_type=device_type,
  1708. role=device_role,
  1709. site=site
  1710. )
  1711. module_bay = device.modulebays.get(name='Bay A')
  1712. module = Module.objects.create(
  1713. device=device,
  1714. module_bay=module_bay,
  1715. module_type=module_type
  1716. )
  1717. # Verify nested bay label resolves {module} to parent position
  1718. nested_bay = module.modulebays.get(name='SFP A-21')
  1719. self.assertEqual(nested_bay.label, 'A-21')
  1720. @tag('regression') # #21418
  1721. def test_module_install_nests_module_bay_parent(self):
  1722. """
  1723. A module bay instantiated when a module is installed must be nested under the
  1724. installing module's bay. bulk_create() bypasses ModuleBay.save(), so the parent
  1725. is assigned in ModuleBayTemplate.instantiate(); without it the bay would be left
  1726. a root with a top-level ltree path.
  1727. """
  1728. manufacturer = Manufacturer.objects.first()
  1729. site = Site.objects.first()
  1730. device_role = DeviceRole.objects.first()
  1731. device_type = DeviceType.objects.create(
  1732. manufacturer=manufacturer, model='Chassis with Bay', slug='chassis-with-bay'
  1733. )
  1734. ModuleBayTemplate.objects.create(device_type=device_type, name='Bay A')
  1735. module_type = ModuleType.objects.create(manufacturer=manufacturer, model='Module with Sub-bay')
  1736. ModuleBayTemplate.objects.create(module_type=module_type, name='Sub-bay 1')
  1737. device = Device.objects.create(
  1738. name='Nested Bay Parent Device', device_type=device_type, role=device_role, site=site
  1739. )
  1740. parent_bay = device.modulebays.get(name='Bay A')
  1741. module = Module.objects.create(device=device, module_bay=parent_bay, module_type=module_type)
  1742. nested_bay = module.modulebays.get(name='Sub-bay 1')
  1743. self.assertEqual(nested_bay.parent, parent_bay)
  1744. # The ltree path/level must reflect the nesting, not a root placement.
  1745. self.assertEqual(nested_bay.level, parent_bay.level + 1)
  1746. self.assertTrue(str(nested_bay.path).startswith(f'{parent_bay.path}.'))
  1747. @tag('regression') # #20467
  1748. def test_nested_module_bay_position_resolution(self):
  1749. """Test that {module} in a module bay template's position field is resolved when the module is installed."""
  1750. manufacturer = Manufacturer.objects.first()
  1751. site = Site.objects.first()
  1752. device_role = DeviceRole.objects.first()
  1753. device_type = DeviceType.objects.create(
  1754. manufacturer=manufacturer,
  1755. model='Device with Position Test',
  1756. slug='device-with-position-test'
  1757. )
  1758. ModuleBayTemplate.objects.create(
  1759. device_type=device_type,
  1760. name='Slot 1',
  1761. position='1'
  1762. )
  1763. module_type = ModuleType.objects.create(
  1764. manufacturer=manufacturer,
  1765. model='Module with Position Placeholder'
  1766. )
  1767. ModuleBayTemplate.objects.create(
  1768. module_type=module_type,
  1769. name='Sub-bay {module}-1',
  1770. position='{module}-1'
  1771. )
  1772. device = Device.objects.create(
  1773. name='Position Test Device',
  1774. device_type=device_type,
  1775. role=device_role,
  1776. site=site
  1777. )
  1778. module_bay = device.modulebays.get(name='Slot 1')
  1779. module = Module.objects.create(
  1780. device=device,
  1781. module_bay=module_bay,
  1782. module_type=module_type
  1783. )
  1784. nested_bay = module.modulebays.get(name='Sub-bay 1-1')
  1785. self.assertEqual(nested_bay.position, '1-1')
  1786. #
  1787. # Position inheritance tests (#19796)
  1788. #
  1789. def test_position_inheritance_depth_2(self):
  1790. """
  1791. A module bay with position '{module}/2' under a parent bay with position '1'
  1792. should resolve to position '1/2'. A single {module} in the interface template
  1793. should then resolve to '1/2'.
  1794. """
  1795. manufacturer = Manufacturer.objects.first()
  1796. site = Site.objects.first()
  1797. device_role = DeviceRole.objects.first()
  1798. device_type = DeviceType.objects.create(
  1799. manufacturer=manufacturer,
  1800. model='Chassis for Inheritance',
  1801. slug='chassis-for-inheritance'
  1802. )
  1803. ModuleBayTemplate.objects.create(
  1804. device_type=device_type,
  1805. name='Line card slot 1',
  1806. position='1'
  1807. )
  1808. line_card_type = ModuleType.objects.create(
  1809. manufacturer=manufacturer,
  1810. model='Line Card with Inherited Bays'
  1811. )
  1812. ModuleBayTemplate.objects.create(
  1813. module_type=line_card_type,
  1814. name='SFP bay {module}/1',
  1815. position='{module}/1'
  1816. )
  1817. ModuleBayTemplate.objects.create(
  1818. module_type=line_card_type,
  1819. name='SFP bay {module}/2',
  1820. position='{module}/2'
  1821. )
  1822. sfp_type = ModuleType.objects.create(
  1823. manufacturer=manufacturer,
  1824. model='SFP with Inherited Path'
  1825. )
  1826. InterfaceTemplate.objects.create(
  1827. module_type=sfp_type,
  1828. name='SFP {module}',
  1829. type=InterfaceTypeChoices.TYPE_10GE_SFP_PLUS
  1830. )
  1831. device = Device.objects.create(
  1832. name='Inheritance Chassis',
  1833. device_type=device_type,
  1834. role=device_role,
  1835. site=site
  1836. )
  1837. lc_bay = device.modulebays.get(name='Line card slot 1')
  1838. line_card = Module.objects.create(
  1839. device=device,
  1840. module_bay=lc_bay,
  1841. module_type=line_card_type
  1842. )
  1843. sfp_bay = line_card.modulebays.get(name='SFP bay 1/2')
  1844. sfp_module = Module.objects.create(
  1845. device=device,
  1846. module_bay=sfp_bay,
  1847. module_type=sfp_type
  1848. )
  1849. interface = sfp_module.interfaces.first()
  1850. self.assertEqual(interface.name, 'SFP 1/2')
  1851. def test_position_inheritance_depth_3(self):
  1852. """
  1853. Position inheritance at depth 3: positions should chain through the tree.
  1854. """
  1855. manufacturer = Manufacturer.objects.first()
  1856. site = Site.objects.first()
  1857. device_role = DeviceRole.objects.first()
  1858. device_type = DeviceType.objects.create(
  1859. manufacturer=manufacturer,
  1860. model='Deep Chassis',
  1861. slug='deep-chassis'
  1862. )
  1863. ModuleBayTemplate.objects.create(
  1864. device_type=device_type,
  1865. name='Slot A',
  1866. position='A'
  1867. )
  1868. mid_type = ModuleType.objects.create(
  1869. manufacturer=manufacturer,
  1870. model='Mid Module'
  1871. )
  1872. ModuleBayTemplate.objects.create(
  1873. module_type=mid_type,
  1874. name='Sub {module}-1',
  1875. position='{module}-1'
  1876. )
  1877. leaf_type = ModuleType.objects.create(
  1878. manufacturer=manufacturer,
  1879. model='Leaf Module'
  1880. )
  1881. InterfaceTemplate.objects.create(
  1882. module_type=leaf_type,
  1883. name='Port {module}',
  1884. type=InterfaceTypeChoices.TYPE_1GE_FIXED
  1885. )
  1886. device = Device.objects.create(
  1887. name='Deep Device',
  1888. device_type=device_type,
  1889. role=device_role,
  1890. site=site
  1891. )
  1892. slot_a = device.modulebays.get(name='Slot A')
  1893. mid_module = Module.objects.create(
  1894. device=device,
  1895. module_bay=slot_a,
  1896. module_type=mid_type
  1897. )
  1898. sub_bay = mid_module.modulebays.get(name='Sub A-1')
  1899. self.assertEqual(sub_bay.position, 'A-1')
  1900. leaf_module = Module.objects.create(
  1901. device=device,
  1902. module_bay=sub_bay,
  1903. module_type=leaf_type
  1904. )
  1905. interface = leaf_module.interfaces.first()
  1906. self.assertEqual(interface.name, 'Port A-1')
  1907. def test_position_inheritance_custom_separator(self):
  1908. """
  1909. Users control the separator through the position field template.
  1910. Using '.' instead of '/' should work correctly.
  1911. """
  1912. manufacturer = Manufacturer.objects.first()
  1913. site = Site.objects.first()
  1914. device_role = DeviceRole.objects.first()
  1915. device_type = DeviceType.objects.create(
  1916. manufacturer=manufacturer,
  1917. model='Dot Separator Chassis',
  1918. slug='dot-separator-chassis'
  1919. )
  1920. ModuleBayTemplate.objects.create(
  1921. device_type=device_type,
  1922. name='Bay 1',
  1923. position='1'
  1924. )
  1925. card_type = ModuleType.objects.create(
  1926. manufacturer=manufacturer,
  1927. model='Card with Dot Separator'
  1928. )
  1929. ModuleBayTemplate.objects.create(
  1930. module_type=card_type,
  1931. name='Port {module}.1',
  1932. position='{module}.1'
  1933. )
  1934. sfp_type = ModuleType.objects.create(
  1935. manufacturer=manufacturer,
  1936. model='SFP Dot'
  1937. )
  1938. InterfaceTemplate.objects.create(
  1939. module_type=sfp_type,
  1940. name='eth{module}',
  1941. type=InterfaceTypeChoices.TYPE_10GE_SFP_PLUS
  1942. )
  1943. device = Device.objects.create(
  1944. name='Dot Device',
  1945. device_type=device_type,
  1946. role=device_role,
  1947. site=site
  1948. )
  1949. bay = device.modulebays.get(name='Bay 1')
  1950. card = Module.objects.create(
  1951. device=device,
  1952. module_bay=bay,
  1953. module_type=card_type
  1954. )
  1955. port_bay = card.modulebays.get(name='Port 1.1')
  1956. sfp = Module.objects.create(
  1957. device=device,
  1958. module_bay=port_bay,
  1959. module_type=sfp_type
  1960. )
  1961. interface = sfp.interfaces.first()
  1962. self.assertEqual(interface.name, 'eth1.1')
  1963. def test_multi_token_backwards_compat(self):
  1964. """
  1965. Multi-token {module}/{module} at matching depth should still resolve
  1966. level-by-level (backwards compatibility).
  1967. """
  1968. manufacturer = Manufacturer.objects.first()
  1969. site = Site.objects.first()
  1970. device_role = DeviceRole.objects.first()
  1971. device_type = DeviceType.objects.create(
  1972. manufacturer=manufacturer,
  1973. model='Multi Token Chassis',
  1974. slug='multi-token-chassis'
  1975. )
  1976. ModuleBayTemplate.objects.create(
  1977. device_type=device_type,
  1978. name='Slot 1',
  1979. position='1'
  1980. )
  1981. card_type = ModuleType.objects.create(
  1982. manufacturer=manufacturer,
  1983. model='Card for Multi Token'
  1984. )
  1985. ModuleBayTemplate.objects.create(
  1986. module_type=card_type,
  1987. name='Port 1',
  1988. position='2'
  1989. )
  1990. iface_type = ModuleType.objects.create(
  1991. manufacturer=manufacturer,
  1992. model='Interface Module Multi Token'
  1993. )
  1994. InterfaceTemplate.objects.create(
  1995. module_type=iface_type,
  1996. name='Gi{module}/{module}',
  1997. type=InterfaceTypeChoices.TYPE_1GE_FIXED
  1998. )
  1999. device = Device.objects.create(
  2000. name='Multi Token Device',
  2001. device_type=device_type,
  2002. role=device_role,
  2003. site=site
  2004. )
  2005. slot = device.modulebays.get(name='Slot 1')
  2006. card = Module.objects.create(
  2007. device=device,
  2008. module_bay=slot,
  2009. module_type=card_type
  2010. )
  2011. port = card.modulebays.get(name='Port 1')
  2012. iface_module = Module.objects.create(
  2013. device=device,
  2014. module_bay=port,
  2015. module_type=iface_type
  2016. )
  2017. interface = iface_module.interfaces.first()
  2018. self.assertEqual(interface.name, 'Gi1/2')
  2019. @tag('regression') # #23478
  2020. def test_module_token_depth_mismatch_in_label_raises_abort_request(self):
  2021. """An unresolvable {module} label aborts a direct module install with AbortRequest."""
  2022. device = Device.objects.first()
  2023. module_bay = ModuleBay.objects.create(device=device, name='Token Label Bay', position='1')
  2024. module_type = ModuleType.objects.create(manufacturer=Manufacturer.objects.first(), model='Token Label Type')
  2025. InterfaceTemplate.objects.create(
  2026. module_type=module_type, name='eth0', label='{module}/{module}', type=InterfaceTypeChoices.TYPE_1GE_FIXED
  2027. )
  2028. module = Module(device=device, module_bay=module_bay, module_type=module_type)
  2029. with self.assertRaises(AbortRequest) as cm:
  2030. module.save()
  2031. self.assertIn('2 placeholders given', cm.exception.message)
  2032. @tag('regression') # #23478
  2033. def test_module_token_without_bay_position_raises_abort_request(self):
  2034. """A {module} name in a bay without a position aborts a direct module install with AbortRequest."""
  2035. device = Device.objects.first()
  2036. module_bay = ModuleBay.objects.create(device=device, name='Token Name Bay')
  2037. module_type = ModuleType.objects.create(manufacturer=Manufacturer.objects.first(), model='Token Name Type')
  2038. InterfaceTemplate.objects.create(
  2039. module_type=module_type, name='eth{module}', type=InterfaceTypeChoices.TYPE_1GE_FIXED
  2040. )
  2041. module = Module(device=device, module_bay=module_bay, module_type=module_type)
  2042. with self.assertRaises(AbortRequest) as cm:
  2043. module.save()
  2044. self.assertIn('no position defined', cm.exception.message)
  2045. @tag('regression') # #23478
  2046. def test_module_token_without_positions_raises_value_error(self):
  2047. """A {module} token with no bay position to resolve against raises ValueError."""
  2048. with self.assertRaises(ValueError) as cm:
  2049. resolve_module_placeholder('eth{module}', [])
  2050. self.assertIn('no position defined', str(cm.exception))
  2051. @tag('regression') # #20912
  2052. def test_module_bay_parent_cleared_when_module_removed(self):
  2053. """Test that the parent field is properly cleared when a module bay's module assignment is removed"""
  2054. device = Device.objects.first()
  2055. manufacturer = Manufacturer.objects.first()
  2056. module_type = ModuleType.objects.create(manufacturer=manufacturer, model='Test Module Type')
  2057. bay1 = ModuleBay.objects.create(device=device, name='Test Bay 1')
  2058. bay2 = ModuleBay.objects.create(device=device, name='Test Bay 2')
  2059. # Install a module in bay1
  2060. module1 = Module.objects.create(device=device, module_bay=bay1, module_type=module_type)
  2061. # Assign bay2 to module1 and verify parent is now set to bay1 (module1's bay)
  2062. bay2.module = module1
  2063. bay2.save()
  2064. bay2.refresh_from_db()
  2065. self.assertEqual(bay2.parent, bay1)
  2066. self.assertEqual(bay2.module, module1)
  2067. # Clear the module assignment (return bay2 to device level) Verify parent is cleared
  2068. bay2.module = None
  2069. bay2.save()
  2070. bay2.refresh_from_db()
  2071. self.assertIsNone(bay2.parent)
  2072. self.assertIsNone(bay2.module)
  2073. def test_module_installation_creates_port_mappings(self):
  2074. """
  2075. Test that installing a module with front/rear port templates correctly
  2076. creates PortMapping instances for the device.
  2077. """
  2078. device = Device.objects.first()
  2079. manufacturer = Manufacturer.objects.first()
  2080. module_bay = ModuleBay.objects.create(device=device, name='Test Bay PortMapping 1')
  2081. # Create a module type with a rear port template
  2082. module_type_with_mappings = ModuleType.objects.create(
  2083. manufacturer=manufacturer,
  2084. model='Module Type With Mappings',
  2085. )
  2086. # Create a rear port template with 12 positions (splice)
  2087. rear_port_template = RearPortTemplate.objects.create(
  2088. module_type=module_type_with_mappings,
  2089. name='Rear Port 1',
  2090. type=PortTypeChoices.TYPE_SPLICE,
  2091. positions=12,
  2092. )
  2093. # Create 12 front port templates mapped to the rear port
  2094. front_port_templates = []
  2095. for i in range(1, 13):
  2096. front_port_template = FrontPortTemplate.objects.create(
  2097. module_type=module_type_with_mappings,
  2098. name=f'port {i}',
  2099. type=PortTypeChoices.TYPE_LC,
  2100. positions=1,
  2101. )
  2102. front_port_templates.append(front_port_template)
  2103. # Create port template mapping
  2104. PortTemplateMapping.objects.create(
  2105. device_type=None,
  2106. module_type=module_type_with_mappings,
  2107. front_port=front_port_template,
  2108. front_port_position=1,
  2109. rear_port=rear_port_template,
  2110. rear_port_position=i,
  2111. )
  2112. # Install the module
  2113. module = Module.objects.create(
  2114. device=device,
  2115. module_bay=module_bay,
  2116. module_type=module_type_with_mappings,
  2117. status=ModuleStatusChoices.STATUS_ACTIVE,
  2118. )
  2119. # Verify that front ports were created
  2120. front_ports = FrontPort.objects.filter(device=device, module=module)
  2121. self.assertEqual(front_ports.count(), 12)
  2122. # Verify that the rear port was created
  2123. rear_ports = RearPort.objects.filter(device=device, module=module)
  2124. self.assertEqual(rear_ports.count(), 1)
  2125. rear_port = rear_ports.first()
  2126. self.assertEqual(rear_port.positions, 12)
  2127. # Verify that port mappings were created
  2128. port_mappings = PortMapping.objects.filter(front_port__module=module)
  2129. self.assertEqual(port_mappings.count(), 12)
  2130. # Verify each mapping is correct
  2131. for i, front_port_template in enumerate(front_port_templates, start=1):
  2132. front_port = FrontPort.objects.get(
  2133. device=device,
  2134. name=front_port_template.name,
  2135. module=module,
  2136. )
  2137. # Check that a mapping exists for this front port
  2138. mapping = PortMapping.objects.get(
  2139. device=device,
  2140. front_port=front_port,
  2141. front_port_position=1,
  2142. )
  2143. self.assertEqual(mapping.rear_port, rear_port)
  2144. self.assertEqual(mapping.front_port_position, 1)
  2145. self.assertEqual(mapping.rear_port_position, i)
  2146. def test_module_installation_without_mappings(self):
  2147. """
  2148. Test that installing a module without port template mappings
  2149. doesn't create any PortMapping instances.
  2150. """
  2151. device = Device.objects.first()
  2152. manufacturer = Manufacturer.objects.first()
  2153. module_bay = ModuleBay.objects.create(device=device, name='Test Bay PortMapping 2')
  2154. # Create a module type without any port template mappings
  2155. module_type_no_mappings = ModuleType.objects.create(
  2156. manufacturer=manufacturer,
  2157. model='Module Type Without Mappings',
  2158. )
  2159. # Create a rear port template
  2160. RearPortTemplate.objects.create(
  2161. module_type=module_type_no_mappings,
  2162. name='Rear Port 1',
  2163. type=PortTypeChoices.TYPE_SPLICE,
  2164. positions=12,
  2165. )
  2166. # Create front port templates but DO NOT create PortTemplateMapping rows
  2167. for i in range(1, 13):
  2168. FrontPortTemplate.objects.create(
  2169. module_type=module_type_no_mappings,
  2170. name=f'port {i}',
  2171. type=PortTypeChoices.TYPE_LC,
  2172. positions=1,
  2173. )
  2174. # Install the module
  2175. module = Module.objects.create(
  2176. device=device,
  2177. module_bay=module_bay,
  2178. module_type=module_type_no_mappings,
  2179. status=ModuleStatusChoices.STATUS_ACTIVE,
  2180. )
  2181. # Verify no port mappings were created for this module
  2182. port_mappings = PortMapping.objects.filter(
  2183. device=device,
  2184. front_port__module=module,
  2185. front_port_position=1,
  2186. )
  2187. self.assertEqual(port_mappings.count(), 0)
  2188. self.assertEqual(FrontPort.objects.filter(module=module).count(), 12)
  2189. self.assertEqual(RearPort.objects.filter(module=module).count(), 1)
  2190. self.assertEqual(PortMapping.objects.filter(front_port__module=module).count(), 0)
  2191. def test_cannot_install_module_in_disabled_bay(self):
  2192. """
  2193. Test that a Module cannot be installed into a disabled ModuleBay.
  2194. """
  2195. device = Device.objects.first()
  2196. manufacturer = Manufacturer.objects.first()
  2197. module_type = ModuleType.objects.create(manufacturer=manufacturer, model='Test Module Type Disabled')
  2198. # Create a disabled module bay
  2199. disabled_bay = ModuleBay.objects.create(device=device, name='Disabled Bay', enabled=False)
  2200. # Attempt to install a module into the disabled bay
  2201. module = Module(device=device, module_bay=disabled_bay, module_type=module_type)
  2202. with self.assertRaises(ValidationError) as cm:
  2203. module.clean()
  2204. self.assertIn('module_bay', cm.exception.message_dict)
  2205. self.assertIn('disabled module bay', str(cm.exception.message_dict['module_bay']))
  2206. class ModuleBayTypeCompatibilityTestCase(TestCase):
  2207. """Tests for bay type compatibility: Module.is_bay_compatible, ModuleType.get_incompatible_modules,
  2208. ModuleBay.is_module_compatible, and Module.clean() validation."""
  2209. @classmethod
  2210. def setUpTestData(cls):
  2211. site = Site.objects.create(name='Compat Site', slug='compat-site')
  2212. manufacturer = Manufacturer.objects.create(name='Compat Mfr', slug='compat-mfr')
  2213. device_type = DeviceType.objects.create(
  2214. manufacturer=manufacturer, model='Compat Device Type', slug='compat-dt'
  2215. )
  2216. device_role = DeviceRole.objects.create(name='Compat Role', slug='compat-role')
  2217. cls.device = Device.objects.create(
  2218. name='Compat Device', device_type=device_type, role=device_role, site=site
  2219. )
  2220. cls.bay_type_a = ModuleBayType.objects.create(
  2221. manufacturer=manufacturer, name='Bay Type A', slug='bay-type-a'
  2222. )
  2223. cls.bay_type_b = ModuleBayType.objects.create(
  2224. manufacturer=manufacturer, name='Bay Type B', slug='bay-type-b'
  2225. )
  2226. cls.module_type_a = ModuleType.objects.create(manufacturer=manufacturer, model='Module Type A')
  2227. cls.module_type_a.module_bay_types.set([cls.bay_type_a])
  2228. cls.module_type_b = ModuleType.objects.create(manufacturer=manufacturer, model='Module Type B')
  2229. cls.module_type_b.module_bay_types.set([cls.bay_type_b])
  2230. cls.module_type_any = ModuleType.objects.create(manufacturer=manufacturer, model='Module Type Any')
  2231. def _make_bay(self, name, *bay_types):
  2232. bay = ModuleBay.objects.create(device=self.device, name=name)
  2233. if bay_types:
  2234. bay.module_bay_types.set(bay_types)
  2235. return bay
  2236. def _install(self, bay, module_type):
  2237. return Module.objects.create(device=self.device, module_bay=bay, module_type=module_type)
  2238. # --- Module.clean() validation ---
  2239. def test_clean_blocks_incompatible_install(self):
  2240. """Module.clean() raises ValidationError when bay and module type have disjoint type sets."""
  2241. bay = self._make_bay('Bay Compat 1', self.bay_type_b)
  2242. module = Module(device=self.device, module_bay=bay, module_type=self.module_type_a)
  2243. with self.assertRaises(ValidationError):
  2244. module.clean()
  2245. def test_clean_allows_compatible_install(self):
  2246. """Module.clean() passes when bay and module type share at least one bay type."""
  2247. bay = self._make_bay('Bay Compat 2', self.bay_type_a)
  2248. module = Module(device=self.device, module_bay=bay, module_type=self.module_type_a)
  2249. module.clean() # should not raise
  2250. def test_clean_allows_unconstrained_module_type(self):
  2251. """Module.clean() passes when the module type has no bay type constraints."""
  2252. bay = self._make_bay('Bay Compat 3', self.bay_type_a)
  2253. module = Module(device=self.device, module_bay=bay, module_type=self.module_type_any)
  2254. module.clean() # should not raise
  2255. def test_clean_allows_unconstrained_bay(self):
  2256. """Module.clean() passes when the bay has no bay type constraints."""
  2257. bay = self._make_bay('Bay Compat 4')
  2258. module = Module(device=self.device, module_bay=bay, module_type=self.module_type_a)
  2259. module.clean() # should not raise
  2260. # --- Module.is_bay_compatible ---
  2261. def test_is_bay_compatible_false_when_disjoint(self):
  2262. """Module.is_bay_compatible returns False when bay and module type sets are disjoint."""
  2263. bay = self._make_bay('Bay Compat 5', self.bay_type_b)
  2264. # Bypass clean() to create an incompatible installation for testing the property
  2265. module = Module.objects.create(device=self.device, module_bay=bay, module_type=self.module_type_a)
  2266. module.refresh_from_db()
  2267. self.assertFalse(module.is_bay_compatible)
  2268. def test_is_bay_compatible_true_when_overlapping(self):
  2269. """Module.is_bay_compatible returns True when bay and module type share a bay type."""
  2270. bay = self._make_bay('Bay Compat 6', self.bay_type_a)
  2271. module = self._install(bay, self.module_type_a)
  2272. self.assertTrue(module.is_bay_compatible)
  2273. def test_is_bay_compatible_true_when_module_type_unconstrained(self):
  2274. """Module.is_bay_compatible returns True when module type has no constraints."""
  2275. bay = self._make_bay('Bay Compat 7', self.bay_type_a)
  2276. module = self._install(bay, self.module_type_any)
  2277. self.assertTrue(module.is_bay_compatible)
  2278. def test_is_bay_compatible_true_when_bay_unconstrained(self):
  2279. """Module.is_bay_compatible returns True when bay has no constraints."""
  2280. bay = self._make_bay('Bay Compat 8')
  2281. module = self._install(bay, self.module_type_a)
  2282. self.assertTrue(module.is_bay_compatible)
  2283. # --- ModuleType.get_incompatible_modules ---
  2284. def test_get_incompatible_modules_returns_incompatible(self):
  2285. """ModuleType.get_incompatible_modules includes modules in bays with disjoint type sets."""
  2286. bay = self._make_bay('Bay Compat 9', self.bay_type_b)
  2287. module = Module.objects.create(device=self.device, module_bay=bay, module_type=self.module_type_a)
  2288. qs = self.module_type_a.get_incompatible_modules()
  2289. self.assertIn(module, qs)
  2290. def test_get_incompatible_modules_excludes_compatible(self):
  2291. """ModuleType.get_incompatible_modules excludes modules in bays with matching type sets."""
  2292. bay = self._make_bay('Bay Compat 10', self.bay_type_a)
  2293. module = self._install(bay, self.module_type_a)
  2294. qs = self.module_type_a.get_incompatible_modules()
  2295. self.assertNotIn(module, qs)
  2296. def test_get_incompatible_modules_excludes_unconstrained_bay(self):
  2297. """ModuleType.get_incompatible_modules excludes modules in unconstrained bays."""
  2298. bay = self._make_bay('Bay Compat 11')
  2299. module = self._install(bay, self.module_type_a)
  2300. qs = self.module_type_a.get_incompatible_modules()
  2301. self.assertNotIn(module, qs)
  2302. def test_get_incompatible_modules_empty_when_type_unconstrained(self):
  2303. """ModuleType.get_incompatible_modules returns empty queryset when type has no constraints."""
  2304. bay = self._make_bay('Bay Compat 12', self.bay_type_a)
  2305. self._install(bay, self.module_type_any)
  2306. qs = self.module_type_any.get_incompatible_modules()
  2307. self.assertFalse(qs.exists())
  2308. # --- ModuleBay.is_module_compatible ---
  2309. def test_bay_is_module_compatible_false_when_disjoint(self):
  2310. """ModuleBay.is_module_compatible returns False when bay and installed module sets are disjoint."""
  2311. bay = self._make_bay('Bay Compat 13', self.bay_type_b)
  2312. Module.objects.create(device=self.device, module_bay=bay, module_type=self.module_type_a)
  2313. bay.refresh_from_db()
  2314. self.assertFalse(bay.is_module_compatible)
  2315. def test_bay_is_module_compatible_true_when_overlapping(self):
  2316. """ModuleBay.is_module_compatible returns True when sets overlap."""
  2317. bay = self._make_bay('Bay Compat 14', self.bay_type_a)
  2318. self._install(bay, self.module_type_a)
  2319. bay.refresh_from_db()
  2320. self.assertTrue(bay.is_module_compatible)
  2321. def test_bay_is_module_compatible_true_when_no_module(self):
  2322. """ModuleBay.is_module_compatible returns True when nothing is installed."""
  2323. bay = self._make_bay('Bay Compat 15', self.bay_type_a)
  2324. self.assertTrue(bay.is_module_compatible)
  2325. def test_bay_is_module_compatible_true_when_bay_unconstrained(self):
  2326. """ModuleBay.is_module_compatible returns True when bay has no constraints."""
  2327. bay = self._make_bay('Bay Compat 16')
  2328. Module.objects.create(device=self.device, module_bay=bay, module_type=self.module_type_a)
  2329. bay.refresh_from_db()
  2330. self.assertTrue(bay.is_module_compatible)
  2331. class CableTestCase(TestCase):
  2332. @classmethod
  2333. def setUpTestData(cls):
  2334. site = Site.objects.create(name='Test Site 1', slug='test-site-1')
  2335. manufacturer = Manufacturer.objects.create(name='Test Manufacturer 1', slug='test-manufacturer-1')
  2336. devicetype = DeviceType.objects.create(
  2337. manufacturer=manufacturer, model='Test Device Type 1', slug='test-device-type-1'
  2338. )
  2339. role = DeviceRole.objects.create(
  2340. name='Test Device Role 1', slug='test-device-role-1', color='ff0000'
  2341. )
  2342. device1 = Device.objects.create(
  2343. device_type=devicetype, role=role, name='TestDevice1', site=site
  2344. )
  2345. device2 = Device.objects.create(
  2346. device_type=devicetype, role=role, name='TestDevice2', site=site
  2347. )
  2348. interfaces = (
  2349. Interface(device=device1, name='eth0'),
  2350. Interface(device=device2, name='eth0'),
  2351. Interface(device=device2, name='eth1'),
  2352. )
  2353. Interface.objects.bulk_create(interfaces)
  2354. Cable(a_terminations=[interfaces[0]], b_terminations=[interfaces[1]]).save()
  2355. PowerPort.objects.create(device=device2, name='psu1')
  2356. patch_panel = Device.objects.create(
  2357. device_type=devicetype, role=role, name='TestPatchPanel', site=site
  2358. )
  2359. rear_ports = (
  2360. RearPort(device=patch_panel, name='RP1', type='8p8c'),
  2361. RearPort(device=patch_panel, name='RP2', type='8p8c', positions=2),
  2362. RearPort(device=patch_panel, name='RP3', type='8p8c', positions=3),
  2363. RearPort(device=patch_panel, name='RP4', type='8p8c', positions=3),
  2364. )
  2365. RearPort.objects.bulk_create(rear_ports)
  2366. front_ports = (
  2367. FrontPort(device=patch_panel, name='FP1', type='8p8c'),
  2368. FrontPort(device=patch_panel, name='FP2', type='8p8c'),
  2369. FrontPort(device=patch_panel, name='FP3', type='8p8c'),
  2370. FrontPort(device=patch_panel, name='FP4', type='8p8c'),
  2371. )
  2372. FrontPort.objects.bulk_create(front_ports)
  2373. PortMapping.objects.bulk_create([
  2374. PortMapping(device=patch_panel, front_port=front_ports[0], rear_port=rear_ports[0]),
  2375. PortMapping(device=patch_panel, front_port=front_ports[1], rear_port=rear_ports[1]),
  2376. PortMapping(device=patch_panel, front_port=front_ports[2], rear_port=rear_ports[2]),
  2377. PortMapping(device=patch_panel, front_port=front_ports[3], rear_port=rear_ports[3]),
  2378. ])
  2379. provider = Provider.objects.create(name='Provider 1', slug='provider-1')
  2380. provider_network = ProviderNetwork.objects.create(name='Provider Network 1', provider=provider)
  2381. circuittype = CircuitType.objects.create(name='Circuit Type 1', slug='circuit-type-1')
  2382. circuit1 = Circuit.objects.create(provider=provider, type=circuittype, cid='1')
  2383. circuit2 = Circuit.objects.create(provider=provider, type=circuittype, cid='2')
  2384. CircuitTermination.objects.create(circuit=circuit1, termination=site, term_side='A')
  2385. CircuitTermination.objects.create(circuit=circuit1, termination=site, term_side='Z')
  2386. CircuitTermination.objects.create(circuit=circuit2, termination=provider_network, term_side='A')
  2387. def test_cable_creation(self):
  2388. """
  2389. When a new Cable is created, it must be cached on either termination point.
  2390. """
  2391. interface1 = Interface.objects.get(device__name='TestDevice1', name='eth0')
  2392. interface2 = Interface.objects.get(device__name='TestDevice2', name='eth0')
  2393. cable = Cable.objects.first()
  2394. self.assertEqual(interface1.cable, cable)
  2395. self.assertEqual(interface2.cable, cable)
  2396. self.assertEqual(interface1.cable_end, 'A')
  2397. self.assertEqual(interface2.cable_end, 'B')
  2398. self.assertEqual(interface1.link_peers, [interface2])
  2399. self.assertEqual(interface2.link_peers, [interface1])
  2400. def test_cable_deletion(self):
  2401. """
  2402. When a Cable is deleted, the `cable` field on its termination points must be nullified. The str() method
  2403. should still return the PK of the string even after being nullified.
  2404. """
  2405. interface1 = Interface.objects.get(device__name='TestDevice1', name='eth0')
  2406. interface2 = Interface.objects.get(device__name='TestDevice2', name='eth0')
  2407. cable = Cable.objects.first()
  2408. cable.delete()
  2409. self.assertIsNone(cable.pk)
  2410. self.assertNotEqual(str(cable), '#None')
  2411. interface1 = Interface.objects.get(pk=interface1.pk)
  2412. self.assertIsNone(interface1.cable)
  2413. self.assertListEqual(interface1.link_peers, [])
  2414. interface2 = Interface.objects.get(pk=interface2.pk)
  2415. self.assertIsNone(interface2.cable)
  2416. self.assertListEqual(interface2.link_peers, [])
  2417. def test_cable_validates_same_parent_object(self):
  2418. """
  2419. The clean method should ensure that all terminations at either end of a Cable belong to the same parent object.
  2420. """
  2421. interface1 = Interface.objects.get(device__name='TestDevice1', name='eth0')
  2422. powerport1 = PowerPort.objects.get(device__name='TestDevice2', name='psu1')
  2423. cable = Cable(a_terminations=[interface1], b_terminations=[powerport1])
  2424. with self.assertRaises(ValidationError):
  2425. cable.clean()
  2426. def test_cable_validates_same_type(self):
  2427. """
  2428. The clean method should ensure that all terminations at either end of a Cable are of the same type.
  2429. """
  2430. interface1 = Interface.objects.get(device__name='TestDevice1', name='eth0')
  2431. frontport1 = FrontPort.objects.get(device__name='TestPatchPanel', name='FP1')
  2432. rearport1 = RearPort.objects.get(device__name='TestPatchPanel', name='RP1')
  2433. cable = Cable(a_terminations=[frontport1, rearport1], b_terminations=[interface1])
  2434. with self.assertRaises(ValidationError):
  2435. cable.clean()
  2436. def test_cable_validates_compatible_types(self):
  2437. """
  2438. The clean method should have a check to ensure only compatible port types can be connected by a cable
  2439. """
  2440. interface1 = Interface.objects.get(device__name='TestDevice1', name='eth0')
  2441. powerport1 = PowerPort.objects.get(device__name='TestDevice2', name='psu1')
  2442. # An interface cannot be connected to a power port, for example
  2443. cable = Cable(a_terminations=[interface1], b_terminations=[powerport1])
  2444. with self.assertRaises(ValidationError):
  2445. cable.clean()
  2446. def test_cable_cannot_terminate_to_a_provider_network_circuittermination(self):
  2447. """
  2448. Neither side of a cable can be terminated to a CircuitTermination which is attached to a ProviderNetwork
  2449. """
  2450. interface3 = Interface.objects.get(device__name='TestDevice2', name='eth1')
  2451. circuittermination3 = CircuitTermination.objects.get(circuit__cid='2', term_side='A')
  2452. cable = Cable(a_terminations=[interface3], b_terminations=[circuittermination3])
  2453. with self.assertRaises(ValidationError):
  2454. cable.clean()
  2455. def test_cable_cannot_terminate_to_a_virtual_interface(self):
  2456. """
  2457. A cable cannot terminate to a virtual interface
  2458. """
  2459. device1 = Device.objects.get(name='TestDevice1')
  2460. interface2 = Interface.objects.get(device__name='TestDevice2', name='eth0')
  2461. virtual_interface = Interface(device=device1, name="V1", type=InterfaceTypeChoices.TYPE_VIRTUAL)
  2462. cable = Cable(a_terminations=[interface2], b_terminations=[virtual_interface])
  2463. with self.assertRaises(ValidationError):
  2464. cable.clean()
  2465. def test_cable_cannot_terminate_to_a_wireless_interface(self):
  2466. """
  2467. A cable cannot terminate to a wireless interface
  2468. """
  2469. device1 = Device.objects.get(name='TestDevice1')
  2470. interface2 = Interface.objects.get(device__name='TestDevice2', name='eth0')
  2471. wireless_interface = Interface(device=device1, name="W1", type=InterfaceTypeChoices.TYPE_80211A)
  2472. cable = Cable(a_terminations=[interface2], b_terminations=[wireless_interface])
  2473. with self.assertRaises(ValidationError):
  2474. cable.clean()
  2475. @tag('regression')
  2476. def test_cable_cannot_terminate_to_a_cellular_interface(self):
  2477. """
  2478. A cable cannot terminate to a cellular interface
  2479. """
  2480. device1 = Device.objects.get(name='TestDevice1')
  2481. interface2 = Interface.objects.get(device__name='TestDevice2', name='eth0')
  2482. cellular_interface = Interface(device=device1, name="W1", type=InterfaceTypeChoices.TYPE_LTE)
  2483. cable = Cable(a_terminations=[interface2], b_terminations=[cellular_interface])
  2484. with self.assertRaises(ValidationError):
  2485. cable.clean()
  2486. def test_cannot_cable_to_mark_connected(self):
  2487. """
  2488. Test that a cable cannot be connected to an interface marked as connected.
  2489. """
  2490. device1 = Device.objects.get(name='TestDevice1')
  2491. interface1 = Interface.objects.get(device__name='TestDevice2', name='eth1')
  2492. mark_connected_interface = Interface(device=device1, name='mark_connected1', mark_connected=True)
  2493. cable = Cable(a_terminations=[mark_connected_interface], b_terminations=[interface1])
  2494. with self.assertRaises(ValidationError):
  2495. cable.clean()
  2496. def test_partial_save_does_not_apply_an_unwritten_profile(self):
  2497. """
  2498. A save excluding profile must leave the terminations alone but keep the change pending.
  2499. """
  2500. cable = Cable.objects.first()
  2501. interface1 = Interface.objects.get(device__name='TestDevice1', name='eth0')
  2502. termination_pks = set(CableTermination.objects.filter(cable=cable).values_list('pk', flat=True))
  2503. cable.profile = CableProfileChoices.SINGLE_1C1P
  2504. cable.save(update_fields=['label'])
  2505. interface1.refresh_from_db()
  2506. # Requery rather than refresh, so the pending profile stays on the instance under test
  2507. self.assertEqual(Cable.objects.get(pk=cable.pk).profile, '')
  2508. self.assertIsNone(interface1.cable_connector)
  2509. self.assertEqual(
  2510. set(CableTermination.objects.filter(cable=cable).values_list('pk', flat=True)),
  2511. termination_pks
  2512. )
  2513. # _orig_profile was not advanced, so the pending change still applies here
  2514. cable.save()
  2515. interface1.refresh_from_db()
  2516. self.assertEqual(Cable.objects.get(pk=cable.pk).profile, CableProfileChoices.SINGLE_1C1P)
  2517. self.assertEqual(interface1.cable_connector, 1)
  2518. def test_cable_profile_change_preserves_terminations(self):
  2519. """
  2520. When a Cable's profile is changed via save() without explicitly setting terminations (as happens during
  2521. bulk edit), the existing termination points must be preserved.
  2522. """
  2523. cable = Cable.objects.first()
  2524. interface1 = Interface.objects.get(device__name='TestDevice1', name='eth0')
  2525. interface2 = Interface.objects.get(device__name='TestDevice2', name='eth0')
  2526. # Verify initial state: cable has terminations and no profile
  2527. self.assertEqual(cable.profile, '')
  2528. self.assertEqual(CableTermination.objects.filter(cable=cable).count(), 2)
  2529. # Simulate what bulk edit does: load the cable from DB, set profile via setattr, and save.
  2530. # Crucially, do NOT set a_terminations or b_terminations on the instance.
  2531. cable_from_db = Cable.objects.get(pk=cable.pk)
  2532. cable_from_db.profile = CableProfileChoices.SINGLE_1C1P
  2533. cable_from_db.save()
  2534. # Verify terminations are preserved
  2535. self.assertEqual(CableTermination.objects.filter(cable=cable).count(), 2)
  2536. # Verify the correct interfaces are still terminated
  2537. cable_from_db.refresh_from_db()
  2538. a_terms = [ct.termination for ct in CableTermination.objects.filter(cable=cable, cable_end='A')]
  2539. b_terms = [ct.termination for ct in CableTermination.objects.filter(cable=cable, cable_end='B')]
  2540. self.assertEqual(a_terms, [interface1])
  2541. self.assertEqual(b_terms, [interface2])
  2542. def _create_multiposition_cable(self, count=4):
  2543. """
  2544. Create a cable with `count` terminations at either end, using the 4C1P trunk profile. Returns
  2545. the cable and its A & B terminating objects.
  2546. """
  2547. device1 = Device.objects.get(name='TestDevice1')
  2548. device2 = Device.objects.get(name='TestDevice2')
  2549. a_interfaces = [
  2550. Interface.objects.create(device=device1, name=f'trunk-a{i}') for i in range(count)
  2551. ]
  2552. b_interfaces = [
  2553. Interface.objects.create(device=device2, name=f'trunk-b{i}') for i in range(count)
  2554. ]
  2555. cable = Cable(
  2556. a_terminations=a_interfaces,
  2557. b_terminations=b_interfaces,
  2558. profile=CableProfileChoices.TRUNK_4C1P,
  2559. )
  2560. cable.save()
  2561. return cable, a_interfaces, b_interfaces
  2562. def _get_connectors(self, cable, cable_end):
  2563. return [
  2564. (ct.connector, ct.termination) for ct in cable.terminations.filter(cable_end=cable_end)
  2565. ]
  2566. def test_reordering_terminations_reassigns_connectors(self):
  2567. """
  2568. A Cable's terminations are assigned to connectors in the order given, so reordering them must
  2569. rewire the Cable even though its set of terminating objects is unchanged.
  2570. """
  2571. cable, a_interfaces, b_interfaces = self._create_multiposition_cable()
  2572. self.assertEqual(
  2573. self._get_connectors(cable, 'B'), list(enumerate(b_interfaces, start=1))
  2574. )
  2575. # Reverse the B side terminations
  2576. cable = Cable.objects.get(pk=cable.pk)
  2577. cable.b_terminations = list(reversed(b_interfaces))
  2578. cable.save()
  2579. self.assertEqual(
  2580. self._get_connectors(cable, 'B'), list(enumerate(reversed(b_interfaces), start=1))
  2581. )
  2582. # The A side, which was not modified, must be left alone
  2583. self.assertEqual(
  2584. self._get_connectors(cable, 'A'), list(enumerate(a_interfaces, start=1))
  2585. )
  2586. # The reordering must be reflected in the terminations' link peers
  2587. self.assertEqual(
  2588. Interface.objects.get(pk=a_interfaces[0].pk).link_peers, [b_interfaces[-1]]
  2589. )
  2590. def test_removing_a_termination_reassigns_connectors(self):
  2591. """
  2592. Removing a termination from the middle of a Cable's list must renumber the connectors of those
  2593. which follow it.
  2594. """
  2595. cable, a_interfaces, b_interfaces = self._create_multiposition_cable()
  2596. cable = Cable.objects.get(pk=cable.pk)
  2597. cable.b_terminations = [b_interfaces[0], b_interfaces[2], b_interfaces[3]]
  2598. cable.save()
  2599. self.assertEqual(
  2600. self._get_connectors(cable, 'B'),
  2601. [(1, b_interfaces[0]), (2, b_interfaces[2]), (3, b_interfaces[3])]
  2602. )
  2603. def test_appending_a_termination_preserves_connectors(self):
  2604. """
  2605. Appending a termination must not disturb the connectors already assigned to the terminations
  2606. which precede it.
  2607. """
  2608. cable, a_interfaces, b_interfaces = self._create_multiposition_cable(count=3)
  2609. original_cts = {ct.termination: ct.pk for ct in cable.terminations.filter(cable_end='B')}
  2610. new_interface = Interface.objects.create(device=Device.objects.get(name='TestDevice2'), name='trunk-b3')
  2611. cable = Cable.objects.get(pk=cable.pk)
  2612. cable.b_terminations = [*b_interfaces, new_interface]
  2613. cable.save()
  2614. self.assertEqual(
  2615. self._get_connectors(cable, 'B'), list(enumerate([*b_interfaces, new_interface], start=1))
  2616. )
  2617. # The existing CableTerminations must not have been recreated
  2618. for ct in cable.terminations.filter(cable_end='B'):
  2619. if ct.termination in original_cts:
  2620. self.assertEqual(ct.pk, original_cts[ct.termination])
  2621. @tag('regression') # #23094
  2622. def test_clearing_an_end_of_a_fresh_instance_removes_its_terminations(self):
  2623. """
  2624. Assigning an empty list to an end of a freshly loaded cable must delete that end's terminations only.
  2625. """
  2626. interface1 = Interface.objects.get(device__name='TestDevice1', name='eth0')
  2627. interface2 = Interface.objects.get(device__name='TestDevice2', name='eth0')
  2628. cable_pk = Cable.objects.first().pk
  2629. for attr, kept_side, cleared, kept in (
  2630. ('a_terminations', CableEndChoices.SIDE_B, interface1, interface2),
  2631. ('b_terminations', CableEndChoices.SIDE_A, interface2, interface1),
  2632. ):
  2633. with self.subTest(attr=attr):
  2634. cable = Cable.objects.get(pk=cable_pk)
  2635. kept_row_pk = CableTermination.objects.get(cable=cable, cable_end=kept_side).pk
  2636. setattr(cable, attr, [])
  2637. self.assertTrue(cable._terminations_modified)
  2638. cable.full_clean()
  2639. cable.save()
  2640. self.assertEqual(
  2641. list(CableTermination.objects.filter(cable=cable).values_list('pk', 'cable_end')),
  2642. [(kept_row_pk, kept_side)]
  2643. )
  2644. cleared.refresh_from_db()
  2645. self.assertIsNone(cleared.cable)
  2646. self.assertIsNone(cleared._path_id)
  2647. kept.refresh_from_db()
  2648. self.assertEqual(kept.cable, cable)
  2649. self.assertFalse(kept._path.is_complete)
  2650. # Reconnect the cleared end so the other side starts from a complete cable
  2651. cable = Cable.objects.get(pk=cable_pk)
  2652. setattr(cable, attr, [cleared])
  2653. cable.save()
  2654. # A profiled cable keeps the other end's rows and connectors
  2655. cable, a_interfaces, b_interfaces = self._create_multiposition_cable()
  2656. a_row_pks = set(cable.terminations.filter(cable_end=CableEndChoices.SIDE_A).values_list('pk', flat=True))
  2657. cable = Cable.objects.get(pk=cable.pk)
  2658. cable.b_terminations = []
  2659. cable.full_clean()
  2660. cable.save()
  2661. self.assertEqual(self._get_connectors(cable, 'B'), [])
  2662. self.assertEqual(self._get_connectors(cable, 'A'), list(enumerate(a_interfaces, start=1)))
  2663. self.assertEqual(
  2664. set(cable.terminations.filter(cable_end=CableEndChoices.SIDE_A).values_list('pk', flat=True)), a_row_pks
  2665. )
  2666. @tag('regression') # #23094
  2667. def test_reassigning_a_mutated_termination_list_flags_a_change(self):
  2668. """
  2669. Appending to a retrieved termination list and assigning it back must be applied on save.
  2670. """
  2671. cable = Cable.objects.first()
  2672. interface1 = Interface.objects.get(device__name='TestDevice1', name='eth0')
  2673. interface3 = Interface.objects.create(device=interface1.device, name='eth1')
  2674. # Assigning warms the A end's cache and the save resets the flag
  2675. cable.a_terminations = [interface1]
  2676. cable.save()
  2677. self.assertFalse(cable._terminations_modified)
  2678. terminations = cable.a_terminations
  2679. terminations.append(interface3)
  2680. cable.a_terminations = terminations
  2681. self.assertTrue(cable._terminations_modified)
  2682. cable.full_clean()
  2683. cable.save()
  2684. self.assertEqual(
  2685. [ct.termination for ct in cable.terminations.filter(cable_end=CableEndChoices.SIDE_A)],
  2686. [interface1, interface3]
  2687. )
  2688. @tag('regression') # #23094
  2689. def test_assigned_termination_list_is_copied(self):
  2690. """
  2691. Mutating a list after assigning it to an end must not change the cable's terminations.
  2692. """
  2693. interface1 = Interface.objects.get(device__name='TestDevice1', name='eth0')
  2694. interface3 = Interface.objects.get(device__name='TestDevice2', name='eth1')
  2695. cable = Cable.objects.first()
  2696. terminations = [interface1]
  2697. cable.a_terminations = terminations
  2698. terminations.append(interface3)
  2699. self.assertEqual(cable.a_terminations, [interface1])
  2700. @tag('regression') # #23094
  2701. def test_assigning_an_iterable_stores_a_list_of_its_terminations(self):
  2702. """
  2703. Single-pass iterables and querysets assigned to an end must be stored as a list of the resolved terminations.
  2704. """
  2705. interface1 = Interface.objects.get(device__name='TestDevice1', name='eth0')
  2706. interface3 = Interface.objects.get(device__name='TestDevice2', name='eth1')
  2707. row_pk = CableTermination.objects.get(cable_end=CableEndChoices.SIDE_A).pk
  2708. for label, value, expected in (
  2709. ('iterator of objects', iter([interface1, interface3]), [interface1, interface3]),
  2710. ('iterator of IDs', iter([row_pk]), [interface1]),
  2711. ('queryset', Interface.objects.filter(pk=interface1.pk), [interface1]),
  2712. ):
  2713. with self.subTest(value=label):
  2714. cable = Cable.objects.first()
  2715. cable.a_terminations = value
  2716. self.assertIsInstance(cable._a_terminations, list)
  2717. self.assertEqual(cable.a_terminations, expected)
  2718. def test_assigning_terminations_to_a_fresh_instance_flags_a_change(self):
  2719. """
  2720. Assigning an end of a freshly loaded cable must flag a change, even when it repeats the stored terminations.
  2721. """
  2722. interface1 = Interface.objects.get(device__name='TestDevice1', name='eth0')
  2723. interface2 = Interface.objects.get(device__name='TestDevice2', name='eth0')
  2724. data = Cable.objects.first().serialize_object()
  2725. # Change replay writes the CableTermination rows first and relies on this to retrace the paths
  2726. for attr, interface in (('a_terminations', interface1), ('b_terminations', interface2)):
  2727. for label, value in (('objects', [interface]), ('IDs', data[attr])):
  2728. with self.subTest(attr=attr, value=label):
  2729. cable = Cable.objects.first()
  2730. setattr(cable, attr, value)
  2731. self.assertEqual(getattr(cable, attr), [interface])
  2732. self.assertTrue(cable._terminations_modified)
  2733. def test_reassigning_an_unchanged_end_on_a_warm_instance_does_not_flag_a_change(self):
  2734. """
  2735. Assigning the value an end already holds in memory must not flag a change or clear a pending one.
  2736. """
  2737. interface1 = Interface.objects.get(device__name='TestDevice1', name='eth0')
  2738. interface3 = Interface.objects.get(device__name='TestDevice2', name='eth1')
  2739. # Assigning warms the A end's cache and the save resets the flag
  2740. cable = Cable.objects.first()
  2741. cable.a_terminations = [interface1]
  2742. cable.save()
  2743. self.assertFalse(cable._terminations_modified)
  2744. termination_pks = set(CableTermination.objects.filter(cable=cable).values_list('pk', flat=True))
  2745. path_pks = set(CablePath.objects.filter(_nodes__contains=cable).values_list('pk', flat=True))
  2746. cable.a_terminations = [interface1]
  2747. self.assertFalse(cable._terminations_modified)
  2748. cable.save()
  2749. self.assertEqual(
  2750. set(CableTermination.objects.filter(cable=cable).values_list('pk', flat=True)),
  2751. termination_pks
  2752. )
  2753. self.assertEqual(set(CablePath.objects.filter(_nodes__contains=cable).values_list('pk', flat=True)), path_pks)
  2754. cable.b_terminations = [interface3]
  2755. cable.a_terminations = [interface1]
  2756. self.assertTrue(cable._terminations_modified)
  2757. @tag('regression') # #21498
  2758. def test_path_refreshes_replaced_cablepath_reference(self):
  2759. """
  2760. An already-instantiated interface should refresh its denormalized
  2761. `_path` foreign key when the referenced CablePath row has been
  2762. replaced in the database.
  2763. """
  2764. stale_interface = Interface.objects.get(device__name='TestDevice1', name='eth0')
  2765. old_path = CablePath.objects.get(pk=stale_interface._path_id)
  2766. new_path = CablePath(
  2767. path=old_path.path,
  2768. is_active=old_path.is_active,
  2769. is_complete=old_path.is_complete,
  2770. is_split=old_path.is_split,
  2771. )
  2772. old_path_id = old_path.pk
  2773. old_path.delete()
  2774. new_path.save()
  2775. # The old CablePath no longer exists
  2776. self.assertFalse(CablePath.objects.filter(pk=old_path_id).exists())
  2777. # The already-instantiated interface still points to the deleted path
  2778. # until the accessor refreshes `_path` from the database.
  2779. self.assertEqual(stale_interface._path_id, old_path_id)
  2780. self.assertEqual(stale_interface.path.pk, new_path.pk)
  2781. @tag('regression') # #21498
  2782. def test_serialize_for_event_handles_stale_cablepath_reference_after_retermination(self):
  2783. """
  2784. Serializing an interface whose previously cached `_path` row has been
  2785. deleted during cable retermination must not raise.
  2786. """
  2787. stale_interface = Interface.objects.get(device__name='TestDevice2', name='eth0')
  2788. old_path_id = stale_interface._path_id
  2789. new_peer = Interface.objects.get(device__name='TestDevice2', name='eth1')
  2790. cable = stale_interface.cable
  2791. self.assertIsNotNone(cable)
  2792. self.assertIsNotNone(old_path_id)
  2793. self.assertEqual(stale_interface.cable_end, 'B')
  2794. cable.b_terminations = [new_peer]
  2795. cable.save()
  2796. # The old CablePath was deleted during retrace.
  2797. self.assertFalse(CablePath.objects.filter(pk=old_path_id).exists())
  2798. # The stale in-memory instance still holds the deleted FK value.
  2799. self.assertEqual(stale_interface._path_id, old_path_id)
  2800. # Serialization must not raise ObjectDoesNotExist. Because this interface
  2801. # was the former B-side termination, it is now disconnected.
  2802. data = serialize_for_event(stale_interface)
  2803. self.assertIsNone(data['connected_endpoints'])
  2804. self.assertIsNone(data['connected_endpoints_type'])
  2805. self.assertFalse(data['connected_endpoints_reachable'])
  2806. @tag('regression') # #21338
  2807. def test_path_refreshes_unset_cablepath_reference(self):
  2808. """
  2809. An endpoint instance saved during cable creation, before path tracing,
  2810. should resolve its path and connected endpoints.
  2811. The stale-instance preconditions rely on Cable.save() saving each
  2812. CableTermination (which re-saves the endpoint) before trace_paths
  2813. creates the CablePath records.
  2814. """
  2815. device = Device.objects.get(name='TestDevice2')
  2816. interface_a = Interface.objects.create(device=device, name='eth2')
  2817. interface_b = Interface.objects.create(device=device, name='eth3')
  2818. # Capture the instances handed to the event machinery on save
  2819. saved_instances = []
  2820. def capture(sender, instance, **kwargs):
  2821. saved_instances.append(instance)
  2822. post_save.connect(capture, sender=Interface)
  2823. try:
  2824. Cable(a_terminations=[interface_a], b_terminations=[interface_b]).save()
  2825. finally:
  2826. post_save.disconnect(capture, sender=Interface)
  2827. self.assertEqual(len(saved_instances), 2)
  2828. captured_a = next(i for i in saved_instances if i.pk == interface_a.pk)
  2829. captured_b = next(i for i in saved_instances if i.pk == interface_b.pk)
  2830. # The captured instances predate path tracing: cabled, but no path yet
  2831. self.assertIsNotNone(captured_a.cable_id)
  2832. self.assertIsNone(captured_a._path_id)
  2833. self.assertIsNone(captured_b._path_id)
  2834. # The accessor must repair the unset denormalized reference
  2835. self.assertIsNotNone(captured_a.path)
  2836. self.assertEqual(captured_a.connected_endpoints, [interface_b])
  2837. # Serialization as performed by the event queue must see the peer
  2838. data = serialize_for_event(captured_b)
  2839. self.assertEqual([endpoint['id'] for endpoint in data['connected_endpoints']], [interface_a.pk])
  2840. self.assertEqual([peer['id'] for peer in data['link_peers']], [interface_a.pk])
  2841. self.assertTrue(data['connected_endpoints_reachable'])
  2842. def test_path_returns_none_for_unsaved_endpoint(self):
  2843. """
  2844. An unsaved endpoint with a link assigned should report no path rather
  2845. than attempting a database refresh.
  2846. """
  2847. device = Device.objects.get(name='TestDevice1')
  2848. cable = Cable.objects.first()
  2849. interface = Interface(device=device, name='tmp', cable=cable)
  2850. self.assertIsNone(interface.path)
  2851. def test_cable_length_normalization_large_kilometer_value(self):
  2852. """
  2853. A large kilometer length must pass validation and fit in the normalized length field.
  2854. """
  2855. cable = Cable.objects.first()
  2856. cable.length = Decimal('1234')
  2857. cable.length_unit = CableLengthUnitChoices.UNIT_KILOMETER
  2858. cable.full_clean()
  2859. cable.save()
  2860. cable.refresh_from_db()
  2861. self.assertEqual(cable._abs_length, Decimal('1234000.0000'))
  2862. def test_cable_length_normalization_maximum_mile_value(self):
  2863. """
  2864. The maximum length value expressed in miles must fit in the normalized length field.
  2865. """
  2866. cable = Cable.objects.first()
  2867. cable.length = Decimal('999999.99')
  2868. cable.length_unit = CableLengthUnitChoices.UNIT_MILE
  2869. cable.full_clean()
  2870. cable.save()
  2871. cable.refresh_from_db()
  2872. self.assertEqual(cable._abs_length, Decimal('1609343983.9066'))
  2873. def test_partial_save_persists_normalized_length(self):
  2874. """
  2875. A save naming only length must persist the normalized length alongside it.
  2876. """
  2877. cable = Cable.objects.first()
  2878. cable.length = Decimal('1')
  2879. cable.length_unit = CableLengthUnitChoices.UNIT_METER
  2880. cable.save()
  2881. cable.length = Decimal('2')
  2882. cable.save(update_fields=['length'])
  2883. cable.refresh_from_db()
  2884. self.assertEqual(cable.length, Decimal('2.00'))
  2885. self.assertEqual(cable.length_unit, CableLengthUnitChoices.UNIT_METER)
  2886. self.assertEqual(cable._abs_length, Decimal('2.0000'))
  2887. def test_partial_save_persists_normalized_length_for_a_unit_change(self):
  2888. """
  2889. A save naming only length_unit must renormalize against the stored length.
  2890. """
  2891. cable = Cable.objects.first()
  2892. cable.length = Decimal('10')
  2893. cable.length_unit = CableLengthUnitChoices.UNIT_METER
  2894. cable.save()
  2895. cable.length_unit = CableLengthUnitChoices.UNIT_FOOT
  2896. cable.save(update_fields=['length_unit'])
  2897. cable.refresh_from_db()
  2898. self.assertEqual(cable.length, Decimal('10.00'))
  2899. self.assertEqual(cable.length_unit, CableLengthUnitChoices.UNIT_FOOT)
  2900. self.assertEqual(cable._abs_length, Decimal('3.0480'))
  2901. def test_partial_save_persists_normalized_length_for_both_source_fields(self):
  2902. """
  2903. A save naming both source fields must normalize from the values being written.
  2904. """
  2905. cable = Cable.objects.first()
  2906. cable.length = Decimal('2')
  2907. cable.length_unit = CableLengthUnitChoices.UNIT_KILOMETER
  2908. cable.save(update_fields=['length', 'length_unit'])
  2909. cable.refresh_from_db()
  2910. self.assertEqual(cable._abs_length, Decimal('2000.0000'))
  2911. def test_partial_save_normalizes_against_an_unwritten_length_unit(self):
  2912. """
  2913. A save naming only length must normalize against the stored unit, not an unwritten one.
  2914. """
  2915. cable = Cable.objects.first()
  2916. cable.length = Decimal('1')
  2917. cable.length_unit = CableLengthUnitChoices.UNIT_METER
  2918. cable.save()
  2919. cable.length = Decimal('2')
  2920. cable.length_unit = CableLengthUnitChoices.UNIT_KILOMETER
  2921. cable.save(update_fields=['length'])
  2922. cable.refresh_from_db()
  2923. self.assertEqual(cable.length_unit, CableLengthUnitChoices.UNIT_METER)
  2924. self.assertEqual(cable._abs_length, Decimal('2.0000'))
  2925. def test_partial_save_normalizes_against_an_unwritten_length(self):
  2926. """
  2927. A save naming only length_unit must normalize against the stored length, not an unwritten one.
  2928. """
  2929. cable = Cable.objects.first()
  2930. cable.length = Decimal('1')
  2931. cable.length_unit = CableLengthUnitChoices.UNIT_METER
  2932. cable.save()
  2933. cable.length = Decimal('2')
  2934. cable.length_unit = CableLengthUnitChoices.UNIT_CENTIMETER
  2935. cable.save(update_fields=['length_unit'])
  2936. cable.refresh_from_db()
  2937. self.assertEqual(cable.length, Decimal('1.00'))
  2938. self.assertEqual(cable.length_unit, CableLengthUnitChoices.UNIT_CENTIMETER)
  2939. self.assertEqual(cable._abs_length, Decimal('0.0100'))
  2940. def test_partial_save_normalizes_against_an_unwritten_cleared_length(self):
  2941. """
  2942. A save naming only length_unit must keep the unit when the excluded length is cleared in memory.
  2943. """
  2944. cable = Cable.objects.first()
  2945. cable.length = Decimal('1')
  2946. cable.length_unit = CableLengthUnitChoices.UNIT_METER
  2947. cable.save()
  2948. cable.length = None
  2949. cable.length_unit = CableLengthUnitChoices.UNIT_CENTIMETER
  2950. cable.save(update_fields=['length_unit'])
  2951. cable.refresh_from_db()
  2952. self.assertEqual(cable.length, Decimal('1.00'))
  2953. self.assertEqual(cable.length_unit, CableLengthUnitChoices.UNIT_CENTIMETER)
  2954. self.assertEqual(cable._abs_length, Decimal('0.0100'))
  2955. def test_partial_save_clearing_length_keeps_the_stored_unit(self):
  2956. """
  2957. A save naming only length must clear the normalized length without writing length_unit.
  2958. """
  2959. cable = Cable.objects.first()
  2960. cable.length = Decimal('1')
  2961. cable.length_unit = CableLengthUnitChoices.UNIT_METER
  2962. cable.save()
  2963. cable.length = None
  2964. cable.save(update_fields=['length'])
  2965. # The unit was not written, so the instance must still agree with the row
  2966. self.assertEqual(cable.length_unit, CableLengthUnitChoices.UNIT_METER)
  2967. cable.refresh_from_db()
  2968. self.assertIsNone(cable.length)
  2969. self.assertEqual(cable.length_unit, CableLengthUnitChoices.UNIT_METER)
  2970. self.assertIsNone(cable._abs_length)
  2971. def test_partial_save_leaves_an_unwritten_length_alone(self):
  2972. """
  2973. A save naming an unrelated field must not persist an in-memory length change.
  2974. """
  2975. cable = Cable.objects.first()
  2976. cable.length = Decimal('1')
  2977. cable.length_unit = CableLengthUnitChoices.UNIT_METER
  2978. cable.save()
  2979. cable.length = Decimal('99')
  2980. cable.label = 'Renamed'
  2981. cable.save(update_fields=['label'])
  2982. cable.refresh_from_db()
  2983. self.assertEqual(cable.label, 'Renamed')
  2984. self.assertEqual(cable.length, Decimal('1.00'))
  2985. self.assertEqual(cable._abs_length, Decimal('1.0000'))
  2986. def test_partial_save_normalizes_against_an_out_of_band_length(self):
  2987. """
  2988. A save naming only length_unit must read the stored length, not one cached on the instance.
  2989. """
  2990. cable = Cable.objects.first()
  2991. cable.length = Decimal('1')
  2992. cable.length_unit = CableLengthUnitChoices.UNIT_METER
  2993. cable.save()
  2994. Cable.objects.filter(pk=cable.pk).update(length=Decimal('7'))
  2995. cable.length_unit = CableLengthUnitChoices.UNIT_FOOT
  2996. cable.save(update_fields=['length_unit'])
  2997. cable.refresh_from_db()
  2998. self.assertEqual(cable.length, Decimal('7.00'))
  2999. self.assertEqual(cable._abs_length, Decimal('2.1336'))
  3000. def test_partial_save_clears_a_unit_written_without_a_stored_length(self):
  3001. """
  3002. A save naming only length_unit must drop the unit when the row holds no length.
  3003. """
  3004. cable = Cable.objects.first()
  3005. cable.length_unit = CableLengthUnitChoices.UNIT_METER
  3006. cable.save(update_fields=['length_unit'])
  3007. cable.refresh_from_db()
  3008. self.assertIsNone(cable.length)
  3009. self.assertIsNone(cable.length_unit)
  3010. self.assertIsNone(cable._abs_length)
  3011. def test_full_save_clears_the_unit_when_the_length_is_removed(self):
  3012. """
  3013. A full save with no length must clear the stored unit.
  3014. """
  3015. cable = Cable.objects.first()
  3016. cable.length = Decimal('1')
  3017. cable.length_unit = CableLengthUnitChoices.UNIT_METER
  3018. cable.save()
  3019. cable.length = None
  3020. cable.save()
  3021. cable.refresh_from_db()
  3022. self.assertIsNone(cable.length)
  3023. self.assertIsNone(cable.length_unit)
  3024. self.assertIsNone(cable._abs_length)
  3025. def test_negative_length_rejected_by_database(self):
  3026. """
  3027. A negative length must not reach the database, even through a write which skips validation.
  3028. """
  3029. cable = Cable.objects.first()
  3030. with self.assertRaises(IntegrityError), transaction.atomic():
  3031. Cable.objects.filter(pk=cable.pk).update(
  3032. length=Decimal('-1'), length_unit=CableLengthUnitChoices.UNIT_METER
  3033. )
  3034. def test_partial_save_reads_the_stored_length_only_for_an_unwritten_length(self):
  3035. """
  3036. Only a save writing length_unit without length must read the row back, to decide whether to clear the
  3037. unit; the database computes the normalized length itself.
  3038. """
  3039. cable = Cable.objects.first()
  3040. cable.length = Decimal('1')
  3041. cable.length_unit = CableLengthUnitChoices.UNIT_METER
  3042. cable.save()
  3043. with CaptureQueriesContext(connection) as both_written:
  3044. cable.save(update_fields=['length', 'length_unit'])
  3045. with CaptureQueriesContext(connection) as length_written:
  3046. cable.save(update_fields=['length'])
  3047. with CaptureQueriesContext(connection) as unit_written:
  3048. cable.save(update_fields=['length_unit'])
  3049. def cable_reads(queries):
  3050. return [q for q in queries if q['sql'].startswith('SELECT') and 'FROM "dcim_cable"' in q['sql']]
  3051. self.assertEqual(cable_reads(both_written), [])
  3052. self.assertEqual(cable_reads(length_written), [])
  3053. self.assertEqual(len(cable_reads(unit_written)), 1)
  3054. class CableTerminationTestCase(TestCase):
  3055. def test_cache_related_objects_requires_resolvable_termination(self):
  3056. """cache_related_objects raises ValueError when the termination cannot be resolved."""
  3057. cable_termination = CableTermination(
  3058. termination_type=ObjectType.objects.get_for_model(Interface),
  3059. termination_id=0,
  3060. )
  3061. with self.assertRaises(ValueError):
  3062. cable_termination.cache_related_objects()
  3063. class CableDisconnectChangeLoggingTestCase(TestCase):
  3064. """
  3065. Deleting a Cable must change-log the disconnect on each terminating object. Its CableTerminations are
  3066. deleted by the cascade, so CableTermination.delete() -- which records the disconnect when a termination
  3067. is removed from a Cable -- never runs.
  3068. """
  3069. @classmethod
  3070. def setUpTestData(cls):
  3071. site = Site.objects.create(name='Test Site 1', slug='test-site-1')
  3072. manufacturer = Manufacturer.objects.create(name='Test Manufacturer 1', slug='test-manufacturer-1')
  3073. device_type = DeviceType.objects.create(
  3074. manufacturer=manufacturer, model='Test Device Type 1', slug='test-device-type-1'
  3075. )
  3076. role = DeviceRole.objects.create(name='Test Device Role 1', slug='test-device-role-1')
  3077. cls.device1 = Device.objects.create(
  3078. name='Device 1', site=site, device_type=device_type, role=role
  3079. )
  3080. cls.device2 = Device.objects.create(
  3081. name='Device 2', site=site, device_type=device_type, role=role
  3082. )
  3083. cls.interface1 = Interface.objects.create(
  3084. device=cls.device1, name='eth0', type=InterfaceTypeChoices.TYPE_1GE_FIXED
  3085. )
  3086. cls.interface2 = Interface.objects.create(
  3087. device=cls.device2, name='eth0', type=InterfaceTypeChoices.TYPE_1GE_FIXED
  3088. )
  3089. cls.interface3 = Interface.objects.create(
  3090. device=cls.device2, name='eth1', type=InterfaceTypeChoices.TYPE_1GE_FIXED
  3091. )
  3092. cls.rear_port = RearPort.objects.create(
  3093. device=cls.device2, name='Rear Port 1', type=PortTypeChoices.TYPE_8P8C, positions=4
  3094. )
  3095. cls.front_port = FrontPort.objects.create(
  3096. device=cls.device2, name='Front Port 1', type=PortTypeChoices.TYPE_8P8C, positions=4
  3097. )
  3098. cls.user = User.objects.create_user(username='testuser')
  3099. def _request(self):
  3100. request = RequestFactory().get('/')
  3101. request.id = uuid.uuid4()
  3102. request.user = self.user
  3103. return request
  3104. def _connect(self, termination_a, termination_b, **kwargs):
  3105. with event_tracking(self._request()):
  3106. cable = Cable(a_terminations=[termination_a], b_terminations=[termination_b], **kwargs)
  3107. cable.save()
  3108. return cable
  3109. def _updates(self, obj):
  3110. return ObjectChange.objects.filter(
  3111. changed_object_type=ObjectType.objects.get_for_model(obj),
  3112. changed_object_id=obj.pk,
  3113. action=ObjectChangeActionChoices.ACTION_UPDATE,
  3114. ).order_by('time')
  3115. @tag('regression') # Ref: netbox-branching#631
  3116. def test_cable_deletion_records_disconnect(self):
  3117. cable = self._connect(self.interface1, self.interface2)
  3118. cable_pk = cable.pk
  3119. with event_tracking(self._request()):
  3120. Cable.objects.get(pk=cable_pk).delete()
  3121. for interface in (self.interface1, self.interface2):
  3122. # One update for the connect, one for the disconnect
  3123. self.assertEqual(self._updates(interface).count(), 2, f'No disconnect recorded for {interface}')
  3124. change = self._updates(interface).last()
  3125. # The cable attributes are cleared in the database before this is recorded, so the pre-change
  3126. # data is only correct if they were restored before the snapshot was taken
  3127. self.assertEqual(change.prechange_data['cable'], cable_pk)
  3128. self.assertIn(change.prechange_data['cable_end'], (CableEndChoices.SIDE_A, CableEndChoices.SIDE_B))
  3129. self.assertIsNone(change.postchange_data['cable'])
  3130. self.assertIsNone(change.postchange_data['cable_end'])
  3131. # The originating path is deleted along with the Cable, outside the changelog
  3132. self.assertIsNone(change.postchange_data['_path'])
  3133. self.assertIsNone(Interface.objects.get(pk=interface.pk).cable_id)
  3134. self.assertFalse(CablePath.objects.exists())
  3135. def test_profiled_cable_deletion_records_connector_and_positions(self):
  3136. cable = self._connect(self.interface1, self.rear_port, profile=CableProfileChoices.SINGLE_1C4P)
  3137. cable_pk = cable.pk
  3138. connector = Interface.objects.get(pk=self.interface1.pk).cable_connector
  3139. positions = Interface.objects.get(pk=self.interface1.pk).cable_positions
  3140. self.assertIsNotNone(connector)
  3141. self.assertTrue(positions)
  3142. with event_tracking(self._request()):
  3143. Cable.objects.get(pk=cable_pk).delete()
  3144. change = self._updates(self.interface1).last()
  3145. self.assertEqual(change.prechange_data['cable_connector'], connector)
  3146. self.assertEqual(change.prechange_data['cable_positions'], positions)
  3147. self.assertIsNone(change.postchange_data['cable_connector'])
  3148. self.assertIsNone(change.postchange_data['cable_positions'])
  3149. def test_queryset_deletion_records_disconnect(self):
  3150. # A queryset delete never calls Cable.delete(), so the tracking is done by CableQuerySet.delete()
  3151. cable = self._connect(self.interface1, self.interface2)
  3152. cable_pk = cable.pk
  3153. with event_tracking(self._request()):
  3154. Cable.objects.filter(pk=cable_pk).delete()
  3155. change = self._updates(self.interface1).last()
  3156. self.assertEqual(change.prechange_data['cable'], cable_pk)
  3157. self.assertIsNone(change.postchange_data['cable'])
  3158. def test_non_path_endpoint_termination(self):
  3159. # A front port carries no _path of its own; the disconnect is recorded the same way
  3160. cable = self._connect(self.interface1, self.front_port)
  3161. cable_pk = cable.pk
  3162. with event_tracking(self._request()):
  3163. Cable.objects.get(pk=cable_pk).delete()
  3164. change = self._updates(self.front_port).last()
  3165. self.assertEqual(change.prechange_data['cable'], cable_pk)
  3166. self.assertIsNone(change.postchange_data['cable'])
  3167. self.assertIsNone(FrontPort.objects.get(pk=self.front_port.pk).cable_id)
  3168. def test_termination_removal_records_disconnect(self):
  3169. # Removing a termination from a Cable (rather than deleting the Cable) is recorded by
  3170. # CableTermination.delete(); the disconnect must not be logged twice or logged as a no-op.
  3171. cable = self._connect(self.interface1, self.interface2)
  3172. cable_pk = cable.pk
  3173. request = self._request()
  3174. with event_tracking(request):
  3175. cable = Cable.objects.get(pk=cable_pk)
  3176. cable.b_terminations = [self.interface3]
  3177. cable.save()
  3178. changes = self._updates(self.interface2).filter(request_id=request.id)
  3179. self.assertEqual(changes.count(), 1)
  3180. self.assertEqual(changes[0].prechange_data['cable'], cable_pk)
  3181. self.assertIsNone(changes[0].postchange_data['cable'])
  3182. def test_terminating_object_deletion_records_no_update(self):
  3183. # The cascade from deleting the terminating object itself reaches the same handler, but the object
  3184. # is on its way out: it must be left alone rather than resurrected as an update.
  3185. self._connect(self.interface1, self.interface2)
  3186. request = self._request()
  3187. with event_tracking(request):
  3188. Interface.objects.get(pk=self.interface1.pk).delete()
  3189. self.assertFalse(self._updates(self.interface1).filter(request_id=request.id).exists())
  3190. class InterfaceLAGAttributesTestCase(TestCase):
  3191. @classmethod
  3192. def setUpTestData(cls):
  3193. site = Site.objects.create(name='Site 1', slug='site-1')
  3194. manufacturer = Manufacturer.objects.create(name='Manufacturer 1', slug='manufacturer-1')
  3195. devicetype = DeviceType.objects.create(manufacturer=manufacturer, model='Device Type 1', slug='device-type-1')
  3196. role = DeviceRole.objects.create(name='Device Role 1', slug='device-role-1', color='ff0000')
  3197. cls.device = Device.objects.create(device_type=devicetype, role=role, name='Device 1', site=site)
  3198. def test_lag_attributes_on_lag_interface(self):
  3199. interface = Interface(
  3200. device=self.device,
  3201. name='bond0',
  3202. type=InterfaceTypeChoices.TYPE_LAG,
  3203. lag_mode=InterfaceLAGModeChoices.MODE_LACP,
  3204. lag_hash_policy=InterfaceLAGHashPolicyChoices.POLICY_LAYER3_4,
  3205. )
  3206. interface.full_clean()
  3207. def test_lag_mode_on_non_lag_interface(self):
  3208. interface = Interface(
  3209. device=self.device,
  3210. name='eth0',
  3211. type=InterfaceTypeChoices.TYPE_1GE_FIXED,
  3212. lag_mode=InterfaceLAGModeChoices.MODE_LACP,
  3213. )
  3214. with self.assertRaises(ValidationError) as cm:
  3215. interface.full_clean()
  3216. self.assertIn('lag_mode', cm.exception.message_dict)
  3217. def test_lag_hash_policy_on_non_lag_interface(self):
  3218. interface = Interface(
  3219. device=self.device,
  3220. name='eth0',
  3221. type=InterfaceTypeChoices.TYPE_1GE_FIXED,
  3222. lag_hash_policy=InterfaceLAGHashPolicyChoices.POLICY_LAYER2,
  3223. )
  3224. with self.assertRaises(ValidationError) as cm:
  3225. interface.full_clean()
  3226. self.assertIn('lag_hash_policy', cm.exception.message_dict)
  3227. def test_lag_hash_policy_lag_mode(self):
  3228. for lag_mode, valid in (
  3229. (None, False),
  3230. (InterfaceLAGModeChoices.MODE_LACP, True),
  3231. (InterfaceLAGModeChoices.MODE_STATIC, True),
  3232. (InterfaceLAGModeChoices.MODE_BALANCE_TLB, True),
  3233. (InterfaceLAGModeChoices.MODE_ACTIVE_BACKUP, False),
  3234. (InterfaceLAGModeChoices.MODE_BALANCE_RR, False),
  3235. (InterfaceLAGModeChoices.MODE_BALANCE_ALB, False),
  3236. (InterfaceLAGModeChoices.MODE_BROADCAST, False),
  3237. ):
  3238. with self.subTest(lag_mode=lag_mode):
  3239. interface = Interface(
  3240. device=self.device,
  3241. name='bond0',
  3242. type=InterfaceTypeChoices.TYPE_LAG,
  3243. lag_mode=lag_mode,
  3244. lag_hash_policy=InterfaceLAGHashPolicyChoices.POLICY_LAYER3_4,
  3245. )
  3246. if valid:
  3247. interface.full_clean()
  3248. else:
  3249. with self.assertRaises(ValidationError) as cm:
  3250. interface.full_clean()
  3251. self.assertIn('lag_hash_policy', cm.exception.message_dict)
  3252. class VirtualDeviceContextTestCase(TestCase):
  3253. @classmethod
  3254. def setUpTestData(cls):
  3255. site = Site.objects.create(name='Test Site 1', slug='test-site-1')
  3256. manufacturer = Manufacturer.objects.create(name='Test Manufacturer 1', slug='test-manufacturer-1')
  3257. devicetype = DeviceType.objects.create(
  3258. manufacturer=manufacturer, model='Test Device Type 1', slug='test-device-type-1'
  3259. )
  3260. role = DeviceRole.objects.create(
  3261. name='Test Device Role 1', slug='test-device-role-1', color='ff0000'
  3262. )
  3263. Device.objects.create(
  3264. device_type=devicetype, role=role, name='TestDevice1', site=site
  3265. )
  3266. def test_vdc_and_interface_creation(self):
  3267. device = Device.objects.first()
  3268. vdc = VirtualDeviceContext(device=device, name="VDC 1", identifier=1, status='active')
  3269. vdc.full_clean()
  3270. vdc.save()
  3271. interface = Interface(device=device, name='Eth1/1', type='10gbase-t')
  3272. interface.full_clean()
  3273. interface.save()
  3274. interface.vdcs.set([vdc])
  3275. def test_vdc_duplicate_name(self):
  3276. device = Device.objects.first()
  3277. vdc1 = VirtualDeviceContext(device=device, name="VDC 1", identifier=1, status='active')
  3278. vdc1.full_clean()
  3279. vdc1.save()
  3280. vdc2 = VirtualDeviceContext(device=device, name="VDC 1", identifier=2, status='active')
  3281. with self.assertRaises(ValidationError):
  3282. vdc2.full_clean()
  3283. def test_vdc_duplicate_identifier(self):
  3284. device = Device.objects.first()
  3285. vdc1 = VirtualDeviceContext(device=device, name="VDC 1", identifier=1, status='active')
  3286. vdc1.full_clean()
  3287. vdc1.save()
  3288. vdc2 = VirtualDeviceContext(device=device, name="VDC 2", identifier=1, status='active')
  3289. with self.assertRaises(ValidationError):
  3290. vdc2.full_clean()
  3291. @tag('regression') # Ref: #23275
  3292. def test_primary_ip_requires_device(self):
  3293. """A primary IP on the device's interface is valid only while that device is assigned."""
  3294. device = Device.objects.first()
  3295. interface = Interface.objects.create(device=device, name='Eth1/1', type='10gbase-t')
  3296. for family, address in ((4, '192.0.2.1/24'), (6, '2001:db8::1/64')):
  3297. field = f'primary_ip{family}'
  3298. ip = IPAddress.objects.create(address=address, assigned_object=interface)
  3299. with self.subTest(family=family):
  3300. VirtualDeviceContext(device=device, name='VDC 1', status='active', **{field: ip}).full_clean()
  3301. vdc = VirtualDeviceContext(name='VDC 1', status='active', **{field: ip})
  3302. with self.assertRaises(ValidationError) as cm:
  3303. vdc.full_clean()
  3304. self.assertIn(field, cm.exception.message_dict)
  3305. self.assertIn('must belong to an interface', str(cm.exception.message_dict[field]))
  3306. class VirtualChassisTestCase(TestCase):
  3307. @classmethod
  3308. def setUpTestData(cls):
  3309. site = Site.objects.create(name='Test Site 1', slug='test-site-1')
  3310. manufacturer = Manufacturer.objects.create(name='Test Manufacturer 1', slug='test-manufacturer-1')
  3311. devicetype = DeviceType.objects.create(
  3312. manufacturer=manufacturer, model='Test Device Type 1', slug='test-device-type-1'
  3313. )
  3314. role = DeviceRole.objects.create(
  3315. name='Test Device Role 1', slug='test-device-role-1', color='ff0000'
  3316. )
  3317. Device.objects.create(
  3318. device_type=devicetype, role=role, name='TestDevice1', site=site
  3319. )
  3320. Device.objects.create(
  3321. device_type=devicetype, role=role, name='TestDevice2', site=site
  3322. )
  3323. def test_virtualchassis_deletion_clears_vc_position(self):
  3324. """
  3325. Test that when a VirtualChassis is deleted, member devices have their
  3326. vc_position and vc_priority fields set to None.
  3327. """
  3328. devices = Device.objects.all()
  3329. device1 = devices[0]
  3330. device2 = devices[1]
  3331. # Create a VirtualChassis with two member devices
  3332. vc = VirtualChassis.objects.create(name='Test VC', master=device1)
  3333. device1.virtual_chassis = vc
  3334. device1.vc_position = 1
  3335. device1.vc_priority = 10
  3336. device1.save()
  3337. device2.virtual_chassis = vc
  3338. device2.vc_position = 2
  3339. device2.vc_priority = 20
  3340. device2.save()
  3341. # Verify devices are members of the VC with positions set
  3342. device1.refresh_from_db()
  3343. device2.refresh_from_db()
  3344. self.assertEqual(device1.virtual_chassis, vc)
  3345. self.assertEqual(device1.vc_position, 1)
  3346. self.assertEqual(device1.vc_priority, 10)
  3347. self.assertEqual(device2.virtual_chassis, vc)
  3348. self.assertEqual(device2.vc_position, 2)
  3349. self.assertEqual(device2.vc_priority, 20)
  3350. # Delete the VirtualChassis
  3351. vc.delete()
  3352. # Verify devices have vc_position and vc_priority set to None
  3353. device1.refresh_from_db()
  3354. device2.refresh_from_db()
  3355. self.assertIsNone(device1.virtual_chassis)
  3356. self.assertIsNone(device1.vc_position)
  3357. self.assertIsNone(device1.vc_priority)
  3358. self.assertIsNone(device2.virtual_chassis)
  3359. self.assertIsNone(device2.vc_position)
  3360. self.assertIsNone(device2.vc_priority)
  3361. @tag('regression') # Ref: #22720
  3362. def test_virtualchassis_deletion_blocked_by_cross_chassis_lag(self):
  3363. """
  3364. Deleting a VirtualChassis whose members form a cross-chassis LAG must
  3365. raise ProtectedError exposing the blocking interfaces, leaving the VC
  3366. and its member assignments unchanged.
  3367. """
  3368. device1 = Device.objects.get(name='TestDevice1')
  3369. device2 = Device.objects.get(name='TestDevice2')
  3370. vc = VirtualChassis.objects.create(name='Test VC', master=device1)
  3371. device1.virtual_chassis = vc
  3372. device1.vc_position = 1
  3373. device1.vc_priority = 10
  3374. device1.save()
  3375. device2.virtual_chassis = vc
  3376. device2.vc_position = 2
  3377. device2.vc_priority = 20
  3378. device2.save()
  3379. lag = Interface.objects.create(device=device1, name='lag0', type=InterfaceTypeChoices.TYPE_LAG)
  3380. member_interface = Interface(
  3381. device=device2,
  3382. name='eth0',
  3383. type=InterfaceTypeChoices.TYPE_1GE_FIXED,
  3384. lag=lag,
  3385. )
  3386. # A cross-chassis LAG member is valid while both devices share the VC
  3387. member_interface.full_clean()
  3388. member_interface.save()
  3389. with self.assertRaises(ProtectedError) as cm:
  3390. vc.delete()
  3391. self.assertEqual(
  3392. cm.exception.args[0],
  3393. 'Unable to delete virtual chassis Test VC. One or more member interfaces form a cross-chassis LAG.'
  3394. )
  3395. self.assertEqual(set(cm.exception.protected_objects), {member_interface})
  3396. # The failed deletion must not clear the VC or its member assignments
  3397. self.assertTrue(VirtualChassis.objects.filter(pk=vc.pk).exists())
  3398. device1.refresh_from_db()
  3399. device2.refresh_from_db()
  3400. self.assertEqual(device1.virtual_chassis, vc)
  3401. self.assertEqual(device1.vc_position, 1)
  3402. self.assertEqual(device1.vc_priority, 10)
  3403. self.assertEqual(device2.virtual_chassis, vc)
  3404. self.assertEqual(device2.vc_position, 2)
  3405. self.assertEqual(device2.vc_priority, 20)
  3406. @tag('regression') # Ref: #23212
  3407. def test_member_removal_blocked_by_cross_chassis_lag(self):
  3408. """
  3409. Removing a device from a VirtualChassis must fail validation while any of its
  3410. interfaces form a LAG with another member, from either side of the LAG.
  3411. """
  3412. device1 = Device.objects.get(name='TestDevice1')
  3413. device2 = Device.objects.get(name='TestDevice2')
  3414. vc = VirtualChassis.objects.create(name='Test VC', master=device1)
  3415. Device.objects.filter(pk=device1.pk).update(virtual_chassis=vc, vc_position=1)
  3416. Device.objects.filter(pk=device2.pk).update(virtual_chassis=vc, vc_position=2)
  3417. device1.refresh_from_db()
  3418. device2.refresh_from_db()
  3419. lag = Interface.objects.create(device=device1, name='lag0', type=InterfaceTypeChoices.TYPE_LAG)
  3420. Interface.objects.create(
  3421. device=device2, name='eth0', type=InterfaceTypeChoices.TYPE_1GE_FIXED, lag=lag
  3422. )
  3423. # Both devices remain valid while in the same VC
  3424. device1.full_clean()
  3425. device2.full_clean()
  3426. # Member interface side
  3427. device2.virtual_chassis = None
  3428. device2.vc_position = None
  3429. with self.assertRaises(ValidationError) as cm:
  3430. device2.full_clean()
  3431. self.assertIn('eth0', str(cm.exception.error_dict['virtual_chassis']))
  3432. # LAG interface side (refresh clears the cached vc_master_for so the master guard doesn't fire first)
  3433. VirtualChassis.objects.filter(pk=vc.pk).update(master=device2)
  3434. device1.refresh_from_db()
  3435. device1.virtual_chassis = None
  3436. device1.vc_position = None
  3437. with self.assertRaises(ValidationError) as cm:
  3438. device1.full_clean()
  3439. self.assertIn('eth0', str(cm.exception.error_dict['virtual_chassis']))
  3440. def test_member_removal_error_lists_at_most_five_interfaces(self):
  3441. """
  3442. The cross-chassis LAG error names at most five interfaces and summarizes the rest.
  3443. """
  3444. device1 = Device.objects.get(name='TestDevice1')
  3445. device2 = Device.objects.get(name='TestDevice2')
  3446. vc = VirtualChassis.objects.create(name='Test VC', master=device1)
  3447. Device.objects.filter(pk=device1.pk).update(virtual_chassis=vc, vc_position=1)
  3448. Device.objects.filter(pk=device2.pk).update(virtual_chassis=vc, vc_position=2)
  3449. device2.refresh_from_db()
  3450. lag = Interface.objects.create(device=device1, name='lag0', type=InterfaceTypeChoices.TYPE_LAG)
  3451. Interface.objects.bulk_create([
  3452. Interface(device=device2, name=f'eth{i}', type=InterfaceTypeChoices.TYPE_1GE_FIXED, lag=lag)
  3453. for i in range(7)
  3454. ])
  3455. device2.virtual_chassis = None
  3456. device2.vc_position = None
  3457. with self.assertRaises(ValidationError) as cm:
  3458. device2.full_clean()
  3459. message = str(cm.exception.error_dict['virtual_chassis'])
  3460. self.assertEqual(message.count('lag0'), 5)
  3461. self.assertIn('(and 2 more)', message)
  3462. def test_unrelated_edit_allowed_with_existing_cross_chassis_lag(self):
  3463. """
  3464. Pre-existing cross-chassis LAG data must not block edits that leave VC membership unchanged.
  3465. """
  3466. device1 = Device.objects.get(name='TestDevice1')
  3467. device2 = Device.objects.get(name='TestDevice2')
  3468. vc = VirtualChassis.objects.create(name='Test VC', master=device1)
  3469. Device.objects.filter(pk=device1.pk).update(virtual_chassis=vc, vc_position=1)
  3470. lag = Interface.objects.create(device=device1, name='lag0', type=InterfaceTypeChoices.TYPE_LAG)
  3471. Interface.objects.create(
  3472. device=device2, name='eth0', type=InterfaceTypeChoices.TYPE_1GE_FIXED, lag=lag
  3473. )
  3474. device1.refresh_from_db()
  3475. device2.refresh_from_db()
  3476. device1.description = 'changed'
  3477. device1.full_clean()
  3478. device2.description = 'changed'
  3479. device2.full_clean()
  3480. def test_member_removal_allowed_with_local_lag(self):
  3481. """
  3482. A device may leave a VirtualChassis when its LAG members are all local.
  3483. """
  3484. device1 = Device.objects.get(name='TestDevice1')
  3485. device2 = Device.objects.get(name='TestDevice2')
  3486. vc = VirtualChassis.objects.create(name='Test VC', master=device1)
  3487. Device.objects.filter(pk=device1.pk).update(virtual_chassis=vc, vc_position=1)
  3488. Device.objects.filter(pk=device2.pk).update(virtual_chassis=vc, vc_position=2)
  3489. device2.refresh_from_db()
  3490. lag = Interface.objects.create(device=device2, name='lag0', type=InterfaceTypeChoices.TYPE_LAG)
  3491. Interface.objects.create(
  3492. device=device2, name='eth0', type=InterfaceTypeChoices.TYPE_1GE_FIXED, lag=lag
  3493. )
  3494. device2.virtual_chassis = None
  3495. device2.vc_position = None
  3496. device2.full_clean()
  3497. def test_virtualchassis_duplicate_vc_position(self):
  3498. """
  3499. Test that two devices cannot be assigned to the same vc_position
  3500. within the same VirtualChassis.
  3501. """
  3502. devices = Device.objects.all()
  3503. device1 = devices[0]
  3504. device2 = devices[1]
  3505. # Create a VirtualChassis
  3506. vc = VirtualChassis.objects.create(name='Test VC')
  3507. # Assign first device to vc_position 1
  3508. device1.virtual_chassis = vc
  3509. device1.vc_position = 1
  3510. device1.full_clean()
  3511. device1.save()
  3512. # Try to assign second device to the same vc_position
  3513. device2.virtual_chassis = vc
  3514. device2.vc_position = 1
  3515. with self.assertRaises(ValidationError):
  3516. device2.full_clean()
  3517. class VCPositionTokenTestCase(TestCase):
  3518. @classmethod
  3519. def setUpTestData(cls):
  3520. Site.objects.create(name='Test Site 1', slug='test-site-1')
  3521. manufacturer = Manufacturer.objects.create(name='Test Manufacturer 1', slug='test-manufacturer-1')
  3522. DeviceType.objects.create(
  3523. manufacturer=manufacturer, model='Test Device Type 1', slug='test-device-type-1'
  3524. )
  3525. ModuleType.objects.create(
  3526. manufacturer=manufacturer, model='Test Module Type 1'
  3527. )
  3528. DeviceRole.objects.create(name='Test Role 1', slug='test-role-1')
  3529. def test_vc_position_token_in_vc(self):
  3530. site = Site.objects.first()
  3531. device_type = DeviceType.objects.first()
  3532. module_type = ModuleType.objects.first()
  3533. device_role = DeviceRole.objects.first()
  3534. InterfaceTemplate.objects.create(
  3535. module_type=module_type,
  3536. name='ge-{vc_position}/{module}/0',
  3537. type='1000base-t',
  3538. )
  3539. vc = VirtualChassis.objects.create(name='Test VC 1')
  3540. device = Device.objects.create(
  3541. name='Device VC 1', device_type=device_type, role=device_role,
  3542. site=site, virtual_chassis=vc, vc_position=8,
  3543. )
  3544. module_bay = ModuleBay.objects.create(device=device, name='Bay 1', position='1')
  3545. Module.objects.create(device=device, module_bay=module_bay, module_type=module_type)
  3546. interface = device.interfaces.get(name='ge-8/1/0')
  3547. self.assertEqual(interface.name, 'ge-8/1/0')
  3548. def test_vc_position_token_not_in_vc_default_fallback(self):
  3549. site = Site.objects.first()
  3550. device_type = DeviceType.objects.first()
  3551. module_type = ModuleType.objects.first()
  3552. device_role = DeviceRole.objects.first()
  3553. InterfaceTemplate.objects.create(
  3554. module_type=module_type,
  3555. name='ge-{vc_position}/{module}/0',
  3556. type='1000base-t',
  3557. )
  3558. device = Device.objects.create(
  3559. name='Device NoVC 1', device_type=device_type, role=device_role,
  3560. site=site,
  3561. )
  3562. module_bay = ModuleBay.objects.create(device=device, name='Bay 1', position='1')
  3563. Module.objects.create(device=device, module_bay=module_bay, module_type=module_type)
  3564. interface = device.interfaces.get(name='ge-0/1/0')
  3565. self.assertEqual(interface.name, 'ge-0/1/0')
  3566. def test_vc_position_token_explicit_fallback(self):
  3567. site = Site.objects.first()
  3568. device_type = DeviceType.objects.first()
  3569. module_type = ModuleType.objects.first()
  3570. device_role = DeviceRole.objects.first()
  3571. InterfaceTemplate.objects.create(
  3572. module_type=module_type,
  3573. name='ge-{vc_position:18}/{module}/0',
  3574. type='1000base-t',
  3575. )
  3576. device = Device.objects.create(
  3577. name='Device NoVC 2', device_type=device_type, role=device_role,
  3578. site=site,
  3579. )
  3580. module_bay = ModuleBay.objects.create(device=device, name='Bay 1', position='1')
  3581. Module.objects.create(device=device, module_bay=module_bay, module_type=module_type)
  3582. interface = device.interfaces.get(name='ge-18/1/0')
  3583. self.assertEqual(interface.name, 'ge-18/1/0')
  3584. def test_vc_position_token_explicit_fallback_ignored_when_in_vc(self):
  3585. site = Site.objects.first()
  3586. device_type = DeviceType.objects.first()
  3587. module_type = ModuleType.objects.first()
  3588. device_role = DeviceRole.objects.first()
  3589. InterfaceTemplate.objects.create(
  3590. module_type=module_type,
  3591. name='ge-{vc_position:99}/{module}/0',
  3592. type='1000base-t',
  3593. )
  3594. vc = VirtualChassis.objects.create(name='Test VC 2')
  3595. device = Device.objects.create(
  3596. name='Device VC 2', device_type=device_type, role=device_role,
  3597. site=site, virtual_chassis=vc, vc_position=2,
  3598. )
  3599. module_bay = ModuleBay.objects.create(device=device, name='Bay 1', position='1')
  3600. Module.objects.create(device=device, module_bay=module_bay, module_type=module_type)
  3601. interface = device.interfaces.get(name='ge-2/1/0')
  3602. self.assertEqual(interface.name, 'ge-2/1/0')
  3603. def test_vc_position_token_device_type_template(self):
  3604. site = Site.objects.first()
  3605. device_type = DeviceType.objects.first()
  3606. device_role = DeviceRole.objects.first()
  3607. InterfaceTemplate.objects.create(
  3608. device_type=device_type,
  3609. name='ge-{vc_position:0}/0/0',
  3610. type='1000base-t',
  3611. )
  3612. vc = VirtualChassis.objects.create(name='Test VC 3')
  3613. device = Device.objects.create(
  3614. name='Device VC 3', device_type=device_type, role=device_role,
  3615. site=site, virtual_chassis=vc, vc_position=3,
  3616. )
  3617. interface = device.interfaces.get(name='ge-3/0/0')
  3618. self.assertEqual(interface.name, 'ge-3/0/0')
  3619. def test_vc_position_token_device_type_template_not_in_vc(self):
  3620. site = Site.objects.first()
  3621. device_type = DeviceType.objects.first()
  3622. device_role = DeviceRole.objects.first()
  3623. InterfaceTemplate.objects.create(
  3624. device_type=device_type,
  3625. name='ge-{vc_position:0}/0/0',
  3626. type='1000base-t',
  3627. )
  3628. device = Device.objects.create(
  3629. name='Device NoVC 3', device_type=device_type, role=device_role,
  3630. site=site,
  3631. )
  3632. interface = device.interfaces.get(name='ge-0/0/0')
  3633. self.assertEqual(interface.name, 'ge-0/0/0')
  3634. def test_vc_position_token_label_resolution(self):
  3635. site = Site.objects.first()
  3636. device_type = DeviceType.objects.first()
  3637. module_type = ModuleType.objects.first()
  3638. device_role = DeviceRole.objects.first()
  3639. InterfaceTemplate.objects.create(
  3640. module_type=module_type,
  3641. name='ge-{vc_position}/{module}/0',
  3642. label='Member {vc_position:0} / Slot {module}',
  3643. type='1000base-t',
  3644. )
  3645. vc = VirtualChassis.objects.create(name='Test VC 4')
  3646. device = Device.objects.create(
  3647. name='Device VC 4', device_type=device_type, role=device_role,
  3648. site=site, virtual_chassis=vc, vc_position=2,
  3649. )
  3650. module_bay = ModuleBay.objects.create(device=device, name='Bay 1', position='1')
  3651. Module.objects.create(device=device, module_bay=module_bay, module_type=module_type)
  3652. interface = device.interfaces.get(name='ge-2/1/0')
  3653. self.assertEqual(interface.label, 'Member 2 / Slot 1')
  3654. @tag('regression') # Ref: #22707
  3655. def test_vc_position_token_interface_bridge_device_type_template(self):
  3656. site = Site.objects.first()
  3657. device_type = DeviceType.objects.first()
  3658. device_role = DeviceRole.objects.first()
  3659. bridge_template = InterfaceTemplate.objects.create(
  3660. device_type=device_type,
  3661. name='br-{vc_position}',
  3662. type='bridge',
  3663. )
  3664. InterfaceTemplate.objects.create(
  3665. device_type=device_type,
  3666. name='ge-{vc_position}/0/1',
  3667. type='1000base-t',
  3668. bridge=bridge_template,
  3669. )
  3670. vc = VirtualChassis.objects.create(name='Test VC 5')
  3671. device = Device.objects.create(
  3672. name='Device VC 5', device_type=device_type, role=device_role,
  3673. site=site, virtual_chassis=vc, vc_position=5,
  3674. )
  3675. interface = device.interfaces.get(name='ge-5/0/1')
  3676. self.assertEqual(interface.bridge, device.interfaces.get(name='br-5'))
  3677. @tag('regression') # Ref: #22707
  3678. def test_vc_position_token_port_mapping_device_type_template(self):
  3679. site = Site.objects.first()
  3680. device_type = DeviceType.objects.first()
  3681. device_role = DeviceRole.objects.first()
  3682. rear_port_template = RearPortTemplate.objects.create(
  3683. device_type=device_type,
  3684. name='rp-{vc_position}/1',
  3685. type=PortTypeChoices.TYPE_LC,
  3686. positions=1,
  3687. )
  3688. front_port_template = FrontPortTemplate.objects.create(
  3689. device_type=device_type,
  3690. name='fp-{vc_position}/1',
  3691. type=PortTypeChoices.TYPE_LC,
  3692. positions=1,
  3693. )
  3694. PortTemplateMapping.objects.create(
  3695. device_type=device_type,
  3696. front_port=front_port_template,
  3697. front_port_position=1,
  3698. rear_port=rear_port_template,
  3699. rear_port_position=1,
  3700. )
  3701. vc = VirtualChassis.objects.create(name='Test VC 6')
  3702. device = Device.objects.create(
  3703. name='Device VC 6', device_type=device_type, role=device_role,
  3704. site=site, virtual_chassis=vc, vc_position=6,
  3705. )
  3706. front_port = FrontPort.objects.get(device=device, name='fp-6/1')
  3707. rear_port = RearPort.objects.get(device=device, name='rp-6/1')
  3708. mapping = PortMapping.objects.get(device=device, front_port=front_port)
  3709. self.assertEqual(mapping.rear_port, rear_port)
  3710. self.assertEqual(mapping.front_port_position, 1)
  3711. self.assertEqual(mapping.rear_port_position, 1)
  3712. class SiteSignalTestCase(TestCase):
  3713. @tag('regression')
  3714. def test_edit_site_with_prefix_no_vrf(self):
  3715. site = Site.objects.create(name='Test Site', slug='test-site')
  3716. Prefix.objects.create(prefix='192.0.2.0/24', scope=site, vrf=None)
  3717. # Regression test for #21045: should not raise ValueError
  3718. site.save()
  3719. class ComponentTypeImageTestCase(TestCase):
  3720. def test_get_type_image(self):
  3721. for model, choices, value in (
  3722. (ConsolePort, ConsolePortTypeChoices, ConsolePortTypeChoices.TYPE_DE9),
  3723. (ConsoleServerPort, ConsolePortTypeChoices, ConsolePortTypeChoices.TYPE_RJ45),
  3724. (FrontPort, PortTypeChoices, PortTypeChoices.TYPE_8P8C),
  3725. (RearPort, PortTypeChoices, PortTypeChoices.TYPE_LC),
  3726. (PowerPort, PowerPortTypeChoices, PowerPortTypeChoices.TYPE_IEC_C14),
  3727. (PowerOutlet, PowerOutletTypeChoices, PowerOutletTypeChoices.TYPE_IEC_C13),
  3728. ):
  3729. with self.subTest(model=model.__name__):
  3730. self.assertEqual(model(type=value).get_type_image(), choices.images[value])
  3731. self.assertIsNone(model(type=choices.TYPE_OTHER).get_type_image())
  3732. self.assertIsNone(model(type=None).get_type_image())
  3733. class PowerPortDrawTestCase(TestCase):
  3734. """
  3735. Tests for PowerPort.get_power_draw() power aggregation logic.
  3736. """
  3737. @classmethod
  3738. def setUpTestData(cls):
  3739. cls.site = Site.objects.create(name='Test Site', slug='test-site')
  3740. manufacturer = Manufacturer.objects.create(name='Generic', slug='generic')
  3741. device_type = DeviceType.objects.create(manufacturer=manufacturer, model='Test Device Type')
  3742. role = DeviceRole.objects.create(name='Test Role', slug='test-role')
  3743. cls.pdu = Device.objects.create(
  3744. device_type=device_type, role=role, site=cls.site, name='pdu'
  3745. )
  3746. cls.server = Device.objects.create(
  3747. device_type=device_type, role=role, site=cls.site, name='server'
  3748. )
  3749. def test_direct_draw_aggregation(self):
  3750. """
  3751. Sanity check: with one PowerOutlet chained directly to a downstream PSU PowerPort,
  3752. the upstream PowerPort should reflect the PSU's allocated/maximum draw.
  3753. [main] -- [outlet] --C-- [psu]
  3754. """
  3755. main = PowerPort.objects.create(device=self.pdu, name='main')
  3756. outlet = PowerOutlet.objects.create(device=self.pdu, name='outlet', power_port=main)
  3757. psu = PowerPort.objects.create(
  3758. device=self.server, name='psu', allocated_draw=200, maximum_draw=400
  3759. )
  3760. Cable(a_terminations=[outlet], b_terminations=[psu]).save()
  3761. draw = main.get_power_draw()
  3762. self.assertEqual(draw['allocated'], 200)
  3763. self.assertEqual(draw['maximum'], 400)
  3764. @tag('regression')
  3765. def test_recursive_draw_through_intermediate_powerport(self):
  3766. """
  3767. Regression test for #21949: A PDU modeled with internal fuses (intermediate PowerPorts in
  3768. auto mode) should still aggregate downstream PSU draw up to the main PowerPort.
  3769. [main] -- [feedback] --C-- [fuse] -- [outlet] --C-- [psu]
  3770. Both `main` and `fuse` are in auto mode (no allocated_draw/maximum_draw set). The draw
  3771. reported by `psu` must propagate through `fuse` and be reflected at `main`.
  3772. """
  3773. main = PowerPort.objects.create(device=self.pdu, name='main')
  3774. feedback = PowerOutlet.objects.create(device=self.pdu, name='feedback', power_port=main)
  3775. fuse = PowerPort.objects.create(device=self.pdu, name='fuse')
  3776. outlet = PowerOutlet.objects.create(device=self.pdu, name='outlet', power_port=fuse)
  3777. psu = PowerPort.objects.create(
  3778. device=self.server, name='psu', allocated_draw=150, maximum_draw=300
  3779. )
  3780. Cable(a_terminations=[feedback], b_terminations=[fuse]).save()
  3781. Cable(a_terminations=[outlet], b_terminations=[psu]).save()
  3782. fuse_draw = fuse.get_power_draw()
  3783. self.assertEqual(fuse_draw['allocated'], 150)
  3784. self.assertEqual(fuse_draw['maximum'], 300)
  3785. main_draw = main.get_power_draw()
  3786. self.assertEqual(main_draw['allocated'], 150)
  3787. self.assertEqual(main_draw['maximum'], 300)
  3788. def test_intermediate_manual_override_stops_recursion(self):
  3789. """
  3790. When an intermediate PowerPort has an explicit allocated_draw/maximum_draw, recursion should
  3791. stop there and the administratively defined values should be used.
  3792. """
  3793. main = PowerPort.objects.create(device=self.pdu, name='main')
  3794. feedback = PowerOutlet.objects.create(device=self.pdu, name='feedback', power_port=main)
  3795. fuse = PowerPort.objects.create(
  3796. device=self.pdu, name='fuse', allocated_draw=500, maximum_draw=1000
  3797. )
  3798. outlet = PowerOutlet.objects.create(device=self.pdu, name='outlet', power_port=fuse)
  3799. psu = PowerPort.objects.create(
  3800. device=self.server, name='psu', allocated_draw=150, maximum_draw=300
  3801. )
  3802. Cable(a_terminations=[feedback], b_terminations=[fuse]).save()
  3803. Cable(a_terminations=[outlet], b_terminations=[psu]).save()
  3804. main_draw = main.get_power_draw()
  3805. self.assertEqual(main_draw['allocated'], 500)
  3806. self.assertEqual(main_draw['maximum'], 1000)
  3807. def _connect_three_phase_feed(self, powerport):
  3808. """
  3809. Helper: attach `powerport` via cable to a newly-created three-phase PowerFeed.
  3810. """
  3811. power_panel = PowerPanel.objects.create(site=self.site, name='Panel')
  3812. power_feed = PowerFeed.objects.create(
  3813. power_panel=power_panel,
  3814. name='Feed',
  3815. phase=PowerFeedPhaseChoices.PHASE_3PHASE,
  3816. )
  3817. Cable(a_terminations=[powerport], b_terminations=[power_feed]).save()
  3818. @tag('regression')
  3819. def test_three_phase_per_leg_aggregation(self):
  3820. """
  3821. Regression test: per-leg totals for a main PowerPort connected to a three-phase PowerFeed
  3822. must be populated even when the full aggregation runs first. Previously, a shared visited
  3823. set caused downstream ports to be skipped during the per-leg passes, zeroing the legs.
  3824. [main] --C-- [3-phase PowerFeed]
  3825. ├── [outlet_A] (leg A) --C-- [portA] (allocated=100, maximum=200)
  3826. ├── [outlet_B] (leg B) --C-- [portB] (allocated=200, maximum=400)
  3827. └── [outlet_C] (leg C) --C-- [portC] (allocated=300, maximum=600)
  3828. """
  3829. main = PowerPort.objects.create(device=self.pdu, name='main')
  3830. self._connect_three_phase_feed(main)
  3831. leg_specs = [
  3832. (PowerOutletFeedLegChoices.FEED_LEG_A, 100, 200),
  3833. (PowerOutletFeedLegChoices.FEED_LEG_B, 200, 400),
  3834. (PowerOutletFeedLegChoices.FEED_LEG_C, 300, 600),
  3835. ]
  3836. for leg, allocated, maximum in leg_specs:
  3837. outlet = PowerOutlet.objects.create(
  3838. device=self.pdu, name=f'outlet_{leg}', power_port=main, feed_leg=leg
  3839. )
  3840. port = PowerPort.objects.create(
  3841. device=self.server, name=f'psu_{leg}',
  3842. allocated_draw=allocated, maximum_draw=maximum,
  3843. )
  3844. Cable(a_terminations=[outlet], b_terminations=[port]).save()
  3845. # Re-fetch to clear cached_property values populated before cable creation
  3846. main = PowerPort.objects.get(pk=main.pk)
  3847. draw = main.get_power_draw()
  3848. self.assertEqual(draw['allocated'], 600)
  3849. self.assertEqual(draw['maximum'], 1200)
  3850. legs_by_name = {leg['name']: leg for leg in draw['legs']}
  3851. self.assertEqual(legs_by_name['A']['allocated'], 100)
  3852. self.assertEqual(legs_by_name['A']['maximum'], 200)
  3853. self.assertEqual(legs_by_name['B']['allocated'], 200)
  3854. self.assertEqual(legs_by_name['B']['maximum'], 400)
  3855. self.assertEqual(legs_by_name['C']['allocated'], 300)
  3856. self.assertEqual(legs_by_name['C']['maximum'], 600)
  3857. @tag('regression')
  3858. def test_three_phase_per_leg_recursive_aggregation(self):
  3859. """
  3860. Regression test for #21949 on three-phase feeds: per-leg totals must aggregate through
  3861. intermediate auto-mode PowerPorts (the PDU-internal "fuse" pattern).
  3862. [main] --C-- [3-phase PowerFeed]
  3863. └── [feedback_A] (leg A) --C-- [fuse_A] (auto)
  3864. └── [outlet_A] (leg A) --C-- [psu_A] (allocated=100)
  3865. """
  3866. main = PowerPort.objects.create(device=self.pdu, name='main')
  3867. self._connect_three_phase_feed(main)
  3868. feedback = PowerOutlet.objects.create(
  3869. device=self.pdu, name='feedback_A', power_port=main,
  3870. feed_leg=PowerOutletFeedLegChoices.FEED_LEG_A,
  3871. )
  3872. fuse = PowerPort.objects.create(device=self.pdu, name='fuse_A')
  3873. outlet = PowerOutlet.objects.create(
  3874. device=self.pdu, name='outlet_A', power_port=fuse,
  3875. feed_leg=PowerOutletFeedLegChoices.FEED_LEG_A,
  3876. )
  3877. psu = PowerPort.objects.create(
  3878. device=self.server, name='psu_A', allocated_draw=100, maximum_draw=200
  3879. )
  3880. Cable(a_terminations=[feedback], b_terminations=[fuse]).save()
  3881. Cable(a_terminations=[outlet], b_terminations=[psu]).save()
  3882. # Re-fetch to clear cached_property values populated before cable creation
  3883. main = PowerPort.objects.get(pk=main.pk)
  3884. draw = main.get_power_draw()
  3885. self.assertEqual(draw['allocated'], 100)
  3886. self.assertEqual(draw['maximum'], 200)
  3887. legs_by_name = {leg['name']: leg for leg in draw['legs']}
  3888. self.assertEqual(legs_by_name['A']['allocated'], 100)
  3889. self.assertEqual(legs_by_name['A']['maximum'], 200)
  3890. self.assertEqual(legs_by_name['B']['allocated'], 0)
  3891. self.assertEqual(legs_by_name['C']['allocated'], 0)
  3892. class InventoryItemCycleTestCase(TestCase):
  3893. """
  3894. InventoryItem (ltree-backed, not the nested-group base) must reject assigning
  3895. self or a descendant as parent — behavior django-mptt previously enforced via
  3896. InvalidMove on save().
  3897. """
  3898. @classmethod
  3899. def setUpTestData(cls):
  3900. site = Site.objects.create(name='Site 1', slug='inv-site-1')
  3901. manufacturer = Manufacturer.objects.create(name='Manufacturer 1', slug='inv-mfr-1')
  3902. device_type = DeviceType.objects.create(
  3903. manufacturer=manufacturer, model='Device Type 1', slug='inv-dt-1'
  3904. )
  3905. role = DeviceRole.objects.create(name='Role 1', slug='inv-role-1')
  3906. cls.device = Device.objects.create(
  3907. name='Device 1', device_type=device_type, role=role, site=site
  3908. )
  3909. def test_cannot_assign_descendant_as_parent(self):
  3910. a = InventoryItem.objects.create(device=self.device, name='A')
  3911. b = InventoryItem.objects.create(device=self.device, name='B', parent=a)
  3912. c = InventoryItem.objects.create(device=self.device, name='C', parent=b)
  3913. a.parent = c
  3914. with self.assertRaises(ValidationError):
  3915. a.full_clean()
  3916. # The save()-level guard also rejects the cycle when clean() is bypassed.
  3917. with self.assertRaises(ValidationError):
  3918. a.save()
  3919. def test_cannot_assign_self_as_parent(self):
  3920. a = InventoryItem.objects.create(device=self.device, name='A')
  3921. a.parent = a
  3922. with self.assertRaises(ValidationError):
  3923. a.full_clean()
  3924. class InventoryItemTemplateCycleTestCase(TestCase):
  3925. """InventoryItemTemplate must likewise reject self/descendant as parent."""
  3926. @classmethod
  3927. def setUpTestData(cls):
  3928. manufacturer = Manufacturer.objects.create(name='Manufacturer 1', slug='iit-mfr-1')
  3929. cls.device_type = DeviceType.objects.create(
  3930. manufacturer=manufacturer, model='Device Type 1', slug='iit-dt-1'
  3931. )
  3932. def test_cannot_assign_descendant_as_parent(self):
  3933. a = InventoryItemTemplate.objects.create(device_type=self.device_type, name='A')
  3934. b = InventoryItemTemplate.objects.create(device_type=self.device_type, name='B', parent=a)
  3935. a.parent = b
  3936. with self.assertRaises(ValidationError):
  3937. a.full_clean()
  3938. with self.assertRaises(ValidationError):
  3939. a.save()
  3940. def test_cannot_assign_self_as_parent(self):
  3941. a = InventoryItemTemplate.objects.create(device_type=self.device_type, name='A')
  3942. a.parent = a
  3943. with self.assertRaises(ValidationError):
  3944. a.full_clean()
  3945. class CoolingComponentTestCase(TestCase):
  3946. @classmethod
  3947. def setUpTestData(cls):
  3948. cls.site = Site.objects.create(name='Site 1', slug='site-1')
  3949. cls.manufacturer = Manufacturer.objects.create(name='Manufacturer 1', slug='manufacturer-1')
  3950. cls.role = DeviceRole.objects.create(name='Device Role 1', slug='device-role-1')
  3951. def test_cooling_method_inherited_from_device_type(self):
  3952. """
  3953. A new Device should inherit its cooling_method from the DeviceType when not explicitly set.
  3954. """
  3955. device_type = DeviceType.objects.create(
  3956. manufacturer=self.manufacturer,
  3957. model='Device Type 1',
  3958. slug='device-type-1',
  3959. cooling_method=CoolingMethodChoices.METHOD_LIQUID
  3960. )
  3961. device = Device.objects.create(
  3962. site=self.site,
  3963. device_type=device_type,
  3964. role=self.role,
  3965. name='Device 1'
  3966. )
  3967. self.assertEqual(device.cooling_method, CoolingMethodChoices.METHOD_LIQUID)
  3968. def test_cooling_method_not_overridden_when_set(self):
  3969. """
  3970. A new Device with an explicitly-set cooling_method should not be overridden by the DeviceType.
  3971. """
  3972. device_type = DeviceType.objects.create(
  3973. manufacturer=self.manufacturer,
  3974. model='Device Type 2',
  3975. slug='device-type-2',
  3976. cooling_method=CoolingMethodChoices.METHOD_LIQUID
  3977. )
  3978. device = Device.objects.create(
  3979. site=self.site,
  3980. device_type=device_type,
  3981. role=self.role,
  3982. name='Device 2',
  3983. cooling_method=CoolingMethodChoices.METHOD_AIR
  3984. )
  3985. self.assertEqual(device.cooling_method, CoolingMethodChoices.METHOD_AIR)
  3986. def test_device_creation_instantiates_cooling_components(self):
  3987. """
  3988. Creating a Device from a DeviceType with cooling component templates should auto-instantiate
  3989. matching CoolingIntake and CoolingOutflow components.
  3990. """
  3991. device_type = DeviceType.objects.create(
  3992. manufacturer=self.manufacturer,
  3993. model='Device Type 3',
  3994. slug='device-type-3'
  3995. )
  3996. cooling_intake_template = CoolingIntakeTemplate.objects.create(
  3997. device_type=device_type,
  3998. name='Cooling Port 1',
  3999. type=CoolingConnectorTypeChoices.TYPE_UQD,
  4000. diameter=Decimal('25'),
  4001. diameter_unit=DiameterUnitChoices.UNIT_MILLIMETER,
  4002. max_flow=100,
  4003. max_flow_unit=FlowRateUnitChoices.UNIT_LITERS_PER_MINUTE
  4004. )
  4005. CoolingOutflowTemplate.objects.create(
  4006. device_type=device_type,
  4007. name='Cooling Outlet 1',
  4008. type=CoolingConnectorTypeChoices.TYPE_UQD,
  4009. diameter=Decimal('25'),
  4010. diameter_unit=DiameterUnitChoices.UNIT_MILLIMETER
  4011. )
  4012. device = Device.objects.create(
  4013. site=self.site,
  4014. device_type=device_type,
  4015. role=self.role,
  4016. name='Device 3'
  4017. )
  4018. cooling_intake = CoolingIntake.objects.get(
  4019. device=device,
  4020. name='Cooling Port 1',
  4021. type=CoolingConnectorTypeChoices.TYPE_UQD,
  4022. diameter=Decimal('25'),
  4023. diameter_unit=DiameterUnitChoices.UNIT_MILLIMETER,
  4024. max_flow=100,
  4025. max_flow_unit=FlowRateUnitChoices.UNIT_LITERS_PER_MINUTE
  4026. )
  4027. self.assertEqual(cooling_intake_template.max_flow, cooling_intake.max_flow)
  4028. CoolingOutflow.objects.get(
  4029. device=device,
  4030. name='Cooling Outlet 1',
  4031. type=CoolingConnectorTypeChoices.TYPE_UQD,
  4032. diameter=Decimal('25'),
  4033. diameter_unit=DiameterUnitChoices.UNIT_MILLIMETER
  4034. )
  4035. def test_cooling_choice_colors_resolve(self):
  4036. """
  4037. ChoiceFieldColumn and ChoiceAttr both render a badge color by calling get_FOO_color() on the
  4038. instance, so every model exposing a colored cooling choice must implement the accessor.
  4039. """
  4040. for model in (Device, DeviceType, ModuleType):
  4041. with self.subTest(model=model.__name__):
  4042. instance = model(cooling_method=CoolingMethodChoices.METHOD_LIQUID)
  4043. self.assertEqual(
  4044. instance.get_cooling_method_color(),
  4045. CoolingMethodChoices.colors[CoolingMethodChoices.METHOD_LIQUID]
  4046. )
  4047. # An unset value has no color, which the consumers fall back on
  4048. self.assertIsNone(model().get_cooling_method_color())
  4049. for model in (Rack, RackType):
  4050. with self.subTest(model=model.__name__):
  4051. instance = model(cooling_capability=RackCoolingCapabilityChoices.CAPABILITY_HYBRID)
  4052. self.assertEqual(
  4053. instance.get_cooling_capability_color(),
  4054. RackCoolingCapabilityChoices.colors[RackCoolingCapabilityChoices.CAPABILITY_HYBRID]
  4055. )
  4056. self.assertIsNone(model().get_cooling_capability_color())
  4057. def test_measurements_below_minimum_rejected(self):
  4058. """
  4059. A populated diameter or flow rate must be positive and non-zero: anything below the smallest storable
  4060. value (0.01) should raise a ValidationError (via MinValueValidator) rather than a raw ValueError from
  4061. the unit conversion in save().
  4062. """
  4063. device_type = DeviceType.objects.create(
  4064. manufacturer=self.manufacturer, model='Device Type 8', slug='device-type-8'
  4065. )
  4066. device = Device.objects.create(
  4067. site=self.site, device_type=device_type, role=self.role, name='Device F'
  4068. )
  4069. cooling_source = CoolingSource.objects.create(
  4070. site=self.site, name='Cooling Source F', type=CoolingSourceTypeChoices.TYPE_CHILLER
  4071. )
  4072. for value in (Decimal('-5'), Decimal('0')):
  4073. with self.subTest(diameter=value):
  4074. cooling_intake = CoolingIntake(
  4075. device=device,
  4076. name='Cooling Port 1',
  4077. diameter=value,
  4078. diameter_unit=DiameterUnitChoices.UNIT_MILLIMETER,
  4079. )
  4080. with self.assertRaises(ValidationError):
  4081. cooling_intake.full_clean()
  4082. with self.subTest(max_flow=value):
  4083. cooling_intake = CoolingIntake(
  4084. device=device,
  4085. name='Cooling Port 1',
  4086. max_flow=value,
  4087. max_flow_unit=FlowRateUnitChoices.UNIT_LITERS_PER_MINUTE,
  4088. )
  4089. with self.assertRaises(ValidationError):
  4090. cooling_intake.full_clean()
  4091. with self.subTest(feed_max_flow=value):
  4092. cooling_feed = CoolingFeed(
  4093. cooling_source=cooling_source,
  4094. name='Cooling Feed F',
  4095. max_flow=value,
  4096. max_flow_unit=FlowRateUnitChoices.UNIT_LITERS_PER_MINUTE,
  4097. )
  4098. with self.assertRaises(ValidationError):
  4099. cooling_feed.full_clean()
  4100. # The minimum itself is permitted
  4101. CoolingIntake(
  4102. device=device,
  4103. name='Cooling Port 1',
  4104. diameter=Decimal('0.01'),
  4105. diameter_unit=DiameterUnitChoices.UNIT_MILLIMETER,
  4106. max_flow=Decimal('0.01'),
  4107. max_flow_unit=FlowRateUnitChoices.UNIT_LITERS_PER_MINUTE,
  4108. ).full_clean()
  4109. # Sub-unit values are permitted: fractional-inch fittings (e.g. 1/2" NPT) and cold plates rated below
  4110. # one gallon per minute are both commonplace.
  4111. CoolingIntake(
  4112. device=device,
  4113. name='Cooling Port 1',
  4114. diameter=Decimal('0.5'),
  4115. diameter_unit=DiameterUnitChoices.UNIT_INCH,
  4116. max_flow=Decimal('0.75'),
  4117. max_flow_unit=FlowRateUnitChoices.UNIT_GALLONS_PER_MINUTE,
  4118. ).full_clean()
  4119. CoolingFeed(
  4120. cooling_source=cooling_source,
  4121. name='Cooling Feed F',
  4122. max_flow=Decimal('0.5'),
  4123. max_flow_unit=FlowRateUnitChoices.UNIT_GALLONS_PER_MINUTE,
  4124. ).full_clean()
  4125. def test_parent_intake_resolved_on_device_instantiation(self):
  4126. """
  4127. A CoolingOutflowTemplate with a parent CoolingIntakeTemplate should resolve to the newly created
  4128. CoolingIntake on the same device. This depends on intakes being instantiated before outflows.
  4129. """
  4130. device_type = DeviceType.objects.create(
  4131. manufacturer=self.manufacturer, model='Device Type 12', slug='device-type-12'
  4132. )
  4133. cooling_intake_template = CoolingIntakeTemplate.objects.create(
  4134. device_type=device_type, name='Cooling Port 1'
  4135. )
  4136. CoolingOutflowTemplate.objects.create(
  4137. device_type=device_type, name='Cooling Outlet 1', cooling_intake=cooling_intake_template
  4138. )
  4139. # A second outflow with no parent must remain unassigned
  4140. CoolingOutflowTemplate.objects.create(device_type=device_type, name='Cooling Outlet 2')
  4141. device = Device.objects.create(
  4142. site=self.site, device_type=device_type, role=self.role, name='Device J'
  4143. )
  4144. cooling_intake = CoolingIntake.objects.get(device=device, name='Cooling Port 1')
  4145. self.assertEqual(
  4146. CoolingOutflow.objects.get(device=device, name='Cooling Outlet 1').cooling_intake,
  4147. cooling_intake
  4148. )
  4149. self.assertIsNone(CoolingOutflow.objects.get(device=device, name='Cooling Outlet 2').cooling_intake)
  4150. def test_parent_intake_resolved_on_module_instantiation(self):
  4151. """
  4152. The parent intake of a CoolingOutflowTemplate should likewise resolve when the components are
  4153. instantiated for a Module rather than a Device.
  4154. """
  4155. device_type = DeviceType.objects.create(
  4156. manufacturer=self.manufacturer, model='Device Type 13', slug='device-type-13'
  4157. )
  4158. device = Device.objects.create(
  4159. site=self.site, device_type=device_type, role=self.role, name='Device K'
  4160. )
  4161. module_bay = ModuleBay.objects.create(device=device, name='Module Bay 1')
  4162. module_type = ModuleType.objects.create(manufacturer=self.manufacturer, model='Module Type 1')
  4163. cooling_intake_template = CoolingIntakeTemplate.objects.create(
  4164. module_type=module_type, name='Cooling Port 1'
  4165. )
  4166. CoolingOutflowTemplate.objects.create(
  4167. module_type=module_type, name='Cooling Outlet 1', cooling_intake=cooling_intake_template
  4168. )
  4169. module = Module.objects.create(device=device, module_bay=module_bay, module_type=module_type)
  4170. cooling_intake = CoolingIntake.objects.get(module=module, name='Cooling Port 1')
  4171. cooling_outflow = CoolingOutflow.objects.get(module=module, name='Cooling Outlet 1')
  4172. self.assertEqual(cooling_outflow.cooling_intake, cooling_intake)
  4173. self.assertEqual(cooling_outflow.device, device)
  4174. def test_measurements_normalized_on_save(self):
  4175. """
  4176. Saving a component should populate the normalized _abs_* columns, converting from the selected
  4177. unit to the canonical unit (millimeters for diameter, liters per minute for flow).
  4178. """
  4179. device_type = DeviceType.objects.create(
  4180. manufacturer=self.manufacturer, model='Device Type 9', slug='device-type-9'
  4181. )
  4182. device = Device.objects.create(
  4183. site=self.site, device_type=device_type, role=self.role, name='Device G'
  4184. )
  4185. cooling_intake = CoolingIntake.objects.create(
  4186. device=device,
  4187. name='Cooling Port 1',
  4188. diameter=Decimal('1'),
  4189. diameter_unit=DiameterUnitChoices.UNIT_INCH,
  4190. max_flow=Decimal('10'),
  4191. max_flow_unit=FlowRateUnitChoices.UNIT_GALLONS_PER_MINUTE,
  4192. )
  4193. cooling_intake.refresh_from_db()
  4194. self.assertEqual(cooling_intake._abs_diameter, Decimal('25.4'))
  4195. self.assertEqual(cooling_intake._abs_max_flow, Decimal('37.8541'))
  4196. # The public aliases used by templates should mirror the underscore-prefixed columns
  4197. self.assertEqual(cooling_intake.abs_diameter, cooling_intake._abs_diameter)
  4198. self.assertEqual(cooling_intake.abs_max_flow, cooling_intake._abs_max_flow)
  4199. # Clearing a value should null both its unit and its normalized column
  4200. cooling_intake.diameter = None
  4201. cooling_intake.max_flow = None
  4202. cooling_intake.save()
  4203. cooling_intake.refresh_from_db()
  4204. self.assertIsNone(cooling_intake.diameter_unit)
  4205. self.assertIsNone(cooling_intake._abs_diameter)
  4206. self.assertIsNone(cooling_intake.max_flow_unit)
  4207. self.assertIsNone(cooling_intake._abs_max_flow)
  4208. def test_measurements_normalized_on_component_instantiation(self):
  4209. """
  4210. Components instantiated from templates are written via bulk_create, which bypasses save(); the
  4211. normalized _abs_* columns must still be populated.
  4212. """
  4213. device_type = DeviceType.objects.create(
  4214. manufacturer=self.manufacturer, model='Device Type 10', slug='device-type-10'
  4215. )
  4216. CoolingIntakeTemplate.objects.create(
  4217. device_type=device_type,
  4218. name='Cooling Port 1',
  4219. diameter=Decimal('1'),
  4220. diameter_unit=DiameterUnitChoices.UNIT_INCH,
  4221. max_flow=Decimal('6'),
  4222. max_flow_unit=FlowRateUnitChoices.UNIT_CUBIC_METERS_PER_HOUR,
  4223. )
  4224. CoolingOutflowTemplate.objects.create(
  4225. device_type=device_type,
  4226. name='Cooling Outlet 1',
  4227. diameter=Decimal('2.5'),
  4228. diameter_unit=DiameterUnitChoices.UNIT_CENTIMETER,
  4229. )
  4230. device = Device.objects.create(
  4231. site=self.site, device_type=device_type, role=self.role, name='Device H'
  4232. )
  4233. cooling_intake = CoolingIntake.objects.get(device=device, name='Cooling Port 1')
  4234. self.assertEqual(cooling_intake._abs_diameter, Decimal('25.4'))
  4235. self.assertEqual(cooling_intake._abs_max_flow, Decimal('100'))
  4236. cooling_outflow = CoolingOutflow.objects.get(device=device, name='Cooling Outlet 1')
  4237. self.assertEqual(cooling_outflow._abs_diameter, Decimal('25'))
  4238. def test_measurement_unit_required(self):
  4239. """
  4240. Setting a measurement without its accompanying unit should raise a ValidationError.
  4241. """
  4242. device_type = DeviceType.objects.create(
  4243. manufacturer=self.manufacturer, model='Device Type 11', slug='device-type-11'
  4244. )
  4245. device = Device.objects.create(
  4246. site=self.site, device_type=device_type, role=self.role, name='Device I'
  4247. )
  4248. with self.assertRaises(ValidationError):
  4249. CoolingIntake(device=device, name='Cooling Port 1', diameter=Decimal('25')).full_clean()
  4250. with self.assertRaises(ValidationError):
  4251. CoolingIntake(device=device, name='Cooling Port 2', max_flow=Decimal('100')).full_clean()
  4252. with self.assertRaises(ValidationError):
  4253. CoolingOutflow(device=device, name='Cooling Outlet 1', diameter=Decimal('25')).full_clean()
  4254. def test_cooling_feed_flow_normalized(self):
  4255. """
  4256. CoolingFeed shares the flow-rate normalization applied to device components, and likewise requires
  4257. a unit whenever a flow rate is set.
  4258. """
  4259. cooling_source = CoolingSource.objects.create(
  4260. site=self.site,
  4261. name='Cooling Source 1',
  4262. type=CoolingSourceTypeChoices.TYPE_CHILLER,
  4263. )
  4264. cooling_feed = CoolingFeed.objects.create(
  4265. cooling_source=cooling_source,
  4266. name='Cooling Feed 1',
  4267. max_flow=Decimal('6'),
  4268. max_flow_unit=FlowRateUnitChoices.UNIT_CUBIC_METERS_PER_HOUR,
  4269. )
  4270. cooling_feed.refresh_from_db()
  4271. self.assertEqual(cooling_feed._abs_max_flow, Decimal('100'))
  4272. self.assertEqual(cooling_feed.abs_max_flow, cooling_feed._abs_max_flow)
  4273. with self.assertRaises(ValidationError):
  4274. CoolingFeed(
  4275. cooling_source=cooling_source, name='Cooling Feed 2', max_flow=Decimal('100')
  4276. ).full_clean()
  4277. def test_cooling_outflow_clean_different_device(self):
  4278. """
  4279. CoolingOutflow.clean() should raise a ValidationError when its cooling_intake belongs to a
  4280. different device.
  4281. """
  4282. device_type = DeviceType.objects.create(
  4283. manufacturer=self.manufacturer,
  4284. model='Device Type 4',
  4285. slug='device-type-4'
  4286. )
  4287. device1 = Device.objects.create(
  4288. site=self.site, device_type=device_type, role=self.role, name='Device A'
  4289. )
  4290. device2 = Device.objects.create(
  4291. site=self.site, device_type=device_type, role=self.role, name='Device B'
  4292. )
  4293. cooling_intake = CoolingIntake.objects.create(device=device1, name='Cooling Port 1')
  4294. cooling_outflow = CoolingOutflow(device=device2, name='Cooling Outlet 1', cooling_intake=cooling_intake)
  4295. with self.assertRaises(ValidationError):
  4296. cooling_outflow.full_clean()
  4297. def test_cooling_source_location_site_mismatch(self):
  4298. """
  4299. CoolingSource.clean() should raise a ValidationError when its location belongs to a different site.
  4300. """
  4301. site2 = Site.objects.create(name='Site 2', slug='site-2')
  4302. location = Location.objects.create(name='Location 1', slug='location-1', site=site2)
  4303. cooling_source = CoolingSource(
  4304. site=self.site,
  4305. location=location,
  4306. name='Cooling Source 1',
  4307. type=CoolingSourceTypeChoices.TYPE_CHILLER,
  4308. status=CoolingSourceStatusChoices.STATUS_ACTIVE,
  4309. )
  4310. with self.assertRaises(ValidationError):
  4311. cooling_source.full_clean()
  4312. def test_cooling_feed_rack_site_mismatch(self):
  4313. """
  4314. CoolingFeed.clean() should raise a ValidationError when its rack is in a different site than the
  4315. cooling source.
  4316. """
  4317. site2 = Site.objects.create(name='Site 3', slug='site-3')
  4318. cooling_source = CoolingSource.objects.create(
  4319. site=self.site,
  4320. name='Cooling Source 3',
  4321. type=CoolingSourceTypeChoices.TYPE_CHILLER,
  4322. status=CoolingSourceStatusChoices.STATUS_ACTIVE,
  4323. )
  4324. rack = Rack.objects.create(name='Rack 1', site=site2, status=RackStatusChoices.STATUS_ACTIVE)
  4325. cooling_feed = CoolingFeed(
  4326. cooling_source=cooling_source,
  4327. rack=rack,
  4328. name='Cooling Feed 1',
  4329. status=CoolingFeedStatusChoices.STATUS_ACTIVE,
  4330. )
  4331. with self.assertRaises(ValidationError):
  4332. cooling_feed.full_clean()
  4333. def test_cooling_chain_valid(self):
  4334. """
  4335. A non-looping intake/outflow assignment should pass validation.
  4336. """
  4337. device_type = DeviceType.objects.create(
  4338. manufacturer=self.manufacturer, model='Device Type 5', slug='device-type-5'
  4339. )
  4340. device = Device.objects.create(
  4341. site=self.site, device_type=device_type, role=self.role, name='Device C'
  4342. )
  4343. cooling_outflow = CoolingOutflow.objects.create(device=device, name='Cooling Outlet 1')
  4344. cooling_intake = CoolingIntake(device=device, name='Cooling Port 1', cooling_outflow=cooling_outflow)
  4345. # Should not raise
  4346. cooling_intake.full_clean()
  4347. def test_cooling_intake_loop_rejected(self):
  4348. """
  4349. Closing the intake/outflow chain into a loop from the intake side should raise a ValidationError.
  4350. """
  4351. device_type = DeviceType.objects.create(
  4352. manufacturer=self.manufacturer, model='Device Type 6', slug='device-type-6'
  4353. )
  4354. device = Device.objects.create(
  4355. site=self.site, device_type=device_type, role=self.role, name='Device D'
  4356. )
  4357. cooling_intake = CoolingIntake.objects.create(device=device, name='Cooling Port 1')
  4358. cooling_outflow = CoolingOutflow.objects.create(
  4359. device=device, name='Cooling Outlet 1', cooling_intake=cooling_intake
  4360. )
  4361. # The outflow is fed by the intake; supplying that same intake from the outflow closes the loop
  4362. cooling_intake.cooling_outflow = cooling_outflow
  4363. with self.assertRaises(ValidationError):
  4364. cooling_intake.full_clean()
  4365. def test_cooling_outflow_loop_rejected(self):
  4366. """
  4367. Closing the intake/outflow chain into a loop from the outflow side should raise a ValidationError.
  4368. """
  4369. device_type = DeviceType.objects.create(
  4370. manufacturer=self.manufacturer, model='Device Type 7', slug='device-type-7'
  4371. )
  4372. device = Device.objects.create(
  4373. site=self.site, device_type=device_type, role=self.role, name='Device E'
  4374. )
  4375. cooling_outflow = CoolingOutflow.objects.create(device=device, name='Cooling Outlet 1')
  4376. cooling_intake = CoolingIntake.objects.create(
  4377. device=device, name='Cooling Port 1', cooling_outflow=cooling_outflow
  4378. )
  4379. # The intake is supplied by the outflow; feeding that same intake into the outflow closes the loop
  4380. cooling_outflow.cooling_intake = cooling_intake
  4381. with self.assertRaises(ValidationError):
  4382. cooling_outflow.full_clean()
  4383. def test_instantiate_clears_unit_without_value(self):
  4384. """
  4385. bulk_create() bypasses save(), so instantiate() must itself clear a unit whose value is unset.
  4386. """
  4387. device_type = DeviceType.objects.create(
  4388. manufacturer=self.manufacturer, model='Device Type 8', slug='device-type-8'
  4389. )
  4390. intake_template = CoolingIntakeTemplate.objects.create(
  4391. device_type=device_type,
  4392. name='Cooling Port 1',
  4393. diameter=Decimal('10'),
  4394. diameter_unit=DiameterUnitChoices.UNIT_MILLIMETER,
  4395. max_flow=Decimal('5'),
  4396. max_flow_unit=FlowRateUnitChoices.UNIT_LITERS_PER_MINUTE,
  4397. )
  4398. outflow_template = CoolingOutflowTemplate.objects.create(
  4399. device_type=device_type,
  4400. name='Cooling Outlet 1',
  4401. diameter=Decimal('10'),
  4402. diameter_unit=DiameterUnitChoices.UNIT_MILLIMETER,
  4403. )
  4404. # Leave the units dangling without passing through save()
  4405. CoolingIntakeTemplate.objects.filter(pk=intake_template.pk).update(diameter=None, max_flow=None)
  4406. CoolingOutflowTemplate.objects.filter(pk=outflow_template.pk).update(diameter=None)
  4407. device = Device.objects.create(
  4408. site=self.site, device_type=device_type, role=self.role, name='Device F'
  4409. )
  4410. cooling_intake = CoolingIntake.objects.get(device=device, name='Cooling Port 1')
  4411. self.assertIsNone(cooling_intake.diameter)
  4412. self.assertIsNone(cooling_intake.diameter_unit)
  4413. self.assertIsNone(cooling_intake.max_flow)
  4414. self.assertIsNone(cooling_intake.max_flow_unit)
  4415. cooling_outflow = CoolingOutflow.objects.get(device=device, name='Cooling Outlet 1')
  4416. self.assertIsNone(cooling_outflow.diameter)
  4417. self.assertIsNone(cooling_outflow.diameter_unit)
  4418. def test_negative_measurements_rejected_by_database(self):
  4419. """
  4420. A negative diameter or max flow must not reach the database, even through a write which skips validation.
  4421. """
  4422. device_type = DeviceType.objects.create(
  4423. manufacturer=self.manufacturer, model='Device Type 9', slug='device-type-9'
  4424. )
  4425. device = Device.objects.create(
  4426. site=self.site, device_type=device_type, role=self.role, name='Device G'
  4427. )
  4428. writes = {
  4429. CoolingIntakeTemplate: CoolingIntakeTemplate.objects.create(device_type=device_type, name='Intake 1'),
  4430. CoolingOutflowTemplate: CoolingOutflowTemplate.objects.create(device_type=device_type, name='Outflow 1'),
  4431. CoolingIntake: CoolingIntake.objects.create(device=device, name='Intake 1'),
  4432. CoolingOutflow: CoolingOutflow.objects.create(device=device, name='Outflow 1'),
  4433. }
  4434. for model, instance in writes.items():
  4435. with self.subTest(model=model.__name__, field='diameter'):
  4436. with self.assertRaises(IntegrityError), transaction.atomic():
  4437. model.objects.filter(pk=instance.pk).update(
  4438. diameter=Decimal('-1'), diameter_unit=DiameterUnitChoices.UNIT_MILLIMETER
  4439. )
  4440. for model in (CoolingIntakeTemplate, CoolingIntake):
  4441. with self.subTest(model=model.__name__, field='max_flow'):
  4442. with self.assertRaises(IntegrityError), transaction.atomic():
  4443. model.objects.filter(pk=writes[model].pk).update(
  4444. max_flow=Decimal('-1'), max_flow_unit=FlowRateUnitChoices.UNIT_LITERS_PER_MINUTE
  4445. )