test_models.py 197 KB

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