test_models.py 168 KB

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