test_models.py 203 KB

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