test_models.py 107 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830
  1. from django.core.exceptions import ValidationError
  2. from django.db.models.signals import post_save
  3. from django.test import TestCase, tag
  4. from circuits.models import *
  5. from core.models import ObjectType
  6. from dcim.choices import *
  7. from dcim.models import *
  8. from extras.events import serialize_for_event
  9. from extras.models import CustomField
  10. from ipam.models import Prefix
  11. from netbox.choices import WeightUnitChoices
  12. from tenancy.models import Tenant
  13. from utilities.data import drange
  14. from virtualization.models import Cluster, ClusterType
  15. class MACAddressTestCase(TestCase):
  16. @classmethod
  17. def setUpTestData(cls):
  18. site = Site.objects.create(name='Test Site 1', slug='test-site-1')
  19. manufacturer = Manufacturer.objects.create(name='Test Manufacturer 1', slug='test-manufacturer-1')
  20. device_type = DeviceType.objects.create(
  21. manufacturer=manufacturer, model='Test Device Type 1', slug='test-device-type-1'
  22. )
  23. device_role = DeviceRole.objects.create(name='Test Role 1', slug='test-role-1')
  24. device = Device.objects.create(
  25. name='Device 1', device_type=device_type, role=device_role, site=site,
  26. )
  27. cls.interface = Interface.objects.create(
  28. device=device,
  29. name='Interface 1',
  30. type=InterfaceTypeChoices.TYPE_1GE_FIXED,
  31. mgmt_only=True
  32. )
  33. cls.mac_a = MACAddress.objects.create(mac_address='1234567890ab', assigned_object=cls.interface)
  34. cls.mac_b = MACAddress.objects.create(mac_address='1234567890ba', assigned_object=cls.interface)
  35. cls.interface.primary_mac_address = cls.mac_a
  36. cls.interface.save()
  37. @tag('regression')
  38. def test_clean_will_not_allow_removal_of_assigned_object_if_primary(self):
  39. self.mac_a.assigned_object = None
  40. with self.assertRaisesMessage(ValidationError, 'Cannot unassign MAC Address while'):
  41. self.mac_a.clean()
  42. @tag('regression')
  43. def test_clean_will_allow_removal_of_assigned_object_if_not_primary(self):
  44. self.mac_b.assigned_object = None
  45. self.mac_b.clean()
  46. class LocationTestCase(TestCase):
  47. def test_change_location_site(self):
  48. """
  49. Check that all child Locations and Racks get updated when a Location is moved to a new Site. Topology:
  50. Site A
  51. - Location A1
  52. - Location A2
  53. - Rack 2
  54. - Device 2
  55. - Rack 1
  56. - Device 1
  57. """
  58. manufacturer = Manufacturer.objects.create(name='Manufacturer 1', slug='manufacturer-1')
  59. device_type = DeviceType.objects.create(
  60. manufacturer=manufacturer, model='Device Type 1', slug='device-type-1'
  61. )
  62. role = DeviceRole.objects.create(
  63. name='Device Role 1', slug='device-role-1', color='ff0000'
  64. )
  65. site_a = Site.objects.create(name='Site A', slug='site-a')
  66. site_b = Site.objects.create(name='Site B', slug='site-b')
  67. location_a1 = Location(site=site_a, name='Location A1', slug='location-a1')
  68. location_a1.save()
  69. location_a2 = Location(site=site_a, parent=location_a1, name='Location A2', slug='location-a2')
  70. location_a2.save()
  71. rack1 = Rack.objects.create(site=site_a, location=location_a1, name='Rack 1')
  72. rack2 = Rack.objects.create(site=site_a, location=location_a2, name='Rack 2')
  73. device1 = Device.objects.create(
  74. site=site_a,
  75. location=location_a1,
  76. name='Device 1',
  77. device_type=device_type,
  78. role=role
  79. )
  80. device2 = Device.objects.create(
  81. site=site_a,
  82. location=location_a2,
  83. name='Device 2',
  84. device_type=device_type,
  85. role=role
  86. )
  87. powerpanel1 = PowerPanel.objects.create(site=site_a, location=location_a1, name='Power Panel 1')
  88. # Move Location A1 to Site B
  89. location_a1.site = site_b
  90. location_a1.save()
  91. # Check that all objects within Location A1 now belong to Site B
  92. self.assertEqual(Location.objects.get(pk=location_a1.pk).site, site_b)
  93. self.assertEqual(Location.objects.get(pk=location_a2.pk).site, site_b)
  94. self.assertEqual(Rack.objects.get(pk=rack1.pk).site, site_b)
  95. self.assertEqual(Rack.objects.get(pk=rack2.pk).site, site_b)
  96. self.assertEqual(Device.objects.get(pk=device1.pk).site, site_b)
  97. self.assertEqual(Device.objects.get(pk=device2.pk).site, site_b)
  98. self.assertEqual(PowerPanel.objects.get(pk=powerpanel1.pk).site, site_b)
  99. class DeviceTypeTestCase(TestCase):
  100. def test_component_template_counts(self):
  101. """
  102. DeviceType component template counters should track the addition and removal of templates.
  103. """
  104. manufacturer = Manufacturer.objects.create(name='Manufacturer 1', slug='manufacturer-1')
  105. device_type = DeviceType.objects.create(
  106. manufacturer=manufacturer, model='Device Type 1', slug='device-type-1'
  107. )
  108. # Counters should start at zero
  109. self.assertEqual(device_type.interface_template_count, 0)
  110. self.assertEqual(device_type.console_port_template_count, 0)
  111. self.assertEqual(device_type.module_bay_template_count, 0)
  112. self.assertEqual(device_type.device_bay_template_count, 0)
  113. # Adding templates should increment the relevant counters
  114. InterfaceTemplate.objects.create(device_type=device_type, name='Interface 1')
  115. InterfaceTemplate.objects.create(device_type=device_type, name='Interface 2')
  116. ConsolePortTemplate.objects.create(device_type=device_type, name='Console 1')
  117. ModuleBayTemplate.objects.create(device_type=device_type, name='Module Bay 1')
  118. DeviceBayTemplate.objects.create(device_type=device_type, name='Device Bay 1')
  119. device_type.refresh_from_db()
  120. self.assertEqual(device_type.interface_template_count, 2)
  121. self.assertEqual(device_type.console_port_template_count, 1)
  122. self.assertEqual(device_type.module_bay_template_count, 1)
  123. self.assertEqual(device_type.device_bay_template_count, 1)
  124. # Deleting a template should decrement the counter
  125. InterfaceTemplate.objects.get(device_type=device_type, name='Interface 1').delete()
  126. device_type.refresh_from_db()
  127. self.assertEqual(device_type.interface_template_count, 1)
  128. class ModuleTypeTestCase(TestCase):
  129. def test_component_template_counts(self):
  130. """
  131. ModuleType component template counters should track the addition and removal of templates.
  132. """
  133. manufacturer = Manufacturer.objects.create(name='Manufacturer 1', slug='manufacturer-1')
  134. module_type = ModuleType.objects.create(manufacturer=manufacturer, model='Module Type 1')
  135. # Counters should start at zero
  136. self.assertEqual(module_type.interface_template_count, 0)
  137. self.assertEqual(module_type.console_port_template_count, 0)
  138. self.assertEqual(module_type.module_bay_template_count, 0)
  139. # Adding templates should increment the relevant counters
  140. InterfaceTemplate.objects.create(module_type=module_type, name='Interface 1')
  141. InterfaceTemplate.objects.create(module_type=module_type, name='Interface 2')
  142. ConsolePortTemplate.objects.create(module_type=module_type, name='Console 1')
  143. ModuleBayTemplate.objects.create(module_type=module_type, name='Module Bay 1')
  144. module_type.refresh_from_db()
  145. self.assertEqual(module_type.interface_template_count, 2)
  146. self.assertEqual(module_type.console_port_template_count, 1)
  147. self.assertEqual(module_type.module_bay_template_count, 1)
  148. # Deleting a template should decrement the counter
  149. InterfaceTemplate.objects.get(module_type=module_type, name='Interface 1').delete()
  150. module_type.refresh_from_db()
  151. self.assertEqual(module_type.interface_template_count, 1)
  152. def test_attributes(self):
  153. """
  154. ModuleType.attributes should normalize iterable values into strings for presentation.
  155. """
  156. manufacturer = Manufacturer.objects.create(name='Manufacturer 1', slug='manufacturer-1')
  157. profile = ModuleTypeProfile.objects.create(
  158. name='Module Type Profile 1',
  159. schema={
  160. 'properties': {
  161. 'media': {
  162. 'title': 'Media',
  163. 'type': 'array',
  164. 'items': {'type': 'string'},
  165. },
  166. 'enabled': {
  167. 'title': 'Enabled',
  168. 'type': 'boolean',
  169. },
  170. },
  171. },
  172. )
  173. module_type = ModuleType.objects.create(
  174. manufacturer=manufacturer,
  175. model='Module Type 1',
  176. profile=profile,
  177. attribute_data={
  178. 'media': ['sfp', 'qsfp28'],
  179. 'enabled': True,
  180. },
  181. )
  182. self.assertEqual(
  183. module_type.attributes,
  184. {
  185. 'Enabled': True,
  186. 'Media': 'sfp, qsfp28',
  187. },
  188. )
  189. class RackTypeTestCase(TestCase):
  190. @classmethod
  191. def setUpTestData(cls):
  192. manufacturer = Manufacturer.objects.create(name='Manufacturer 1', slug='manufacturer-1')
  193. RackType.objects.create(
  194. manufacturer=manufacturer,
  195. model='RackType 1',
  196. slug='rack-type-1',
  197. width=11,
  198. u_height=22,
  199. starting_unit=3,
  200. desc_units=True,
  201. outer_width=444,
  202. outer_depth=5,
  203. outer_unit=RackDimensionUnitChoices.UNIT_MILLIMETER,
  204. weight=66,
  205. weight_unit=WeightUnitChoices.UNIT_POUND,
  206. max_weight=7777,
  207. mounting_depth=8,
  208. )
  209. def test_rack_creation(self):
  210. rack_type = RackType.objects.first()
  211. sites = (
  212. Site(name='Site 1', slug='site-1'),
  213. )
  214. Site.objects.bulk_create(sites)
  215. locations = (
  216. Location(name='Location 1', slug='location-1', site=sites[0]),
  217. )
  218. for location in locations:
  219. location.save()
  220. rack = Rack.objects.create(
  221. name='Rack 1',
  222. facility_id='A101',
  223. site=sites[0],
  224. location=locations[0],
  225. rack_type=rack_type
  226. )
  227. self.assertEqual(rack.width, rack_type.width)
  228. self.assertEqual(rack.u_height, rack_type.u_height)
  229. self.assertEqual(rack.starting_unit, rack_type.starting_unit)
  230. self.assertEqual(rack.desc_units, rack_type.desc_units)
  231. self.assertEqual(rack.outer_width, rack_type.outer_width)
  232. self.assertEqual(rack.outer_depth, rack_type.outer_depth)
  233. self.assertEqual(rack.outer_unit, rack_type.outer_unit)
  234. self.assertEqual(rack.weight, rack_type.weight)
  235. self.assertEqual(rack.weight_unit, rack_type.weight_unit)
  236. self.assertEqual(rack.max_weight, rack_type.max_weight)
  237. self.assertEqual(rack.mounting_depth, rack_type.mounting_depth)
  238. class RackTestCase(TestCase):
  239. @classmethod
  240. def setUpTestData(cls):
  241. sites = (
  242. Site(name='Site 1', slug='site-1'),
  243. Site(name='Site 2', slug='site-2'),
  244. )
  245. Site.objects.bulk_create(sites)
  246. locations = (
  247. Location(name='Location 1', slug='location-1', site=sites[0]),
  248. Location(name='Location 2', slug='location-2', site=sites[1]),
  249. )
  250. for location in locations:
  251. location.save()
  252. Rack.objects.create(
  253. name='Rack 1',
  254. facility_id='A101',
  255. site=sites[0],
  256. location=locations[0],
  257. u_height=42
  258. )
  259. manufacturer = Manufacturer.objects.create(name='Manufacturer 1', slug='manufacturer-1')
  260. device_types = (
  261. DeviceType(manufacturer=manufacturer, model='Device Type 1', slug='device-type-1', u_height=1),
  262. DeviceType(manufacturer=manufacturer, model='Device Type 2', slug='device-type-2', u_height=0),
  263. DeviceType(manufacturer=manufacturer, model='Device Type 3', slug='device-type-3', u_height=0.5),
  264. )
  265. DeviceType.objects.bulk_create(device_types)
  266. DeviceRole.objects.create(name='Device Role 1', slug='device-role-1')
  267. def test_rack_device_outside_height(self):
  268. site = Site.objects.first()
  269. rack = Rack.objects.first()
  270. device1 = Device(
  271. name='Device 1',
  272. device_type=DeviceType.objects.first(),
  273. role=DeviceRole.objects.first(),
  274. site=site,
  275. rack=rack,
  276. position=43,
  277. face=DeviceFaceChoices.FACE_FRONT,
  278. )
  279. device1.save()
  280. with self.assertRaises(ValidationError):
  281. rack.clean()
  282. def test_location_site(self):
  283. site1 = Site.objects.get(name='Site 1')
  284. location2 = Location.objects.get(name='Location 2')
  285. rack2 = Rack(
  286. name='Rack 2',
  287. site=site1,
  288. location=location2,
  289. u_height=42
  290. )
  291. rack2.save()
  292. with self.assertRaises(ValidationError):
  293. rack2.clean()
  294. def test_mount_single_device(self):
  295. site = Site.objects.first()
  296. rack = Rack.objects.first()
  297. device1 = Device(
  298. name='TestSwitch1',
  299. device_type=DeviceType.objects.first(),
  300. role=DeviceRole.objects.first(),
  301. site=site,
  302. rack=rack,
  303. position=10.0,
  304. face=DeviceFaceChoices.FACE_REAR,
  305. )
  306. device1.save()
  307. # Validate rack height
  308. self.assertEqual(list(rack.units), list(drange(42.5, 0.5, -0.5)))
  309. # Validate inventory (front face)
  310. rack1_inventory_front = {
  311. u['id']: u for u in rack.get_rack_units(face=DeviceFaceChoices.FACE_FRONT)
  312. }
  313. self.assertEqual(rack1_inventory_front[10.0]['device'], device1)
  314. self.assertEqual(rack1_inventory_front[10.5]['device'], device1)
  315. del rack1_inventory_front[10.0]
  316. del rack1_inventory_front[10.5]
  317. for u in rack1_inventory_front.values():
  318. self.assertIsNone(u['device'])
  319. # Validate inventory (rear face)
  320. rack1_inventory_rear = {
  321. u['id']: u for u in rack.get_rack_units(face=DeviceFaceChoices.FACE_REAR)
  322. }
  323. self.assertEqual(rack1_inventory_rear[10.0]['device'], device1)
  324. self.assertEqual(rack1_inventory_rear[10.5]['device'], device1)
  325. del rack1_inventory_rear[10.0]
  326. del rack1_inventory_rear[10.5]
  327. for u in rack1_inventory_rear.values():
  328. self.assertIsNone(u['device'])
  329. def test_mount_zero_ru(self):
  330. """
  331. Check that a 0RU device can be mounted in a rack with no face/position.
  332. """
  333. site = Site.objects.first()
  334. rack = Rack.objects.first()
  335. Device(
  336. name='Device 1',
  337. role=DeviceRole.objects.first(),
  338. device_type=DeviceType.objects.first(),
  339. site=site,
  340. rack=rack
  341. ).save()
  342. def test_mount_half_u_devices(self):
  343. """
  344. Check that two 0.5U devices can be mounted in the same rack unit.
  345. """
  346. rack = Rack.objects.first()
  347. attrs = {
  348. 'device_type': DeviceType.objects.get(u_height=0.5),
  349. 'role': DeviceRole.objects.first(),
  350. 'site': Site.objects.first(),
  351. 'rack': rack,
  352. 'face': DeviceFaceChoices.FACE_FRONT,
  353. }
  354. Device(name='Device 1', position=1, **attrs).save()
  355. Device(name='Device 2', position=1.5, **attrs).save()
  356. self.assertEqual(len(rack.get_available_units()), rack.u_height * 2 - 3)
  357. def test_change_rack_site(self):
  358. """
  359. Check that child Devices get updated when a Rack is moved to a new Site.
  360. """
  361. site_a = Site.objects.create(name='Site A', slug='site-a')
  362. site_b = Site.objects.create(name='Site B', slug='site-b')
  363. # Create Rack1 in Site A
  364. rack1 = Rack.objects.create(site=site_a, name='Rack 1')
  365. # Create Device1 in Rack1
  366. device1 = Device.objects.create(
  367. site=site_a,
  368. rack=rack1,
  369. device_type=DeviceType.objects.first(),
  370. role=DeviceRole.objects.first()
  371. )
  372. # Move Rack1 to Site B
  373. rack1.site = site_b
  374. rack1.save()
  375. # Check that Device1 is now assigned to Site B
  376. self.assertEqual(Device.objects.get(pk=device1.pk).site, site_b)
  377. def test_utilization(self):
  378. site = Site.objects.first()
  379. rack = Rack.objects.first()
  380. Device(
  381. name='Device 1',
  382. role=DeviceRole.objects.first(),
  383. device_type=DeviceType.objects.first(),
  384. site=site,
  385. rack=rack,
  386. position=1
  387. ).save()
  388. rack.refresh_from_db()
  389. self.assertEqual(rack.get_utilization(), 1 / 42 * 100)
  390. # create device excluded from utilization calculations
  391. dt = DeviceType.objects.create(
  392. manufacturer=Manufacturer.objects.first(),
  393. model='Device Type 4',
  394. slug='device-type-4',
  395. u_height=1,
  396. exclude_from_utilization=True
  397. )
  398. Device(
  399. name='Device 2',
  400. role=DeviceRole.objects.first(),
  401. device_type=dt,
  402. site=site,
  403. rack=rack,
  404. position=5
  405. ).save()
  406. rack.refresh_from_db()
  407. self.assertEqual(rack.get_utilization(), 1 / 42 * 100)
  408. class DeviceTestCase(TestCase):
  409. @classmethod
  410. def setUpTestData(cls):
  411. Site.objects.create(name='Test Site 1', slug='test-site-1')
  412. manufacturer = Manufacturer.objects.create(name='Test Manufacturer 1', slug='test-manufacturer-1')
  413. device_type = DeviceType.objects.create(
  414. manufacturer=manufacturer, model='Test Device Type 1', slug='test-device-type-1'
  415. )
  416. roles = (
  417. DeviceRole(name='Test Role 1', slug='test-role-1'),
  418. DeviceRole(name='Test Role 2', slug='test-role-2'),
  419. )
  420. for role in roles:
  421. role.save()
  422. # Create a CustomField with a default value & assign it to all component models
  423. cf1 = CustomField.objects.create(name='cf1', default='foo')
  424. cf1.object_types.set(
  425. ObjectType.objects.filter(app_label='dcim', model__in=[
  426. 'consoleport',
  427. 'consoleserverport',
  428. 'powerport',
  429. 'poweroutlet',
  430. 'interface',
  431. 'rearport',
  432. 'frontport',
  433. 'modulebay',
  434. 'devicebay',
  435. 'inventoryitem',
  436. ])
  437. )
  438. # Create DeviceType components
  439. ConsolePortTemplate(
  440. device_type=device_type,
  441. name='Console Port 1'
  442. ).save()
  443. ConsoleServerPortTemplate(
  444. device_type=device_type,
  445. name='Console Server Port 1'
  446. ).save()
  447. powerport = PowerPortTemplate(
  448. device_type=device_type,
  449. name='Power Port 1',
  450. maximum_draw=1000,
  451. allocated_draw=500
  452. )
  453. powerport.save()
  454. PowerOutletTemplate(
  455. device_type=device_type,
  456. name='Power Outlet 1',
  457. power_port=powerport,
  458. feed_leg=PowerOutletFeedLegChoices.FEED_LEG_A
  459. ).save()
  460. InterfaceTemplate(
  461. device_type=device_type,
  462. name='Interface 1',
  463. type=InterfaceTypeChoices.TYPE_1GE_FIXED,
  464. mgmt_only=True
  465. ).save()
  466. rearport = RearPortTemplate(
  467. device_type=device_type,
  468. name='Rear Port 1',
  469. type=PortTypeChoices.TYPE_8P8C,
  470. positions=8
  471. )
  472. rearport.save()
  473. frontport = FrontPortTemplate(
  474. device_type=device_type,
  475. name='Front Port 1',
  476. type=PortTypeChoices.TYPE_8P8C,
  477. )
  478. frontport.save()
  479. PortTemplateMapping.objects.create(
  480. device_type=device_type,
  481. front_port=frontport,
  482. rear_port=rearport,
  483. rear_port_position=2,
  484. )
  485. ModuleBayTemplate(
  486. device_type=device_type,
  487. name='Module Bay 1'
  488. ).save()
  489. DeviceBayTemplate(
  490. device_type=device_type,
  491. name='Device Bay 1'
  492. ).save()
  493. InventoryItemTemplate(
  494. device_type=device_type,
  495. name='Inventory Item 1'
  496. ).save()
  497. def test_device_creation(self):
  498. """
  499. Ensure that all Device components are copied automatically from the DeviceType.
  500. """
  501. device = Device(
  502. site=Site.objects.first(),
  503. device_type=DeviceType.objects.first(),
  504. role=DeviceRole.objects.first(),
  505. name='Test Device 1'
  506. )
  507. device.save()
  508. consoleport = ConsolePort.objects.get(
  509. device=device,
  510. name='Console Port 1'
  511. )
  512. self.assertEqual(consoleport.cf['cf1'], 'foo')
  513. consoleserverport = ConsoleServerPort.objects.get(
  514. device=device,
  515. name='Console Server Port 1'
  516. )
  517. self.assertEqual(consoleserverport.cf['cf1'], 'foo')
  518. powerport = PowerPort.objects.get(
  519. device=device,
  520. name='Power Port 1',
  521. maximum_draw=1000,
  522. allocated_draw=500
  523. )
  524. self.assertEqual(powerport.cf['cf1'], 'foo')
  525. poweroutlet = PowerOutlet.objects.get(
  526. device=device,
  527. name='Power Outlet 1',
  528. power_port=powerport,
  529. feed_leg=PowerOutletFeedLegChoices.FEED_LEG_A,
  530. status=PowerOutletStatusChoices.STATUS_ENABLED,
  531. )
  532. self.assertEqual(poweroutlet.cf['cf1'], 'foo')
  533. interface = Interface.objects.get(
  534. device=device,
  535. name='Interface 1',
  536. type=InterfaceTypeChoices.TYPE_1GE_FIXED,
  537. mgmt_only=True
  538. )
  539. self.assertEqual(interface.cf['cf1'], 'foo')
  540. rearport = RearPort.objects.get(
  541. device=device,
  542. name='Rear Port 1',
  543. type=PortTypeChoices.TYPE_8P8C,
  544. positions=8
  545. )
  546. self.assertEqual(rearport.cf['cf1'], 'foo')
  547. frontport = FrontPort.objects.get(
  548. device=device,
  549. name='Front Port 1',
  550. type=PortTypeChoices.TYPE_8P8C,
  551. positions=1
  552. )
  553. self.assertEqual(frontport.cf['cf1'], 'foo')
  554. self.assertTrue(PortMapping.objects.filter(front_port=frontport, rear_port=rearport).exists())
  555. modulebay = ModuleBay.objects.get(
  556. device=device,
  557. name='Module Bay 1'
  558. )
  559. self.assertEqual(modulebay.cf['cf1'], 'foo')
  560. devicebay = DeviceBay.objects.get(
  561. device=device,
  562. name='Device Bay 1'
  563. )
  564. self.assertEqual(devicebay.cf['cf1'], 'foo')
  565. inventoryitem = InventoryItem.objects.get(
  566. device=device,
  567. name='Inventory Item 1'
  568. )
  569. self.assertEqual(inventoryitem.cf['cf1'], 'foo')
  570. def test_multiple_unnamed_devices(self):
  571. device1 = Device(
  572. site=Site.objects.first(),
  573. device_type=DeviceType.objects.first(),
  574. role=DeviceRole.objects.first(),
  575. name=None
  576. )
  577. device1.save()
  578. device2 = Device(
  579. site=device1.site,
  580. device_type=device1.device_type,
  581. role=device1.role,
  582. name=None
  583. )
  584. device2.full_clean()
  585. device2.save()
  586. self.assertEqual(Device.objects.filter(name__isnull=True).count(), 2)
  587. def test_device_name_case_sensitivity(self):
  588. device1 = Device(
  589. site=Site.objects.first(),
  590. device_type=DeviceType.objects.first(),
  591. role=DeviceRole.objects.first(),
  592. name='device 1'
  593. )
  594. device1.save()
  595. device2 = Device(
  596. site=device1.site,
  597. device_type=device1.device_type,
  598. role=device1.role,
  599. name='DEVICE 1'
  600. )
  601. # Uniqueness validation for name should ignore case
  602. with self.assertRaises(ValidationError):
  603. device2.full_clean()
  604. def test_device_duplicate_names(self):
  605. device1 = Device(
  606. site=Site.objects.first(),
  607. device_type=DeviceType.objects.first(),
  608. role=DeviceRole.objects.first(),
  609. name='Test Device 1'
  610. )
  611. device1.save()
  612. device2 = Device(
  613. site=device1.site,
  614. device_type=device1.device_type,
  615. role=device1.role,
  616. name=device1.name
  617. )
  618. # Two devices assigned to the same Site and no Tenant should fail validation
  619. with self.assertRaises(ValidationError):
  620. device2.full_clean()
  621. tenant = Tenant.objects.create(name='Test Tenant 1', slug='test-tenant-1')
  622. device1.tenant = tenant
  623. device1.save()
  624. device2.tenant = tenant
  625. # Two devices assigned to the same Site and the same Tenant should fail validation
  626. with self.assertRaises(ValidationError):
  627. device2.full_clean()
  628. device2.tenant = None
  629. # Two devices assigned to the same Site and different Tenants should pass validation
  630. device2.full_clean()
  631. device2.save()
  632. def test_empty_asset_tag_coerced_to_null_on_clean(self):
  633. """
  634. An empty string assigned to a unique nullable CharField (e.g. asset_tag) must be coerced
  635. to None on save so that multiple objects can be saved without violating the unique
  636. constraint. Test that this is done on clean().
  637. """
  638. common_kwargs = {
  639. 'site': Site.objects.first(),
  640. 'device_type': DeviceType.objects.first(),
  641. 'role': DeviceRole.objects.first(),
  642. }
  643. device1 = Device(name='Device 1', asset_tag='', **common_kwargs)
  644. device1.clean()
  645. self.assertIsNone(device1.asset_tag)
  646. def test_empty_asset_tag_coerced_to_null_on_save(self):
  647. """
  648. An empty string assigned to a unique nullable CharField (e.g. asset_tag) must be coerced
  649. to None on save so that multiple objects can be saved without violating the unique
  650. constraint. Test that this is done on save().
  651. """
  652. common_kwargs = {
  653. 'site': Site.objects.first(),
  654. 'device_type': DeviceType.objects.first(),
  655. 'role': DeviceRole.objects.first(),
  656. }
  657. device1 = Device(name='Device 1', asset_tag='', **common_kwargs)
  658. device1.save()
  659. device2 = Device(name='Device 2', asset_tag='', **common_kwargs)
  660. device2.save()
  661. device1.refresh_from_db()
  662. device2.refresh_from_db()
  663. self.assertIsNone(device1.asset_tag)
  664. self.assertIsNone(device2.asset_tag)
  665. def test_device_label(self):
  666. device1 = Device(
  667. site=Site.objects.first(),
  668. device_type=DeviceType.objects.first(),
  669. role=DeviceRole.objects.first(),
  670. name=None,
  671. )
  672. self.assertEqual(device1.label, None)
  673. device1.name = 'Test Device 1'
  674. self.assertEqual(device1.label, 'Test Device 1')
  675. virtual_chassis = VirtualChassis.objects.create(name='VC 1')
  676. device2 = Device(
  677. site=Site.objects.first(),
  678. device_type=DeviceType.objects.first(),
  679. role=DeviceRole.objects.first(),
  680. name=None,
  681. virtual_chassis=virtual_chassis,
  682. vc_position=2,
  683. )
  684. self.assertEqual(device2.label, 'VC 1:2')
  685. device2.name = 'Test Device 2'
  686. self.assertEqual(device2.label, 'Test Device 2')
  687. def test_device_mismatched_site_cluster(self):
  688. cluster_type = ClusterType.objects.create(name='Cluster Type 1', slug='cluster-type-1')
  689. Cluster.objects.create(name='Cluster 1', type=cluster_type)
  690. sites = (
  691. Site(name='Site 1', slug='site-1'),
  692. Site(name='Site 2', slug='site-2'),
  693. )
  694. Site.objects.bulk_create(sites)
  695. clusters = (
  696. Cluster(name='Cluster 1', type=cluster_type, scope=sites[0]),
  697. Cluster(name='Cluster 2', type=cluster_type, scope=sites[1]),
  698. Cluster(name='Cluster 3', type=cluster_type, scope=None),
  699. )
  700. for cluster in clusters:
  701. cluster.save()
  702. device_type = DeviceType.objects.first()
  703. device_role = DeviceRole.objects.first()
  704. # Device with site only should pass
  705. Device(
  706. name='device1',
  707. site=sites[0],
  708. device_type=device_type,
  709. role=device_role
  710. ).full_clean()
  711. # Device with site, cluster non-site should pass
  712. Device(
  713. name='device1',
  714. site=sites[0],
  715. device_type=device_type,
  716. role=device_role,
  717. cluster=clusters[2]
  718. ).full_clean()
  719. # Device with mismatched site & cluster should fail
  720. with self.assertRaises(ValidationError):
  721. Device(
  722. name='device1',
  723. site=sites[0],
  724. device_type=device_type,
  725. role=device_role,
  726. cluster=clusters[1]
  727. ).full_clean()
  728. class DeviceBayTestCase(TestCase):
  729. @classmethod
  730. def setUpTestData(cls):
  731. site = Site.objects.create(name='Test Site 1', slug='test-site-1')
  732. manufacturer = Manufacturer.objects.create(name='Test Manufacturer 1', slug='test-manufacturer-1')
  733. # Parent device type must support device bays (is_parent_device=True)
  734. parent_device_type = DeviceType.objects.create(
  735. manufacturer=manufacturer,
  736. model='Parent Device Type',
  737. slug='parent-device-type',
  738. subdevice_role=SubdeviceRoleChoices.ROLE_PARENT
  739. )
  740. # Child device type for installation
  741. child_device_type = DeviceType.objects.create(
  742. manufacturer=manufacturer,
  743. model='Child Device Type',
  744. slug='child-device-type',
  745. u_height=0,
  746. subdevice_role=SubdeviceRoleChoices.ROLE_CHILD
  747. )
  748. device_role = DeviceRole.objects.create(name='Test Role 1', slug='test-role-1')
  749. cls.parent_device = Device.objects.create(
  750. name='Parent Device',
  751. device_type=parent_device_type,
  752. role=device_role,
  753. site=site
  754. )
  755. cls.child_device = Device.objects.create(
  756. name='Child Device',
  757. device_type=child_device_type,
  758. role=device_role,
  759. site=site
  760. )
  761. cls.child_device_2 = Device.objects.create(
  762. name='Child Device 2',
  763. device_type=child_device_type,
  764. role=device_role,
  765. site=site
  766. )
  767. def test_cannot_install_device_in_disabled_bay(self):
  768. """
  769. Test that a device cannot be installed into a disabled DeviceBay.
  770. """
  771. # Create a disabled device bay with a device being installed
  772. device_bay = DeviceBay(
  773. device=self.parent_device,
  774. name='Disabled Bay',
  775. enabled=False,
  776. installed_device=self.child_device
  777. )
  778. with self.assertRaises(ValidationError) as cm:
  779. device_bay.clean()
  780. self.assertIn('installed_device', cm.exception.message_dict)
  781. self.assertIn('disabled device bay', str(cm.exception.message_dict['installed_device']))
  782. def test_can_disable_bay_with_existing_device(self):
  783. """
  784. Test that disabling a bay that already has a device installed does NOT raise an error
  785. (same installed_device_id).
  786. """
  787. # First, create an enabled device bay with a device installed
  788. device_bay = DeviceBay.objects.create(
  789. device=self.parent_device,
  790. name='Bay To Disable',
  791. enabled=True,
  792. installed_device=self.child_device
  793. )
  794. # Now disable the bay while keeping the same installed device
  795. device_bay.enabled = False
  796. # This should NOT raise a ValidationError
  797. device_bay.clean()
  798. device_bay.save()
  799. device_bay.refresh_from_db()
  800. self.assertFalse(device_bay.enabled)
  801. self.assertEqual(device_bay.installed_device, self.child_device)
  802. def test_cannot_change_installed_device_in_disabled_bay(self):
  803. """
  804. Test that changing the installed device in a disabled bay raises a ValidationError.
  805. """
  806. # Create an enabled device bay with a device installed
  807. device_bay = DeviceBay.objects.create(
  808. device=self.parent_device,
  809. name='Bay With Device',
  810. enabled=True,
  811. installed_device=self.child_device
  812. )
  813. # Disable the bay and try to change the installed device
  814. device_bay.enabled = False
  815. device_bay.installed_device = self.child_device_2
  816. with self.assertRaises(ValidationError) as cm:
  817. device_bay.clean()
  818. self.assertIn('installed_device', cm.exception.message_dict)
  819. class ModuleBayTestCase(TestCase):
  820. @classmethod
  821. def setUpTestData(cls):
  822. site = Site.objects.create(name='Test Site 1', slug='test-site-1')
  823. manufacturer = Manufacturer.objects.create(name='Test Manufacturer 1', slug='test-manufacturer-1')
  824. device_type = DeviceType.objects.create(
  825. manufacturer=manufacturer, model='Test Device Type 1', slug='test-device-type-1'
  826. )
  827. device_role = DeviceRole.objects.create(name='Test Role 1', slug='test-role-1')
  828. # Create a CustomField with a default value & assign it to all component models
  829. location = Location.objects.create(name='Location 1', slug='location-1', site=site)
  830. rack = Rack.objects.create(name='Rack 1', site=site)
  831. device = Device.objects.create(
  832. name='Device 1', device_type=device_type, role=device_role, site=site, location=location, rack=rack
  833. )
  834. module_bays = (
  835. ModuleBay(device=device, name='Module Bay 1', label='A', description='First'),
  836. ModuleBay(device=device, name='Module Bay 2', label='B', description='Second'),
  837. ModuleBay(device=device, name='Module Bay 3', label='C', description='Third'),
  838. )
  839. for module_bay in module_bays:
  840. module_bay.save()
  841. manufacturer = Manufacturer.objects.create(name='Manufacturer 1', slug='manufacturer-1')
  842. module_type = ModuleType.objects.create(manufacturer=manufacturer, model='Module Type 1')
  843. modules = (
  844. Module(device=device, module_bay=module_bays[0], module_type=module_type),
  845. Module(device=device, module_bay=module_bays[1], module_type=module_type),
  846. Module(device=device, module_bay=module_bays[2], module_type=module_type),
  847. )
  848. # M3 -> MB3 -> M2 -> MB2 -> M1 -> MB1
  849. Module.objects.bulk_create(modules)
  850. module_bays[1].module = modules[0]
  851. module_bays[1].clean()
  852. module_bays[1].save()
  853. module_bays[2].module = modules[1]
  854. module_bays[2].clean()
  855. module_bays[2].save()
  856. def test_module_bay_recursion(self):
  857. module_bay_1 = ModuleBay.objects.get(name='Module Bay 1')
  858. module_bay_3 = ModuleBay.objects.get(name='Module Bay 3')
  859. module_1 = Module.objects.get(module_bay=module_bay_1)
  860. module_3 = Module.objects.get(module_bay=module_bay_3)
  861. # Confirm error if ModuleBay recurses
  862. with self.assertRaises(ValidationError):
  863. module_bay_1.module = module_3
  864. module_bay_1.clean()
  865. module_bay_1.save()
  866. # Confirm error if Module recurses
  867. with self.assertRaises(ValidationError):
  868. module_1.module_bay = module_bay_3
  869. module_1.clean()
  870. module_1.save()
  871. @tag('regression') # #22146
  872. def test_module_bay_ordering_after_recreate(self):
  873. """
  874. Module bays must remain in name order after a delete-and-recreate cycle,
  875. even though MPTT no longer renumbers tree_ids on root insertion.
  876. """
  877. device_type = DeviceType.objects.first()
  878. device_role = DeviceRole.objects.first()
  879. site = Site.objects.first()
  880. device = Device.objects.create(
  881. name='Ordering Test Device',
  882. device_type=device_type,
  883. role=device_role,
  884. site=site,
  885. )
  886. for name in ('Bay 1', 'Bay 2', 'Bay 3', 'Bay 4'):
  887. ModuleBay.objects.create(device=device, name=name)
  888. ModuleBay.objects.get(device=device, name='Bay 3').delete()
  889. ModuleBay.objects.create(device=device, name='Bay 3')
  890. names = list(ModuleBay.objects.filter(device=device).values_list('name', flat=True))
  891. self.assertEqual(names, ['Bay 1', 'Bay 2', 'Bay 3', 'Bay 4'])
  892. @tag('regression') # #22146
  893. def test_module_bay_natural_ordering(self):
  894. """
  895. Module bays must be returned in natural (numeric-aware) order, e.g.
  896. "Bay 2" before "Bay 10".
  897. """
  898. device_type = DeviceType.objects.first()
  899. device_role = DeviceRole.objects.first()
  900. site = Site.objects.first()
  901. device = Device.objects.create(
  902. name='Natural Sort Device',
  903. device_type=device_type,
  904. role=device_role,
  905. site=site,
  906. )
  907. # Insert in non-natural order to confirm sort is not insertion-driven.
  908. for name in ('Bay 10', 'Bay 1', 'Bay 2', 'Bay 11'):
  909. ModuleBay.objects.create(device=device, name=name)
  910. names = list(ModuleBay.objects.filter(device=device).values_list('name', flat=True))
  911. self.assertEqual(names, ['Bay 1', 'Bay 2', 'Bay 10', 'Bay 11'])
  912. @tag('regression') # #22146
  913. def test_child_module_bay_ordering(self):
  914. """
  915. Child module bays inside a module must be returned in name order even
  916. when inserted out of order.
  917. """
  918. device_type = DeviceType.objects.first()
  919. device_role = DeviceRole.objects.first()
  920. site = Site.objects.first()
  921. device = Device.objects.create(
  922. name='Child Ordering Device',
  923. device_type=device_type,
  924. role=device_role,
  925. site=site,
  926. )
  927. root_bay = ModuleBay.objects.create(device=device, name='Bay 1')
  928. manufacturer = Manufacturer.objects.first()
  929. module_type = ModuleType.objects.create(
  930. manufacturer=manufacturer, model='Child Ordering Type'
  931. )
  932. module = Module.objects.create(
  933. device=device, module_bay=root_bay, module_type=module_type
  934. )
  935. # Insert children out of name order.
  936. for name in ('Bay 1.1', 'Bay 1.3', 'Bay 1.2'):
  937. ModuleBay.objects.create(device=device, module=module, name=name)
  938. names = list(ModuleBay.objects.filter(device=device).values_list('name', flat=True))
  939. self.assertEqual(names, ['Bay 1', 'Bay 1.1', 'Bay 1.2', 'Bay 1.3'])
  940. @tag('regression') # #22146
  941. def test_root_module_bay_rename_preserves_paths(self):
  942. """
  943. Renaming a root module bay must not rewrite any tree's path. Renaming
  944. touches only sort_path (the display-ordering column), so every bay's
  945. path — including the renamed bay's own — must be unchanged afterward.
  946. """
  947. device_type = DeviceType.objects.first()
  948. device_role = DeviceRole.objects.first()
  949. site = Site.objects.first()
  950. device = Device.objects.create(
  951. name='Rename Path Device',
  952. device_type=device_type,
  953. role=device_role,
  954. site=site,
  955. )
  956. for name in ('Bay 1', 'Bay 2', 'Bay 3', 'Bay 4'):
  957. ModuleBay.objects.create(device=device, name=name)
  958. paths_before = {
  959. bay.pk: str(bay.path)
  960. for bay in ModuleBay.objects.filter(device=device)
  961. }
  962. bay = ModuleBay.objects.get(device=device, name='Bay 2')
  963. bay.name = 'Bay 99'
  964. bay.save()
  965. paths_after = {
  966. bay.pk: str(bay.path)
  967. for bay in ModuleBay.objects.filter(device=device)
  968. }
  969. self.assertEqual(paths_after, paths_before)
  970. @tag('regression') # #22146
  971. def test_root_module_bay_rename_updates_display_order(self):
  972. """
  973. Even though renaming a root module bay does not rewrite its path,
  974. the manager's _root_name annotation must reflect the new name so the
  975. display ordering is correct.
  976. """
  977. device_type = DeviceType.objects.first()
  978. device_role = DeviceRole.objects.first()
  979. site = Site.objects.first()
  980. device = Device.objects.create(
  981. name='Rename Order Device',
  982. device_type=device_type,
  983. role=device_role,
  984. site=site,
  985. )
  986. for name in ('Bay 1', 'Bay 2', 'Bay 3'):
  987. ModuleBay.objects.create(device=device, name=name)
  988. bay = ModuleBay.objects.get(device=device, name='Bay 1')
  989. bay.name = 'Bay 4'
  990. bay.save()
  991. names = list(ModuleBay.objects.filter(device=device).values_list('name', flat=True))
  992. self.assertEqual(names, ['Bay 2', 'Bay 3', 'Bay 4'])
  993. @tag('regression') # #22146
  994. def test_child_module_bay_rename_preserves_intra_tree_ordering(self):
  995. """
  996. Renaming a *child* module bay must still trigger MPTT's intra-tree
  997. reorder, so siblings appear in name order after the rename. The
  998. rename-bypass only covers root bays.
  999. """
  1000. device_type = DeviceType.objects.first()
  1001. device_role = DeviceRole.objects.first()
  1002. site = Site.objects.first()
  1003. device = Device.objects.create(
  1004. name='Child Rename Device',
  1005. device_type=device_type,
  1006. role=device_role,
  1007. site=site,
  1008. )
  1009. root_bay = ModuleBay.objects.create(device=device, name='Bay 1')
  1010. manufacturer = Manufacturer.objects.first()
  1011. module_type = ModuleType.objects.create(
  1012. manufacturer=manufacturer, model='Child Rename Type'
  1013. )
  1014. module = Module.objects.create(
  1015. device=device, module_bay=root_bay, module_type=module_type
  1016. )
  1017. for name in ('Bay 1.1', 'Bay 1.2', 'Bay 1.3'):
  1018. ModuleBay.objects.create(device=device, module=module, name=name)
  1019. child = ModuleBay.objects.get(device=device, name='Bay 1.1')
  1020. child.name = 'Bay 1.4'
  1021. child.save()
  1022. names = list(ModuleBay.objects.filter(device=device).values_list('name', flat=True))
  1023. self.assertEqual(names, ['Bay 1', 'Bay 1.2', 'Bay 1.3', 'Bay 1.4'])
  1024. @tag('regression') # #22146
  1025. def test_root_to_child_transition_still_relocates(self):
  1026. """
  1027. Promoting an existing root module bay to a child (by assigning a
  1028. module) must still flow through MPTT's normal move logic. The
  1029. rename-bypass must not suppress legitimate parent changes.
  1030. """
  1031. device_type = DeviceType.objects.first()
  1032. device_role = DeviceRole.objects.first()
  1033. site = Site.objects.first()
  1034. device = Device.objects.create(
  1035. name='Root To Child Device',
  1036. device_type=device_type,
  1037. role=device_role,
  1038. site=site,
  1039. )
  1040. host_bay = ModuleBay.objects.create(device=device, name='Host Bay')
  1041. movable_bay = ModuleBay.objects.create(device=device, name='Movable Bay')
  1042. manufacturer = Manufacturer.objects.first()
  1043. module_type = ModuleType.objects.create(
  1044. manufacturer=manufacturer, model='Root To Child Type'
  1045. )
  1046. host_module = Module.objects.create(
  1047. device=device, module_bay=host_bay, module_type=module_type
  1048. )
  1049. movable_bay.module = host_module
  1050. movable_bay.save()
  1051. movable_bay.refresh_from_db()
  1052. host_bay.refresh_from_db()
  1053. self.assertEqual(movable_bay.parent_id, host_bay.pk)
  1054. # The trigger cascade must have re-rooted the moved bay into host_bay's
  1055. # tree: its path is now a strict descendant of host_bay's path.
  1056. self.assertTrue(str(movable_bay.path).startswith(f'{host_bay.path}.'))
  1057. @tag('regression') # #22251
  1058. def test_moving_module_reparents_child_module_bays(self):
  1059. """
  1060. When a module is moved to a different module bay, each child ModuleBay
  1061. (a bay that belongs to the module) must have its parent updated to the
  1062. new host bay. Without the fix the children stay parented to the old bay
  1063. even though Module.module_bay_id has changed.
  1064. """
  1065. device_type = DeviceType.objects.first()
  1066. device_role = DeviceRole.objects.first()
  1067. site = Site.objects.first()
  1068. device = Device.objects.create(
  1069. name='Move Module Device',
  1070. device_type=device_type,
  1071. role=device_role,
  1072. site=site,
  1073. )
  1074. bay_a = ModuleBay.objects.create(device=device, name='Bay A')
  1075. bay_b = ModuleBay.objects.create(device=device, name='Bay B')
  1076. manufacturer = Manufacturer.objects.first()
  1077. module_type = ModuleType.objects.create(
  1078. manufacturer=manufacturer, model='Move Module Type'
  1079. )
  1080. module = Module.objects.create(
  1081. device=device, module_bay=bay_a, module_type=module_type
  1082. )
  1083. child_1 = ModuleBay.objects.create(device=device, module=module, name='Child Bay 1')
  1084. child_2 = ModuleBay.objects.create(device=device, module=module, name='Child Bay 2')
  1085. self.assertEqual(child_1.parent_id, bay_a.pk)
  1086. self.assertEqual(child_2.parent_id, bay_a.pk)
  1087. # Move the module to bay_b.
  1088. module.module_bay = bay_b
  1089. module.save()
  1090. child_1.refresh_from_db()
  1091. child_2.refresh_from_db()
  1092. self.assertEqual(child_1.parent_id, bay_b.pk)
  1093. self.assertEqual(child_2.parent_id, bay_b.pk)
  1094. # Children must be re-rooted under bay_b in the ltree hierarchy.
  1095. bay_b.refresh_from_db()
  1096. self.assertTrue(str(child_1.path).startswith(f'{bay_b.path}.'))
  1097. self.assertTrue(str(child_2.path).startswith(f'{bay_b.path}.'))
  1098. @tag('regression') # #22251
  1099. def test_moving_module_reparents_grandchild_module_bays(self):
  1100. """
  1101. When a module is moved, grandchild ModuleBays (bays inside a module
  1102. that is itself installed inside a child bay of the moved module) must
  1103. also land in the new ltree subtree. The trigger cascade moves subtrees
  1104. atomically, so calling save() only on direct children is sufficient —
  1105. this test documents and preserves that invariant for future tree-backend
  1106. changes.
  1107. """
  1108. device_type = DeviceType.objects.first()
  1109. device_role = DeviceRole.objects.first()
  1110. site = Site.objects.first()
  1111. device = Device.objects.create(
  1112. name='Grandchild Move Device',
  1113. device_type=device_type,
  1114. role=device_role,
  1115. site=site,
  1116. )
  1117. bay_a = ModuleBay.objects.create(device=device, name='Bay A')
  1118. bay_b = ModuleBay.objects.create(device=device, name='Bay B')
  1119. manufacturer = Manufacturer.objects.first()
  1120. module_type = ModuleType.objects.create(
  1121. manufacturer=manufacturer, model='Grandchild Move Type'
  1122. )
  1123. # Depth-1: module installed in bay_a, with one child bay.
  1124. module_1 = Module.objects.create(device=device, module_bay=bay_a, module_type=module_type)
  1125. child_bay = ModuleBay.objects.create(device=device, module=module_1, name='Child Bay')
  1126. # Depth-2: module installed in child_bay, with one grandchild bay.
  1127. module_2 = Module.objects.create(device=device, module_bay=child_bay, module_type=module_type)
  1128. grandchild_bay = ModuleBay.objects.create(device=device, module=module_2, name='Grandchild Bay')
  1129. self.assertEqual(child_bay.parent_id, bay_a.pk)
  1130. self.assertEqual(grandchild_bay.parent_id, child_bay.pk)
  1131. bay_a.refresh_from_db()
  1132. self.assertTrue(str(grandchild_bay.path).startswith(f'{bay_a.path}.'))
  1133. # Move the top-level module to bay_b.
  1134. module_1.module_bay = bay_b
  1135. module_1.save()
  1136. child_bay.refresh_from_db()
  1137. grandchild_bay.refresh_from_db()
  1138. bay_b.refresh_from_db()
  1139. self.assertEqual(child_bay.parent_id, bay_b.pk)
  1140. self.assertTrue(str(child_bay.path).startswith(f'{bay_b.path}.'))
  1141. # Grandchild's direct parent (child_bay) is unchanged; only tree placement moves.
  1142. self.assertEqual(grandchild_bay.parent_id, child_bay.pk)
  1143. self.assertTrue(str(grandchild_bay.path).startswith(f'{bay_b.path}.'))
  1144. def test_single_module_token(self):
  1145. device_type = DeviceType.objects.first()
  1146. device_role = DeviceRole.objects.first()
  1147. site = Site.objects.first()
  1148. location = Location.objects.first()
  1149. rack = Rack.objects.first()
  1150. # Create DeviceType components
  1151. ConsolePortTemplate.objects.create(
  1152. device_type=device_type,
  1153. name='{module}',
  1154. label='{module}',
  1155. )
  1156. ModuleBayTemplate.objects.create(
  1157. device_type=device_type,
  1158. name='Module Bay 1'
  1159. )
  1160. device = Device.objects.create(
  1161. name='Device 2',
  1162. device_type=device_type,
  1163. role=device_role,
  1164. site=site,
  1165. location=location,
  1166. rack=rack
  1167. )
  1168. device.consoleports.first()
  1169. @tag('regression') # #19918
  1170. def test_nested_module_bay_label_resolution(self):
  1171. """Test that nested module bay labels properly resolve {module} placeholders"""
  1172. manufacturer = Manufacturer.objects.first()
  1173. site = Site.objects.first()
  1174. device_role = DeviceRole.objects.first()
  1175. # Create device type with module bay template (position='A')
  1176. device_type = DeviceType.objects.create(
  1177. manufacturer=manufacturer,
  1178. model='Device with Bays',
  1179. slug='device-with-bays'
  1180. )
  1181. ModuleBayTemplate.objects.create(
  1182. device_type=device_type,
  1183. name='Bay A',
  1184. position='A'
  1185. )
  1186. # Create module type with nested bay template using {module} placeholder
  1187. module_type = ModuleType.objects.create(
  1188. manufacturer=manufacturer,
  1189. model='Module with Nested Bays'
  1190. )
  1191. ModuleBayTemplate.objects.create(
  1192. module_type=module_type,
  1193. name='SFP {module}-21',
  1194. label='{module}-21',
  1195. position='21'
  1196. )
  1197. # Create device and install module
  1198. device = Device.objects.create(
  1199. name='Test Device',
  1200. device_type=device_type,
  1201. role=device_role,
  1202. site=site
  1203. )
  1204. module_bay = device.modulebays.get(name='Bay A')
  1205. module = Module.objects.create(
  1206. device=device,
  1207. module_bay=module_bay,
  1208. module_type=module_type
  1209. )
  1210. # Verify nested bay label resolves {module} to parent position
  1211. nested_bay = module.modulebays.get(name='SFP A-21')
  1212. self.assertEqual(nested_bay.label, 'A-21')
  1213. @tag('regression') # #21418
  1214. def test_module_install_nests_module_bay_parent(self):
  1215. """
  1216. A module bay instantiated when a module is installed must be nested under the
  1217. installing module's bay. bulk_create() bypasses ModuleBay.save(), so the parent
  1218. is assigned in ModuleBayTemplate.instantiate(); without it the bay would be left
  1219. a root with a top-level ltree path.
  1220. """
  1221. manufacturer = Manufacturer.objects.first()
  1222. site = Site.objects.first()
  1223. device_role = DeviceRole.objects.first()
  1224. device_type = DeviceType.objects.create(
  1225. manufacturer=manufacturer, model='Chassis with Bay', slug='chassis-with-bay'
  1226. )
  1227. ModuleBayTemplate.objects.create(device_type=device_type, name='Bay A')
  1228. module_type = ModuleType.objects.create(manufacturer=manufacturer, model='Module with Sub-bay')
  1229. ModuleBayTemplate.objects.create(module_type=module_type, name='Sub-bay 1')
  1230. device = Device.objects.create(
  1231. name='Nested Bay Parent Device', device_type=device_type, role=device_role, site=site
  1232. )
  1233. parent_bay = device.modulebays.get(name='Bay A')
  1234. module = Module.objects.create(device=device, module_bay=parent_bay, module_type=module_type)
  1235. nested_bay = module.modulebays.get(name='Sub-bay 1')
  1236. self.assertEqual(nested_bay.parent, parent_bay)
  1237. # The ltree path/level must reflect the nesting, not a root placement.
  1238. self.assertEqual(nested_bay.level, parent_bay.level + 1)
  1239. self.assertTrue(str(nested_bay.path).startswith(f'{parent_bay.path}.'))
  1240. @tag('regression') # #20467
  1241. def test_nested_module_bay_position_resolution(self):
  1242. """Test that {module} in a module bay template's position field is resolved when the module is installed."""
  1243. manufacturer = Manufacturer.objects.first()
  1244. site = Site.objects.first()
  1245. device_role = DeviceRole.objects.first()
  1246. device_type = DeviceType.objects.create(
  1247. manufacturer=manufacturer,
  1248. model='Device with Position Test',
  1249. slug='device-with-position-test'
  1250. )
  1251. ModuleBayTemplate.objects.create(
  1252. device_type=device_type,
  1253. name='Slot 1',
  1254. position='1'
  1255. )
  1256. module_type = ModuleType.objects.create(
  1257. manufacturer=manufacturer,
  1258. model='Module with Position Placeholder'
  1259. )
  1260. ModuleBayTemplate.objects.create(
  1261. module_type=module_type,
  1262. name='Sub-bay {module}-1',
  1263. position='{module}-1'
  1264. )
  1265. device = Device.objects.create(
  1266. name='Position Test Device',
  1267. device_type=device_type,
  1268. role=device_role,
  1269. site=site
  1270. )
  1271. module_bay = device.modulebays.get(name='Slot 1')
  1272. module = Module.objects.create(
  1273. device=device,
  1274. module_bay=module_bay,
  1275. module_type=module_type
  1276. )
  1277. nested_bay = module.modulebays.get(name='Sub-bay 1-1')
  1278. self.assertEqual(nested_bay.position, '1-1')
  1279. #
  1280. # Position inheritance tests (#19796)
  1281. #
  1282. def test_position_inheritance_depth_2(self):
  1283. """
  1284. A module bay with position '{module}/2' under a parent bay with position '1'
  1285. should resolve to position '1/2'. A single {module} in the interface template
  1286. should then resolve to '1/2'.
  1287. """
  1288. manufacturer = Manufacturer.objects.first()
  1289. site = Site.objects.first()
  1290. device_role = DeviceRole.objects.first()
  1291. device_type = DeviceType.objects.create(
  1292. manufacturer=manufacturer,
  1293. model='Chassis for Inheritance',
  1294. slug='chassis-for-inheritance'
  1295. )
  1296. ModuleBayTemplate.objects.create(
  1297. device_type=device_type,
  1298. name='Line card slot 1',
  1299. position='1'
  1300. )
  1301. line_card_type = ModuleType.objects.create(
  1302. manufacturer=manufacturer,
  1303. model='Line Card with Inherited Bays'
  1304. )
  1305. ModuleBayTemplate.objects.create(
  1306. module_type=line_card_type,
  1307. name='SFP bay {module}/1',
  1308. position='{module}/1'
  1309. )
  1310. ModuleBayTemplate.objects.create(
  1311. module_type=line_card_type,
  1312. name='SFP bay {module}/2',
  1313. position='{module}/2'
  1314. )
  1315. sfp_type = ModuleType.objects.create(
  1316. manufacturer=manufacturer,
  1317. model='SFP with Inherited Path'
  1318. )
  1319. InterfaceTemplate.objects.create(
  1320. module_type=sfp_type,
  1321. name='SFP {module}',
  1322. type=InterfaceTypeChoices.TYPE_10GE_SFP_PLUS
  1323. )
  1324. device = Device.objects.create(
  1325. name='Inheritance Chassis',
  1326. device_type=device_type,
  1327. role=device_role,
  1328. site=site
  1329. )
  1330. lc_bay = device.modulebays.get(name='Line card slot 1')
  1331. line_card = Module.objects.create(
  1332. device=device,
  1333. module_bay=lc_bay,
  1334. module_type=line_card_type
  1335. )
  1336. sfp_bay = line_card.modulebays.get(name='SFP bay 1/2')
  1337. sfp_module = Module.objects.create(
  1338. device=device,
  1339. module_bay=sfp_bay,
  1340. module_type=sfp_type
  1341. )
  1342. interface = sfp_module.interfaces.first()
  1343. self.assertEqual(interface.name, 'SFP 1/2')
  1344. def test_position_inheritance_depth_3(self):
  1345. """
  1346. Position inheritance at depth 3: positions should chain through the tree.
  1347. """
  1348. manufacturer = Manufacturer.objects.first()
  1349. site = Site.objects.first()
  1350. device_role = DeviceRole.objects.first()
  1351. device_type = DeviceType.objects.create(
  1352. manufacturer=manufacturer,
  1353. model='Deep Chassis',
  1354. slug='deep-chassis'
  1355. )
  1356. ModuleBayTemplate.objects.create(
  1357. device_type=device_type,
  1358. name='Slot A',
  1359. position='A'
  1360. )
  1361. mid_type = ModuleType.objects.create(
  1362. manufacturer=manufacturer,
  1363. model='Mid Module'
  1364. )
  1365. ModuleBayTemplate.objects.create(
  1366. module_type=mid_type,
  1367. name='Sub {module}-1',
  1368. position='{module}-1'
  1369. )
  1370. leaf_type = ModuleType.objects.create(
  1371. manufacturer=manufacturer,
  1372. model='Leaf Module'
  1373. )
  1374. InterfaceTemplate.objects.create(
  1375. module_type=leaf_type,
  1376. name='Port {module}',
  1377. type=InterfaceTypeChoices.TYPE_1GE_FIXED
  1378. )
  1379. device = Device.objects.create(
  1380. name='Deep Device',
  1381. device_type=device_type,
  1382. role=device_role,
  1383. site=site
  1384. )
  1385. slot_a = device.modulebays.get(name='Slot A')
  1386. mid_module = Module.objects.create(
  1387. device=device,
  1388. module_bay=slot_a,
  1389. module_type=mid_type
  1390. )
  1391. sub_bay = mid_module.modulebays.get(name='Sub A-1')
  1392. self.assertEqual(sub_bay.position, 'A-1')
  1393. leaf_module = Module.objects.create(
  1394. device=device,
  1395. module_bay=sub_bay,
  1396. module_type=leaf_type
  1397. )
  1398. interface = leaf_module.interfaces.first()
  1399. self.assertEqual(interface.name, 'Port A-1')
  1400. def test_position_inheritance_custom_separator(self):
  1401. """
  1402. Users control the separator through the position field template.
  1403. Using '.' instead of '/' should work correctly.
  1404. """
  1405. manufacturer = Manufacturer.objects.first()
  1406. site = Site.objects.first()
  1407. device_role = DeviceRole.objects.first()
  1408. device_type = DeviceType.objects.create(
  1409. manufacturer=manufacturer,
  1410. model='Dot Separator Chassis',
  1411. slug='dot-separator-chassis'
  1412. )
  1413. ModuleBayTemplate.objects.create(
  1414. device_type=device_type,
  1415. name='Bay 1',
  1416. position='1'
  1417. )
  1418. card_type = ModuleType.objects.create(
  1419. manufacturer=manufacturer,
  1420. model='Card with Dot Separator'
  1421. )
  1422. ModuleBayTemplate.objects.create(
  1423. module_type=card_type,
  1424. name='Port {module}.1',
  1425. position='{module}.1'
  1426. )
  1427. sfp_type = ModuleType.objects.create(
  1428. manufacturer=manufacturer,
  1429. model='SFP Dot'
  1430. )
  1431. InterfaceTemplate.objects.create(
  1432. module_type=sfp_type,
  1433. name='eth{module}',
  1434. type=InterfaceTypeChoices.TYPE_10GE_SFP_PLUS
  1435. )
  1436. device = Device.objects.create(
  1437. name='Dot Device',
  1438. device_type=device_type,
  1439. role=device_role,
  1440. site=site
  1441. )
  1442. bay = device.modulebays.get(name='Bay 1')
  1443. card = Module.objects.create(
  1444. device=device,
  1445. module_bay=bay,
  1446. module_type=card_type
  1447. )
  1448. port_bay = card.modulebays.get(name='Port 1.1')
  1449. sfp = Module.objects.create(
  1450. device=device,
  1451. module_bay=port_bay,
  1452. module_type=sfp_type
  1453. )
  1454. interface = sfp.interfaces.first()
  1455. self.assertEqual(interface.name, 'eth1.1')
  1456. def test_multi_token_backwards_compat(self):
  1457. """
  1458. Multi-token {module}/{module} at matching depth should still resolve
  1459. level-by-level (backwards compatibility).
  1460. """
  1461. manufacturer = Manufacturer.objects.first()
  1462. site = Site.objects.first()
  1463. device_role = DeviceRole.objects.first()
  1464. device_type = DeviceType.objects.create(
  1465. manufacturer=manufacturer,
  1466. model='Multi Token Chassis',
  1467. slug='multi-token-chassis'
  1468. )
  1469. ModuleBayTemplate.objects.create(
  1470. device_type=device_type,
  1471. name='Slot 1',
  1472. position='1'
  1473. )
  1474. card_type = ModuleType.objects.create(
  1475. manufacturer=manufacturer,
  1476. model='Card for Multi Token'
  1477. )
  1478. ModuleBayTemplate.objects.create(
  1479. module_type=card_type,
  1480. name='Port 1',
  1481. position='2'
  1482. )
  1483. iface_type = ModuleType.objects.create(
  1484. manufacturer=manufacturer,
  1485. model='Interface Module Multi Token'
  1486. )
  1487. InterfaceTemplate.objects.create(
  1488. module_type=iface_type,
  1489. name='Gi{module}/{module}',
  1490. type=InterfaceTypeChoices.TYPE_1GE_FIXED
  1491. )
  1492. device = Device.objects.create(
  1493. name='Multi Token Device',
  1494. device_type=device_type,
  1495. role=device_role,
  1496. site=site
  1497. )
  1498. slot = device.modulebays.get(name='Slot 1')
  1499. card = Module.objects.create(
  1500. device=device,
  1501. module_bay=slot,
  1502. module_type=card_type
  1503. )
  1504. port = card.modulebays.get(name='Port 1')
  1505. iface_module = Module.objects.create(
  1506. device=device,
  1507. module_bay=port,
  1508. module_type=iface_type
  1509. )
  1510. interface = iface_module.interfaces.first()
  1511. self.assertEqual(interface.name, 'Gi1/2')
  1512. @tag('regression') # #20912
  1513. def test_module_bay_parent_cleared_when_module_removed(self):
  1514. """Test that the parent field is properly cleared when a module bay's module assignment is removed"""
  1515. device = Device.objects.first()
  1516. manufacturer = Manufacturer.objects.first()
  1517. module_type = ModuleType.objects.create(manufacturer=manufacturer, model='Test Module Type')
  1518. bay1 = ModuleBay.objects.create(device=device, name='Test Bay 1')
  1519. bay2 = ModuleBay.objects.create(device=device, name='Test Bay 2')
  1520. # Install a module in bay1
  1521. module1 = Module.objects.create(device=device, module_bay=bay1, module_type=module_type)
  1522. # Assign bay2 to module1 and verify parent is now set to bay1 (module1's bay)
  1523. bay2.module = module1
  1524. bay2.save()
  1525. bay2.refresh_from_db()
  1526. self.assertEqual(bay2.parent, bay1)
  1527. self.assertEqual(bay2.module, module1)
  1528. # Clear the module assignment (return bay2 to device level) Verify parent is cleared
  1529. bay2.module = None
  1530. bay2.save()
  1531. bay2.refresh_from_db()
  1532. self.assertIsNone(bay2.parent)
  1533. self.assertIsNone(bay2.module)
  1534. def test_module_installation_creates_port_mappings(self):
  1535. """
  1536. Test that installing a module with front/rear port templates correctly
  1537. creates PortMapping instances for the device.
  1538. """
  1539. device = Device.objects.first()
  1540. manufacturer = Manufacturer.objects.first()
  1541. module_bay = ModuleBay.objects.create(device=device, name='Test Bay PortMapping 1')
  1542. # Create a module type with a rear port template
  1543. module_type_with_mappings = ModuleType.objects.create(
  1544. manufacturer=manufacturer,
  1545. model='Module Type With Mappings',
  1546. )
  1547. # Create a rear port template with 12 positions (splice)
  1548. rear_port_template = RearPortTemplate.objects.create(
  1549. module_type=module_type_with_mappings,
  1550. name='Rear Port 1',
  1551. type=PortTypeChoices.TYPE_SPLICE,
  1552. positions=12,
  1553. )
  1554. # Create 12 front port templates mapped to the rear port
  1555. front_port_templates = []
  1556. for i in range(1, 13):
  1557. front_port_template = FrontPortTemplate.objects.create(
  1558. module_type=module_type_with_mappings,
  1559. name=f'port {i}',
  1560. type=PortTypeChoices.TYPE_LC,
  1561. positions=1,
  1562. )
  1563. front_port_templates.append(front_port_template)
  1564. # Create port template mapping
  1565. PortTemplateMapping.objects.create(
  1566. device_type=None,
  1567. module_type=module_type_with_mappings,
  1568. front_port=front_port_template,
  1569. front_port_position=1,
  1570. rear_port=rear_port_template,
  1571. rear_port_position=i,
  1572. )
  1573. # Install the module
  1574. module = Module.objects.create(
  1575. device=device,
  1576. module_bay=module_bay,
  1577. module_type=module_type_with_mappings,
  1578. status=ModuleStatusChoices.STATUS_ACTIVE,
  1579. )
  1580. # Verify that front ports were created
  1581. front_ports = FrontPort.objects.filter(device=device, module=module)
  1582. self.assertEqual(front_ports.count(), 12)
  1583. # Verify that the rear port was created
  1584. rear_ports = RearPort.objects.filter(device=device, module=module)
  1585. self.assertEqual(rear_ports.count(), 1)
  1586. rear_port = rear_ports.first()
  1587. self.assertEqual(rear_port.positions, 12)
  1588. # Verify that port mappings were created
  1589. port_mappings = PortMapping.objects.filter(front_port__module=module)
  1590. self.assertEqual(port_mappings.count(), 12)
  1591. # Verify each mapping is correct
  1592. for i, front_port_template in enumerate(front_port_templates, start=1):
  1593. front_port = FrontPort.objects.get(
  1594. device=device,
  1595. name=front_port_template.name,
  1596. module=module,
  1597. )
  1598. # Check that a mapping exists for this front port
  1599. mapping = PortMapping.objects.get(
  1600. device=device,
  1601. front_port=front_port,
  1602. front_port_position=1,
  1603. )
  1604. self.assertEqual(mapping.rear_port, rear_port)
  1605. self.assertEqual(mapping.front_port_position, 1)
  1606. self.assertEqual(mapping.rear_port_position, i)
  1607. def test_module_installation_without_mappings(self):
  1608. """
  1609. Test that installing a module without port template mappings
  1610. doesn't create any PortMapping instances.
  1611. """
  1612. device = Device.objects.first()
  1613. manufacturer = Manufacturer.objects.first()
  1614. module_bay = ModuleBay.objects.create(device=device, name='Test Bay PortMapping 2')
  1615. # Create a module type without any port template mappings
  1616. module_type_no_mappings = ModuleType.objects.create(
  1617. manufacturer=manufacturer,
  1618. model='Module Type Without Mappings',
  1619. )
  1620. # Create a rear port template
  1621. RearPortTemplate.objects.create(
  1622. module_type=module_type_no_mappings,
  1623. name='Rear Port 1',
  1624. type=PortTypeChoices.TYPE_SPLICE,
  1625. positions=12,
  1626. )
  1627. # Create front port templates but DO NOT create PortTemplateMapping rows
  1628. for i in range(1, 13):
  1629. FrontPortTemplate.objects.create(
  1630. module_type=module_type_no_mappings,
  1631. name=f'port {i}',
  1632. type=PortTypeChoices.TYPE_LC,
  1633. positions=1,
  1634. )
  1635. # Install the module
  1636. module = Module.objects.create(
  1637. device=device,
  1638. module_bay=module_bay,
  1639. module_type=module_type_no_mappings,
  1640. status=ModuleStatusChoices.STATUS_ACTIVE,
  1641. )
  1642. # Verify no port mappings were created for this module
  1643. port_mappings = PortMapping.objects.filter(
  1644. device=device,
  1645. front_port__module=module,
  1646. front_port_position=1,
  1647. )
  1648. self.assertEqual(port_mappings.count(), 0)
  1649. self.assertEqual(FrontPort.objects.filter(module=module).count(), 12)
  1650. self.assertEqual(RearPort.objects.filter(module=module).count(), 1)
  1651. self.assertEqual(PortMapping.objects.filter(front_port__module=module).count(), 0)
  1652. def test_cannot_install_module_in_disabled_bay(self):
  1653. """
  1654. Test that a Module cannot be installed into a disabled ModuleBay.
  1655. """
  1656. device = Device.objects.first()
  1657. manufacturer = Manufacturer.objects.first()
  1658. module_type = ModuleType.objects.create(manufacturer=manufacturer, model='Test Module Type Disabled')
  1659. # Create a disabled module bay
  1660. disabled_bay = ModuleBay.objects.create(device=device, name='Disabled Bay', enabled=False)
  1661. # Attempt to install a module into the disabled bay
  1662. module = Module(device=device, module_bay=disabled_bay, module_type=module_type)
  1663. with self.assertRaises(ValidationError) as cm:
  1664. module.clean()
  1665. self.assertIn('module_bay', cm.exception.message_dict)
  1666. self.assertIn('disabled module bay', str(cm.exception.message_dict['module_bay']))
  1667. class CableTestCase(TestCase):
  1668. @classmethod
  1669. def setUpTestData(cls):
  1670. site = Site.objects.create(name='Test Site 1', slug='test-site-1')
  1671. manufacturer = Manufacturer.objects.create(name='Test Manufacturer 1', slug='test-manufacturer-1')
  1672. devicetype = DeviceType.objects.create(
  1673. manufacturer=manufacturer, model='Test Device Type 1', slug='test-device-type-1'
  1674. )
  1675. role = DeviceRole.objects.create(
  1676. name='Test Device Role 1', slug='test-device-role-1', color='ff0000'
  1677. )
  1678. device1 = Device.objects.create(
  1679. device_type=devicetype, role=role, name='TestDevice1', site=site
  1680. )
  1681. device2 = Device.objects.create(
  1682. device_type=devicetype, role=role, name='TestDevice2', site=site
  1683. )
  1684. interfaces = (
  1685. Interface(device=device1, name='eth0'),
  1686. Interface(device=device2, name='eth0'),
  1687. Interface(device=device2, name='eth1'),
  1688. )
  1689. Interface.objects.bulk_create(interfaces)
  1690. Cable(a_terminations=[interfaces[0]], b_terminations=[interfaces[1]]).save()
  1691. PowerPort.objects.create(device=device2, name='psu1')
  1692. patch_panel = Device.objects.create(
  1693. device_type=devicetype, role=role, name='TestPatchPanel', site=site
  1694. )
  1695. rear_ports = (
  1696. RearPort(device=patch_panel, name='RP1', type='8p8c'),
  1697. RearPort(device=patch_panel, name='RP2', type='8p8c', positions=2),
  1698. RearPort(device=patch_panel, name='RP3', type='8p8c', positions=3),
  1699. RearPort(device=patch_panel, name='RP4', type='8p8c', positions=3),
  1700. )
  1701. RearPort.objects.bulk_create(rear_ports)
  1702. front_ports = (
  1703. FrontPort(device=patch_panel, name='FP1', type='8p8c'),
  1704. FrontPort(device=patch_panel, name='FP2', type='8p8c'),
  1705. FrontPort(device=patch_panel, name='FP3', type='8p8c'),
  1706. FrontPort(device=patch_panel, name='FP4', type='8p8c'),
  1707. )
  1708. FrontPort.objects.bulk_create(front_ports)
  1709. PortMapping.objects.bulk_create([
  1710. PortMapping(device=patch_panel, front_port=front_ports[0], rear_port=rear_ports[0]),
  1711. PortMapping(device=patch_panel, front_port=front_ports[1], rear_port=rear_ports[1]),
  1712. PortMapping(device=patch_panel, front_port=front_ports[2], rear_port=rear_ports[2]),
  1713. PortMapping(device=patch_panel, front_port=front_ports[3], rear_port=rear_ports[3]),
  1714. ])
  1715. provider = Provider.objects.create(name='Provider 1', slug='provider-1')
  1716. provider_network = ProviderNetwork.objects.create(name='Provider Network 1', provider=provider)
  1717. circuittype = CircuitType.objects.create(name='Circuit Type 1', slug='circuit-type-1')
  1718. circuit1 = Circuit.objects.create(provider=provider, type=circuittype, cid='1')
  1719. circuit2 = Circuit.objects.create(provider=provider, type=circuittype, cid='2')
  1720. CircuitTermination.objects.create(circuit=circuit1, termination=site, term_side='A')
  1721. CircuitTermination.objects.create(circuit=circuit1, termination=site, term_side='Z')
  1722. CircuitTermination.objects.create(circuit=circuit2, termination=provider_network, term_side='A')
  1723. def test_cable_creation(self):
  1724. """
  1725. When a new Cable is created, it must be cached on either termination point.
  1726. """
  1727. interface1 = Interface.objects.get(device__name='TestDevice1', name='eth0')
  1728. interface2 = Interface.objects.get(device__name='TestDevice2', name='eth0')
  1729. cable = Cable.objects.first()
  1730. self.assertEqual(interface1.cable, cable)
  1731. self.assertEqual(interface2.cable, cable)
  1732. self.assertEqual(interface1.cable_end, 'A')
  1733. self.assertEqual(interface2.cable_end, 'B')
  1734. self.assertEqual(interface1.link_peers, [interface2])
  1735. self.assertEqual(interface2.link_peers, [interface1])
  1736. def test_cable_deletion(self):
  1737. """
  1738. When a Cable is deleted, the `cable` field on its termination points must be nullified. The str() method
  1739. should still return the PK of the string even after being nullified.
  1740. """
  1741. interface1 = Interface.objects.get(device__name='TestDevice1', name='eth0')
  1742. interface2 = Interface.objects.get(device__name='TestDevice2', name='eth0')
  1743. cable = Cable.objects.first()
  1744. cable.delete()
  1745. self.assertIsNone(cable.pk)
  1746. self.assertNotEqual(str(cable), '#None')
  1747. interface1 = Interface.objects.get(pk=interface1.pk)
  1748. self.assertIsNone(interface1.cable)
  1749. self.assertListEqual(interface1.link_peers, [])
  1750. interface2 = Interface.objects.get(pk=interface2.pk)
  1751. self.assertIsNone(interface2.cable)
  1752. self.assertListEqual(interface2.link_peers, [])
  1753. def test_cable_validates_same_parent_object(self):
  1754. """
  1755. The clean method should ensure that all terminations at either end of a Cable belong to the same parent object.
  1756. """
  1757. interface1 = Interface.objects.get(device__name='TestDevice1', name='eth0')
  1758. powerport1 = PowerPort.objects.get(device__name='TestDevice2', name='psu1')
  1759. cable = Cable(a_terminations=[interface1], b_terminations=[powerport1])
  1760. with self.assertRaises(ValidationError):
  1761. cable.clean()
  1762. def test_cable_validates_same_type(self):
  1763. """
  1764. The clean method should ensure that all terminations at either end of a Cable are of the same type.
  1765. """
  1766. interface1 = Interface.objects.get(device__name='TestDevice1', name='eth0')
  1767. frontport1 = FrontPort.objects.get(device__name='TestPatchPanel', name='FP1')
  1768. rearport1 = RearPort.objects.get(device__name='TestPatchPanel', name='RP1')
  1769. cable = Cable(a_terminations=[frontport1, rearport1], b_terminations=[interface1])
  1770. with self.assertRaises(ValidationError):
  1771. cable.clean()
  1772. def test_cable_validates_compatible_types(self):
  1773. """
  1774. The clean method should have a check to ensure only compatible port types can be connected by a cable
  1775. """
  1776. interface1 = Interface.objects.get(device__name='TestDevice1', name='eth0')
  1777. powerport1 = PowerPort.objects.get(device__name='TestDevice2', name='psu1')
  1778. # An interface cannot be connected to a power port, for example
  1779. cable = Cable(a_terminations=[interface1], b_terminations=[powerport1])
  1780. with self.assertRaises(ValidationError):
  1781. cable.clean()
  1782. def test_cable_cannot_terminate_to_a_provider_network_circuittermination(self):
  1783. """
  1784. Neither side of a cable can be terminated to a CircuitTermination which is attached to a ProviderNetwork
  1785. """
  1786. interface3 = Interface.objects.get(device__name='TestDevice2', name='eth1')
  1787. circuittermination3 = CircuitTermination.objects.get(circuit__cid='2', term_side='A')
  1788. cable = Cable(a_terminations=[interface3], b_terminations=[circuittermination3])
  1789. with self.assertRaises(ValidationError):
  1790. cable.clean()
  1791. def test_cable_cannot_terminate_to_a_virtual_interface(self):
  1792. """
  1793. A cable cannot terminate to a virtual interface
  1794. """
  1795. device1 = Device.objects.get(name='TestDevice1')
  1796. interface2 = Interface.objects.get(device__name='TestDevice2', name='eth0')
  1797. virtual_interface = Interface(device=device1, name="V1", type=InterfaceTypeChoices.TYPE_VIRTUAL)
  1798. cable = Cable(a_terminations=[interface2], b_terminations=[virtual_interface])
  1799. with self.assertRaises(ValidationError):
  1800. cable.clean()
  1801. def test_cable_cannot_terminate_to_a_wireless_interface(self):
  1802. """
  1803. A cable cannot terminate to a wireless interface
  1804. """
  1805. device1 = Device.objects.get(name='TestDevice1')
  1806. interface2 = Interface.objects.get(device__name='TestDevice2', name='eth0')
  1807. wireless_interface = Interface(device=device1, name="W1", type=InterfaceTypeChoices.TYPE_80211A)
  1808. cable = Cable(a_terminations=[interface2], b_terminations=[wireless_interface])
  1809. with self.assertRaises(ValidationError):
  1810. cable.clean()
  1811. @tag('regression')
  1812. def test_cable_cannot_terminate_to_a_cellular_interface(self):
  1813. """
  1814. A cable cannot terminate to a cellular interface
  1815. """
  1816. device1 = Device.objects.get(name='TestDevice1')
  1817. interface2 = Interface.objects.get(device__name='TestDevice2', name='eth0')
  1818. cellular_interface = Interface(device=device1, name="W1", type=InterfaceTypeChoices.TYPE_LTE)
  1819. cable = Cable(a_terminations=[interface2], b_terminations=[cellular_interface])
  1820. with self.assertRaises(ValidationError):
  1821. cable.clean()
  1822. def test_cannot_cable_to_mark_connected(self):
  1823. """
  1824. Test that a cable cannot be connected to an interface marked as connected.
  1825. """
  1826. device1 = Device.objects.get(name='TestDevice1')
  1827. interface1 = Interface.objects.get(device__name='TestDevice2', name='eth1')
  1828. mark_connected_interface = Interface(device=device1, name='mark_connected1', mark_connected=True)
  1829. cable = Cable(a_terminations=[mark_connected_interface], b_terminations=[interface1])
  1830. with self.assertRaises(ValidationError):
  1831. cable.clean()
  1832. def test_cable_profile_change_preserves_terminations(self):
  1833. """
  1834. When a Cable's profile is changed via save() without explicitly setting terminations (as happens during
  1835. bulk edit), the existing termination points must be preserved.
  1836. """
  1837. cable = Cable.objects.first()
  1838. interface1 = Interface.objects.get(device__name='TestDevice1', name='eth0')
  1839. interface2 = Interface.objects.get(device__name='TestDevice2', name='eth0')
  1840. # Verify initial state: cable has terminations and no profile
  1841. self.assertEqual(cable.profile, '')
  1842. self.assertEqual(CableTermination.objects.filter(cable=cable).count(), 2)
  1843. # Simulate what bulk edit does: load the cable from DB, set profile via setattr, and save.
  1844. # Crucially, do NOT set a_terminations or b_terminations on the instance.
  1845. cable_from_db = Cable.objects.get(pk=cable.pk)
  1846. cable_from_db.profile = CableProfileChoices.SINGLE_1C1P
  1847. cable_from_db.save()
  1848. # Verify terminations are preserved
  1849. self.assertEqual(CableTermination.objects.filter(cable=cable).count(), 2)
  1850. # Verify the correct interfaces are still terminated
  1851. cable_from_db.refresh_from_db()
  1852. a_terms = [ct.termination for ct in CableTermination.objects.filter(cable=cable, cable_end='A')]
  1853. b_terms = [ct.termination for ct in CableTermination.objects.filter(cable=cable, cable_end='B')]
  1854. self.assertEqual(a_terms, [interface1])
  1855. self.assertEqual(b_terms, [interface2])
  1856. @tag('regression') # #21498
  1857. def test_path_refreshes_replaced_cablepath_reference(self):
  1858. """
  1859. An already-instantiated interface should refresh its denormalized
  1860. `_path` foreign key when the referenced CablePath row has been
  1861. replaced in the database.
  1862. """
  1863. stale_interface = Interface.objects.get(device__name='TestDevice1', name='eth0')
  1864. old_path = CablePath.objects.get(pk=stale_interface._path_id)
  1865. new_path = CablePath(
  1866. path=old_path.path,
  1867. is_active=old_path.is_active,
  1868. is_complete=old_path.is_complete,
  1869. is_split=old_path.is_split,
  1870. )
  1871. old_path_id = old_path.pk
  1872. old_path.delete()
  1873. new_path.save()
  1874. # The old CablePath no longer exists
  1875. self.assertFalse(CablePath.objects.filter(pk=old_path_id).exists())
  1876. # The already-instantiated interface still points to the deleted path
  1877. # until the accessor refreshes `_path` from the database.
  1878. self.assertEqual(stale_interface._path_id, old_path_id)
  1879. self.assertEqual(stale_interface.path.pk, new_path.pk)
  1880. @tag('regression') # #21498
  1881. def test_serialize_for_event_handles_stale_cablepath_reference_after_retermination(self):
  1882. """
  1883. Serializing an interface whose previously cached `_path` row has been
  1884. deleted during cable retermination must not raise.
  1885. """
  1886. stale_interface = Interface.objects.get(device__name='TestDevice2', name='eth0')
  1887. old_path_id = stale_interface._path_id
  1888. new_peer = Interface.objects.get(device__name='TestDevice2', name='eth1')
  1889. cable = stale_interface.cable
  1890. self.assertIsNotNone(cable)
  1891. self.assertIsNotNone(old_path_id)
  1892. self.assertEqual(stale_interface.cable_end, 'B')
  1893. cable.b_terminations = [new_peer]
  1894. cable.save()
  1895. # The old CablePath was deleted during retrace.
  1896. self.assertFalse(CablePath.objects.filter(pk=old_path_id).exists())
  1897. # The stale in-memory instance still holds the deleted FK value.
  1898. self.assertEqual(stale_interface._path_id, old_path_id)
  1899. # Serialization must not raise ObjectDoesNotExist. Because this interface
  1900. # was the former B-side termination, it is now disconnected.
  1901. data = serialize_for_event(stale_interface)
  1902. self.assertIsNone(data['connected_endpoints'])
  1903. self.assertIsNone(data['connected_endpoints_type'])
  1904. self.assertFalse(data['connected_endpoints_reachable'])
  1905. @tag('regression') # #21338
  1906. def test_path_refreshes_unset_cablepath_reference(self):
  1907. """
  1908. An endpoint instance saved during cable creation, before path tracing,
  1909. should resolve its path and connected endpoints.
  1910. The stale-instance preconditions rely on Cable.save() saving each
  1911. CableTermination (which re-saves the endpoint) before trace_paths
  1912. creates the CablePath records.
  1913. """
  1914. device = Device.objects.get(name='TestDevice2')
  1915. interface_a = Interface.objects.create(device=device, name='eth2')
  1916. interface_b = Interface.objects.create(device=device, name='eth3')
  1917. # Capture the instances handed to the event machinery on save
  1918. saved_instances = []
  1919. def capture(sender, instance, **kwargs):
  1920. saved_instances.append(instance)
  1921. post_save.connect(capture, sender=Interface)
  1922. try:
  1923. Cable(a_terminations=[interface_a], b_terminations=[interface_b]).save()
  1924. finally:
  1925. post_save.disconnect(capture, sender=Interface)
  1926. self.assertEqual(len(saved_instances), 2)
  1927. captured_a = next(i for i in saved_instances if i.pk == interface_a.pk)
  1928. captured_b = next(i for i in saved_instances if i.pk == interface_b.pk)
  1929. # The captured instances predate path tracing: cabled, but no path yet
  1930. self.assertIsNotNone(captured_a.cable_id)
  1931. self.assertIsNone(captured_a._path_id)
  1932. self.assertIsNone(captured_b._path_id)
  1933. # The accessor must repair the unset denormalized reference
  1934. self.assertIsNotNone(captured_a.path)
  1935. self.assertEqual(captured_a.connected_endpoints, [interface_b])
  1936. # Serialization as performed by the event queue must see the peer
  1937. data = serialize_for_event(captured_b)
  1938. self.assertEqual([endpoint['id'] for endpoint in data['connected_endpoints']], [interface_a.pk])
  1939. self.assertEqual([peer['id'] for peer in data['link_peers']], [interface_a.pk])
  1940. self.assertTrue(data['connected_endpoints_reachable'])
  1941. def test_path_returns_none_for_unsaved_endpoint(self):
  1942. """
  1943. An unsaved endpoint with a link assigned should report no path rather
  1944. than attempting a database refresh.
  1945. """
  1946. device = Device.objects.get(name='TestDevice1')
  1947. cable = Cable.objects.first()
  1948. interface = Interface(device=device, name='tmp', cable=cable)
  1949. self.assertIsNone(interface.path)
  1950. class CableTerminationTestCase(TestCase):
  1951. def test_cache_related_objects_requires_resolvable_termination(self):
  1952. """cache_related_objects raises ValueError when the termination cannot be resolved."""
  1953. cable_termination = CableTermination(
  1954. termination_type=ObjectType.objects.get_for_model(Interface),
  1955. termination_id=0,
  1956. )
  1957. with self.assertRaises(ValueError):
  1958. cable_termination.cache_related_objects()
  1959. class VirtualDeviceContextTestCase(TestCase):
  1960. @classmethod
  1961. def setUpTestData(cls):
  1962. site = Site.objects.create(name='Test Site 1', slug='test-site-1')
  1963. manufacturer = Manufacturer.objects.create(name='Test Manufacturer 1', slug='test-manufacturer-1')
  1964. devicetype = DeviceType.objects.create(
  1965. manufacturer=manufacturer, model='Test Device Type 1', slug='test-device-type-1'
  1966. )
  1967. role = DeviceRole.objects.create(
  1968. name='Test Device Role 1', slug='test-device-role-1', color='ff0000'
  1969. )
  1970. Device.objects.create(
  1971. device_type=devicetype, role=role, name='TestDevice1', site=site
  1972. )
  1973. def test_vdc_and_interface_creation(self):
  1974. device = Device.objects.first()
  1975. vdc = VirtualDeviceContext(device=device, name="VDC 1", identifier=1, status='active')
  1976. vdc.full_clean()
  1977. vdc.save()
  1978. interface = Interface(device=device, name='Eth1/1', type='10gbase-t')
  1979. interface.full_clean()
  1980. interface.save()
  1981. interface.vdcs.set([vdc])
  1982. def test_vdc_duplicate_name(self):
  1983. device = Device.objects.first()
  1984. vdc1 = VirtualDeviceContext(device=device, name="VDC 1", identifier=1, status='active')
  1985. vdc1.full_clean()
  1986. vdc1.save()
  1987. vdc2 = VirtualDeviceContext(device=device, name="VDC 1", identifier=2, status='active')
  1988. with self.assertRaises(ValidationError):
  1989. vdc2.full_clean()
  1990. def test_vdc_duplicate_identifier(self):
  1991. device = Device.objects.first()
  1992. vdc1 = VirtualDeviceContext(device=device, name="VDC 1", identifier=1, status='active')
  1993. vdc1.full_clean()
  1994. vdc1.save()
  1995. vdc2 = VirtualDeviceContext(device=device, name="VDC 2", identifier=1, status='active')
  1996. with self.assertRaises(ValidationError):
  1997. vdc2.full_clean()
  1998. class VirtualChassisTestCase(TestCase):
  1999. @classmethod
  2000. def setUpTestData(cls):
  2001. site = Site.objects.create(name='Test Site 1', slug='test-site-1')
  2002. manufacturer = Manufacturer.objects.create(name='Test Manufacturer 1', slug='test-manufacturer-1')
  2003. devicetype = DeviceType.objects.create(
  2004. manufacturer=manufacturer, model='Test Device Type 1', slug='test-device-type-1'
  2005. )
  2006. role = DeviceRole.objects.create(
  2007. name='Test Device Role 1', slug='test-device-role-1', color='ff0000'
  2008. )
  2009. Device.objects.create(
  2010. device_type=devicetype, role=role, name='TestDevice1', site=site
  2011. )
  2012. Device.objects.create(
  2013. device_type=devicetype, role=role, name='TestDevice2', site=site
  2014. )
  2015. def test_virtualchassis_deletion_clears_vc_position(self):
  2016. """
  2017. Test that when a VirtualChassis is deleted, member devices have their
  2018. vc_position and vc_priority fields set to None.
  2019. """
  2020. devices = Device.objects.all()
  2021. device1 = devices[0]
  2022. device2 = devices[1]
  2023. # Create a VirtualChassis with two member devices
  2024. vc = VirtualChassis.objects.create(name='Test VC', master=device1)
  2025. device1.virtual_chassis = vc
  2026. device1.vc_position = 1
  2027. device1.vc_priority = 10
  2028. device1.save()
  2029. device2.virtual_chassis = vc
  2030. device2.vc_position = 2
  2031. device2.vc_priority = 20
  2032. device2.save()
  2033. # Verify devices are members of the VC with positions set
  2034. device1.refresh_from_db()
  2035. device2.refresh_from_db()
  2036. self.assertEqual(device1.virtual_chassis, vc)
  2037. self.assertEqual(device1.vc_position, 1)
  2038. self.assertEqual(device1.vc_priority, 10)
  2039. self.assertEqual(device2.virtual_chassis, vc)
  2040. self.assertEqual(device2.vc_position, 2)
  2041. self.assertEqual(device2.vc_priority, 20)
  2042. # Delete the VirtualChassis
  2043. vc.delete()
  2044. # Verify devices have vc_position and vc_priority set to None
  2045. device1.refresh_from_db()
  2046. device2.refresh_from_db()
  2047. self.assertIsNone(device1.virtual_chassis)
  2048. self.assertIsNone(device1.vc_position)
  2049. self.assertIsNone(device1.vc_priority)
  2050. self.assertIsNone(device2.virtual_chassis)
  2051. self.assertIsNone(device2.vc_position)
  2052. self.assertIsNone(device2.vc_priority)
  2053. def test_virtualchassis_duplicate_vc_position(self):
  2054. """
  2055. Test that two devices cannot be assigned to the same vc_position
  2056. within the same VirtualChassis.
  2057. """
  2058. devices = Device.objects.all()
  2059. device1 = devices[0]
  2060. device2 = devices[1]
  2061. # Create a VirtualChassis
  2062. vc = VirtualChassis.objects.create(name='Test VC')
  2063. # Assign first device to vc_position 1
  2064. device1.virtual_chassis = vc
  2065. device1.vc_position = 1
  2066. device1.full_clean()
  2067. device1.save()
  2068. # Try to assign second device to the same vc_position
  2069. device2.virtual_chassis = vc
  2070. device2.vc_position = 1
  2071. with self.assertRaises(ValidationError):
  2072. device2.full_clean()
  2073. class VCPositionTokenTestCase(TestCase):
  2074. @classmethod
  2075. def setUpTestData(cls):
  2076. Site.objects.create(name='Test Site 1', slug='test-site-1')
  2077. manufacturer = Manufacturer.objects.create(name='Test Manufacturer 1', slug='test-manufacturer-1')
  2078. DeviceType.objects.create(
  2079. manufacturer=manufacturer, model='Test Device Type 1', slug='test-device-type-1'
  2080. )
  2081. ModuleType.objects.create(
  2082. manufacturer=manufacturer, model='Test Module Type 1'
  2083. )
  2084. DeviceRole.objects.create(name='Test Role 1', slug='test-role-1')
  2085. def test_vc_position_token_in_vc(self):
  2086. site = Site.objects.first()
  2087. device_type = DeviceType.objects.first()
  2088. module_type = ModuleType.objects.first()
  2089. device_role = DeviceRole.objects.first()
  2090. InterfaceTemplate.objects.create(
  2091. module_type=module_type,
  2092. name='ge-{vc_position}/{module}/0',
  2093. type='1000base-t',
  2094. )
  2095. vc = VirtualChassis.objects.create(name='Test VC 1')
  2096. device = Device.objects.create(
  2097. name='Device VC 1', device_type=device_type, role=device_role,
  2098. site=site, virtual_chassis=vc, vc_position=8,
  2099. )
  2100. module_bay = ModuleBay.objects.create(device=device, name='Bay 1', position='1')
  2101. Module.objects.create(device=device, module_bay=module_bay, module_type=module_type)
  2102. interface = device.interfaces.get(name='ge-8/1/0')
  2103. self.assertEqual(interface.name, 'ge-8/1/0')
  2104. def test_vc_position_token_not_in_vc_default_fallback(self):
  2105. site = Site.objects.first()
  2106. device_type = DeviceType.objects.first()
  2107. module_type = ModuleType.objects.first()
  2108. device_role = DeviceRole.objects.first()
  2109. InterfaceTemplate.objects.create(
  2110. module_type=module_type,
  2111. name='ge-{vc_position}/{module}/0',
  2112. type='1000base-t',
  2113. )
  2114. device = Device.objects.create(
  2115. name='Device NoVC 1', device_type=device_type, role=device_role,
  2116. site=site,
  2117. )
  2118. module_bay = ModuleBay.objects.create(device=device, name='Bay 1', position='1')
  2119. Module.objects.create(device=device, module_bay=module_bay, module_type=module_type)
  2120. interface = device.interfaces.get(name='ge-0/1/0')
  2121. self.assertEqual(interface.name, 'ge-0/1/0')
  2122. def test_vc_position_token_explicit_fallback(self):
  2123. site = Site.objects.first()
  2124. device_type = DeviceType.objects.first()
  2125. module_type = ModuleType.objects.first()
  2126. device_role = DeviceRole.objects.first()
  2127. InterfaceTemplate.objects.create(
  2128. module_type=module_type,
  2129. name='ge-{vc_position:18}/{module}/0',
  2130. type='1000base-t',
  2131. )
  2132. device = Device.objects.create(
  2133. name='Device NoVC 2', device_type=device_type, role=device_role,
  2134. site=site,
  2135. )
  2136. module_bay = ModuleBay.objects.create(device=device, name='Bay 1', position='1')
  2137. Module.objects.create(device=device, module_bay=module_bay, module_type=module_type)
  2138. interface = device.interfaces.get(name='ge-18/1/0')
  2139. self.assertEqual(interface.name, 'ge-18/1/0')
  2140. def test_vc_position_token_explicit_fallback_ignored_when_in_vc(self):
  2141. site = Site.objects.first()
  2142. device_type = DeviceType.objects.first()
  2143. module_type = ModuleType.objects.first()
  2144. device_role = DeviceRole.objects.first()
  2145. InterfaceTemplate.objects.create(
  2146. module_type=module_type,
  2147. name='ge-{vc_position:99}/{module}/0',
  2148. type='1000base-t',
  2149. )
  2150. vc = VirtualChassis.objects.create(name='Test VC 2')
  2151. device = Device.objects.create(
  2152. name='Device VC 2', device_type=device_type, role=device_role,
  2153. site=site, virtual_chassis=vc, vc_position=2,
  2154. )
  2155. module_bay = ModuleBay.objects.create(device=device, name='Bay 1', position='1')
  2156. Module.objects.create(device=device, module_bay=module_bay, module_type=module_type)
  2157. interface = device.interfaces.get(name='ge-2/1/0')
  2158. self.assertEqual(interface.name, 'ge-2/1/0')
  2159. def test_vc_position_token_device_type_template(self):
  2160. site = Site.objects.first()
  2161. device_type = DeviceType.objects.first()
  2162. device_role = DeviceRole.objects.first()
  2163. InterfaceTemplate.objects.create(
  2164. device_type=device_type,
  2165. name='ge-{vc_position:0}/0/0',
  2166. type='1000base-t',
  2167. )
  2168. vc = VirtualChassis.objects.create(name='Test VC 3')
  2169. device = Device.objects.create(
  2170. name='Device VC 3', device_type=device_type, role=device_role,
  2171. site=site, virtual_chassis=vc, vc_position=3,
  2172. )
  2173. interface = device.interfaces.get(name='ge-3/0/0')
  2174. self.assertEqual(interface.name, 'ge-3/0/0')
  2175. def test_vc_position_token_device_type_template_not_in_vc(self):
  2176. site = Site.objects.first()
  2177. device_type = DeviceType.objects.first()
  2178. device_role = DeviceRole.objects.first()
  2179. InterfaceTemplate.objects.create(
  2180. device_type=device_type,
  2181. name='ge-{vc_position:0}/0/0',
  2182. type='1000base-t',
  2183. )
  2184. device = Device.objects.create(
  2185. name='Device NoVC 3', device_type=device_type, role=device_role,
  2186. site=site,
  2187. )
  2188. interface = device.interfaces.get(name='ge-0/0/0')
  2189. self.assertEqual(interface.name, 'ge-0/0/0')
  2190. def test_vc_position_token_label_resolution(self):
  2191. site = Site.objects.first()
  2192. device_type = DeviceType.objects.first()
  2193. module_type = ModuleType.objects.first()
  2194. device_role = DeviceRole.objects.first()
  2195. InterfaceTemplate.objects.create(
  2196. module_type=module_type,
  2197. name='ge-{vc_position}/{module}/0',
  2198. label='Member {vc_position:0} / Slot {module}',
  2199. type='1000base-t',
  2200. )
  2201. vc = VirtualChassis.objects.create(name='Test VC 4')
  2202. device = Device.objects.create(
  2203. name='Device VC 4', device_type=device_type, role=device_role,
  2204. site=site, virtual_chassis=vc, vc_position=2,
  2205. )
  2206. module_bay = ModuleBay.objects.create(device=device, name='Bay 1', position='1')
  2207. Module.objects.create(device=device, module_bay=module_bay, module_type=module_type)
  2208. interface = device.interfaces.get(name='ge-2/1/0')
  2209. self.assertEqual(interface.label, 'Member 2 / Slot 1')
  2210. class SiteSignalTestCase(TestCase):
  2211. @tag('regression')
  2212. def test_edit_site_with_prefix_no_vrf(self):
  2213. site = Site.objects.create(name='Test Site', slug='test-site')
  2214. Prefix.objects.create(prefix='192.0.2.0/24', scope=site, vrf=None)
  2215. # Regression test for #21045: should not raise ValueError
  2216. site.save()
  2217. class PowerPortDrawTestCase(TestCase):
  2218. """
  2219. Tests for PowerPort.get_power_draw() power aggregation logic.
  2220. """
  2221. @classmethod
  2222. def setUpTestData(cls):
  2223. cls.site = Site.objects.create(name='Test Site', slug='test-site')
  2224. manufacturer = Manufacturer.objects.create(name='Generic', slug='generic')
  2225. device_type = DeviceType.objects.create(manufacturer=manufacturer, model='Test Device Type')
  2226. role = DeviceRole.objects.create(name='Test Role', slug='test-role')
  2227. cls.pdu = Device.objects.create(
  2228. device_type=device_type, role=role, site=cls.site, name='pdu'
  2229. )
  2230. cls.server = Device.objects.create(
  2231. device_type=device_type, role=role, site=cls.site, name='server'
  2232. )
  2233. def test_direct_draw_aggregation(self):
  2234. """
  2235. Sanity check: with one PowerOutlet chained directly to a downstream PSU PowerPort,
  2236. the upstream PowerPort should reflect the PSU's allocated/maximum draw.
  2237. [main] -- [outlet] --C-- [psu]
  2238. """
  2239. main = PowerPort.objects.create(device=self.pdu, name='main')
  2240. outlet = PowerOutlet.objects.create(device=self.pdu, name='outlet', power_port=main)
  2241. psu = PowerPort.objects.create(
  2242. device=self.server, name='psu', allocated_draw=200, maximum_draw=400
  2243. )
  2244. Cable(a_terminations=[outlet], b_terminations=[psu]).save()
  2245. draw = main.get_power_draw()
  2246. self.assertEqual(draw['allocated'], 200)
  2247. self.assertEqual(draw['maximum'], 400)
  2248. @tag('regression')
  2249. def test_recursive_draw_through_intermediate_powerport(self):
  2250. """
  2251. Regression test for #21949: A PDU modeled with internal fuses (intermediate PowerPorts in
  2252. auto mode) should still aggregate downstream PSU draw up to the main PowerPort.
  2253. [main] -- [feedback] --C-- [fuse] -- [outlet] --C-- [psu]
  2254. Both `main` and `fuse` are in auto mode (no allocated_draw/maximum_draw set). The draw
  2255. reported by `psu` must propagate through `fuse` and be reflected at `main`.
  2256. """
  2257. main = PowerPort.objects.create(device=self.pdu, name='main')
  2258. feedback = PowerOutlet.objects.create(device=self.pdu, name='feedback', power_port=main)
  2259. fuse = PowerPort.objects.create(device=self.pdu, name='fuse')
  2260. outlet = PowerOutlet.objects.create(device=self.pdu, name='outlet', power_port=fuse)
  2261. psu = PowerPort.objects.create(
  2262. device=self.server, name='psu', allocated_draw=150, maximum_draw=300
  2263. )
  2264. Cable(a_terminations=[feedback], b_terminations=[fuse]).save()
  2265. Cable(a_terminations=[outlet], b_terminations=[psu]).save()
  2266. fuse_draw = fuse.get_power_draw()
  2267. self.assertEqual(fuse_draw['allocated'], 150)
  2268. self.assertEqual(fuse_draw['maximum'], 300)
  2269. main_draw = main.get_power_draw()
  2270. self.assertEqual(main_draw['allocated'], 150)
  2271. self.assertEqual(main_draw['maximum'], 300)
  2272. def test_intermediate_manual_override_stops_recursion(self):
  2273. """
  2274. When an intermediate PowerPort has an explicit allocated_draw/maximum_draw, recursion should
  2275. stop there and the administratively defined values should be used.
  2276. """
  2277. main = PowerPort.objects.create(device=self.pdu, name='main')
  2278. feedback = PowerOutlet.objects.create(device=self.pdu, name='feedback', power_port=main)
  2279. fuse = PowerPort.objects.create(
  2280. device=self.pdu, name='fuse', allocated_draw=500, maximum_draw=1000
  2281. )
  2282. outlet = PowerOutlet.objects.create(device=self.pdu, name='outlet', power_port=fuse)
  2283. psu = PowerPort.objects.create(
  2284. device=self.server, name='psu', allocated_draw=150, maximum_draw=300
  2285. )
  2286. Cable(a_terminations=[feedback], b_terminations=[fuse]).save()
  2287. Cable(a_terminations=[outlet], b_terminations=[psu]).save()
  2288. main_draw = main.get_power_draw()
  2289. self.assertEqual(main_draw['allocated'], 500)
  2290. self.assertEqual(main_draw['maximum'], 1000)
  2291. def _connect_three_phase_feed(self, powerport):
  2292. """
  2293. Helper: attach `powerport` via cable to a newly-created three-phase PowerFeed.
  2294. """
  2295. power_panel = PowerPanel.objects.create(site=self.site, name='Panel')
  2296. power_feed = PowerFeed.objects.create(
  2297. power_panel=power_panel,
  2298. name='Feed',
  2299. phase=PowerFeedPhaseChoices.PHASE_3PHASE,
  2300. )
  2301. Cable(a_terminations=[powerport], b_terminations=[power_feed]).save()
  2302. @tag('regression')
  2303. def test_three_phase_per_leg_aggregation(self):
  2304. """
  2305. Regression test: per-leg totals for a main PowerPort connected to a three-phase PowerFeed
  2306. must be populated even when the full aggregation runs first. Previously, a shared visited
  2307. set caused downstream ports to be skipped during the per-leg passes, zeroing the legs.
  2308. [main] --C-- [3-phase PowerFeed]
  2309. ├── [outlet_A] (leg A) --C-- [portA] (allocated=100, maximum=200)
  2310. ├── [outlet_B] (leg B) --C-- [portB] (allocated=200, maximum=400)
  2311. └── [outlet_C] (leg C) --C-- [portC] (allocated=300, maximum=600)
  2312. """
  2313. main = PowerPort.objects.create(device=self.pdu, name='main')
  2314. self._connect_three_phase_feed(main)
  2315. leg_specs = [
  2316. (PowerOutletFeedLegChoices.FEED_LEG_A, 100, 200),
  2317. (PowerOutletFeedLegChoices.FEED_LEG_B, 200, 400),
  2318. (PowerOutletFeedLegChoices.FEED_LEG_C, 300, 600),
  2319. ]
  2320. for leg, allocated, maximum in leg_specs:
  2321. outlet = PowerOutlet.objects.create(
  2322. device=self.pdu, name=f'outlet_{leg}', power_port=main, feed_leg=leg
  2323. )
  2324. port = PowerPort.objects.create(
  2325. device=self.server, name=f'psu_{leg}',
  2326. allocated_draw=allocated, maximum_draw=maximum,
  2327. )
  2328. Cable(a_terminations=[outlet], b_terminations=[port]).save()
  2329. # Re-fetch to clear cached_property values populated before cable creation
  2330. main = PowerPort.objects.get(pk=main.pk)
  2331. draw = main.get_power_draw()
  2332. self.assertEqual(draw['allocated'], 600)
  2333. self.assertEqual(draw['maximum'], 1200)
  2334. legs_by_name = {leg['name']: leg for leg in draw['legs']}
  2335. self.assertEqual(legs_by_name['A']['allocated'], 100)
  2336. self.assertEqual(legs_by_name['A']['maximum'], 200)
  2337. self.assertEqual(legs_by_name['B']['allocated'], 200)
  2338. self.assertEqual(legs_by_name['B']['maximum'], 400)
  2339. self.assertEqual(legs_by_name['C']['allocated'], 300)
  2340. self.assertEqual(legs_by_name['C']['maximum'], 600)
  2341. @tag('regression')
  2342. def test_three_phase_per_leg_recursive_aggregation(self):
  2343. """
  2344. Regression test for #21949 on three-phase feeds: per-leg totals must aggregate through
  2345. intermediate auto-mode PowerPorts (the PDU-internal "fuse" pattern).
  2346. [main] --C-- [3-phase PowerFeed]
  2347. └── [feedback_A] (leg A) --C-- [fuse_A] (auto)
  2348. └── [outlet_A] (leg A) --C-- [psu_A] (allocated=100)
  2349. """
  2350. main = PowerPort.objects.create(device=self.pdu, name='main')
  2351. self._connect_three_phase_feed(main)
  2352. feedback = PowerOutlet.objects.create(
  2353. device=self.pdu, name='feedback_A', power_port=main,
  2354. feed_leg=PowerOutletFeedLegChoices.FEED_LEG_A,
  2355. )
  2356. fuse = PowerPort.objects.create(device=self.pdu, name='fuse_A')
  2357. outlet = PowerOutlet.objects.create(
  2358. device=self.pdu, name='outlet_A', power_port=fuse,
  2359. feed_leg=PowerOutletFeedLegChoices.FEED_LEG_A,
  2360. )
  2361. psu = PowerPort.objects.create(
  2362. device=self.server, name='psu_A', allocated_draw=100, maximum_draw=200
  2363. )
  2364. Cable(a_terminations=[feedback], b_terminations=[fuse]).save()
  2365. Cable(a_terminations=[outlet], b_terminations=[psu]).save()
  2366. # Re-fetch to clear cached_property values populated before cable creation
  2367. main = PowerPort.objects.get(pk=main.pk)
  2368. draw = main.get_power_draw()
  2369. self.assertEqual(draw['allocated'], 100)
  2370. self.assertEqual(draw['maximum'], 200)
  2371. legs_by_name = {leg['name']: leg for leg in draw['legs']}
  2372. self.assertEqual(legs_by_name['A']['allocated'], 100)
  2373. self.assertEqual(legs_by_name['A']['maximum'], 200)
  2374. self.assertEqual(legs_by_name['B']['allocated'], 0)
  2375. self.assertEqual(legs_by_name['C']['allocated'], 0)
  2376. class InventoryItemCycleTestCase(TestCase):
  2377. """
  2378. InventoryItem (ltree-backed, not the nested-group base) must reject assigning
  2379. self or a descendant as parent — behavior django-mptt previously enforced via
  2380. InvalidMove on save().
  2381. """
  2382. @classmethod
  2383. def setUpTestData(cls):
  2384. site = Site.objects.create(name='Site 1', slug='inv-site-1')
  2385. manufacturer = Manufacturer.objects.create(name='Manufacturer 1', slug='inv-mfr-1')
  2386. device_type = DeviceType.objects.create(
  2387. manufacturer=manufacturer, model='Device Type 1', slug='inv-dt-1'
  2388. )
  2389. role = DeviceRole.objects.create(name='Role 1', slug='inv-role-1')
  2390. cls.device = Device.objects.create(
  2391. name='Device 1', device_type=device_type, role=role, site=site
  2392. )
  2393. def test_cannot_assign_descendant_as_parent(self):
  2394. a = InventoryItem.objects.create(device=self.device, name='A')
  2395. b = InventoryItem.objects.create(device=self.device, name='B', parent=a)
  2396. c = InventoryItem.objects.create(device=self.device, name='C', parent=b)
  2397. a.parent = c
  2398. with self.assertRaises(ValidationError):
  2399. a.full_clean()
  2400. # The save()-level guard also rejects the cycle when clean() is bypassed.
  2401. with self.assertRaises(ValidationError):
  2402. a.save()
  2403. def test_cannot_assign_self_as_parent(self):
  2404. a = InventoryItem.objects.create(device=self.device, name='A')
  2405. a.parent = a
  2406. with self.assertRaises(ValidationError):
  2407. a.full_clean()
  2408. class InventoryItemTemplateCycleTestCase(TestCase):
  2409. """InventoryItemTemplate must likewise reject self/descendant as parent."""
  2410. @classmethod
  2411. def setUpTestData(cls):
  2412. manufacturer = Manufacturer.objects.create(name='Manufacturer 1', slug='iit-mfr-1')
  2413. cls.device_type = DeviceType.objects.create(
  2414. manufacturer=manufacturer, model='Device Type 1', slug='iit-dt-1'
  2415. )
  2416. def test_cannot_assign_descendant_as_parent(self):
  2417. a = InventoryItemTemplate.objects.create(device_type=self.device_type, name='A')
  2418. b = InventoryItemTemplate.objects.create(device_type=self.device_type, name='B', parent=a)
  2419. a.parent = b
  2420. with self.assertRaises(ValidationError):
  2421. a.full_clean()
  2422. with self.assertRaises(ValidationError):
  2423. a.save()
  2424. def test_cannot_assign_self_as_parent(self):
  2425. a = InventoryItemTemplate.objects.create(device_type=self.device_type, name='A')
  2426. a.parent = a
  2427. with self.assertRaises(ValidationError):
  2428. a.full_clean()