test_models.py 63 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674
  1. import io
  2. import tempfile
  3. from pathlib import Path
  4. from types import SimpleNamespace
  5. from unittest.mock import patch
  6. from django.contrib.contenttypes.models import ContentType
  7. from django.core.files.base import ContentFile
  8. from django.core.files.storage import Storage
  9. from django.core.files.uploadedfile import SimpleUploadedFile
  10. from django.forms import ValidationError
  11. from django.test import TestCase, tag
  12. from jinja2 import DebugUndefined, StrictUndefined, TemplateError, TemplateSyntaxError, UndefinedError
  13. from PIL import Image
  14. from core.events import OBJECT_CREATED
  15. from core.models import AutoSyncRecord, DataSource, ObjectType
  16. from dcim.models import Device, DeviceRole, DeviceType, Location, Manufacturer, Platform, Region, Site, SiteGroup
  17. from extras.constants import DEFAULT_MIME_TYPE
  18. from extras.models import (
  19. ConfigContext,
  20. ConfigContextProfile,
  21. ConfigTemplate,
  22. EventRule,
  23. ExportTemplate,
  24. ImageAttachment,
  25. TableConfig,
  26. Tag,
  27. TaggedItem,
  28. )
  29. from extras.models.mixins import RenderTemplateMixin
  30. from tenancy.models import Tenant, TenantGroup
  31. from utilities.exceptions import AbortRequest
  32. from utilities.jinja2 import env_filter, render_jinja2
  33. from utilities.tables import get_table_for_model
  34. from virtualization.models import Cluster, ClusterGroup, ClusterType, VirtualMachine
  35. class OverwriteStyleMemoryStorage(Storage):
  36. """
  37. In-memory storage that mimics overwrite-style backends by returning the
  38. incoming name unchanged from get_available_name().
  39. """
  40. def __init__(self):
  41. self.files = {}
  42. def _open(self, name, mode='rb'):
  43. return ContentFile(self.files[name], name=name)
  44. def _save(self, name, content):
  45. self.files[name] = content.read()
  46. return name
  47. def delete(self, name):
  48. self.files.pop(name, None)
  49. def exists(self, name):
  50. return name in self.files
  51. def get_available_name(self, name, max_length=None):
  52. return name
  53. def get_alternative_name(self, file_root, file_ext):
  54. return f'{file_root}_sdmmer4{file_ext}'
  55. def listdir(self, path):
  56. return [], list(self.files)
  57. def size(self, name):
  58. return len(self.files[name])
  59. def url(self, name):
  60. return f'https://example.invalid/{name}'
  61. class UnreadableSizeMemoryStorage(OverwriteStyleMemoryStorage):
  62. """
  63. Like OverwriteStyleMemoryStorage, but size() raises OSError to model a storage backend that is
  64. transiently unavailable (e.g. an S3 outage) when reading file size.
  65. """
  66. def size(self, name):
  67. raise OSError('storage unavailable')
  68. class ImageAttachmentTestCase(TestCase):
  69. @classmethod
  70. def setUpTestData(cls):
  71. cls.ct_rack = ContentType.objects.get_by_natural_key('dcim', 'rack')
  72. cls.ct_site = ContentType.objects.get_by_natural_key('dcim', 'site')
  73. cls.site = Site.objects.create(name='Site 1')
  74. cls.image_content = b''
  75. def _stub_image_attachment(self, object_id, image_filename, name=None):
  76. """
  77. Creates an instance of ImageAttachment with the provided object_id and image_name.
  78. This method prepares a stubbed image attachment to test functionalities that
  79. require an ImageAttachment object.
  80. The function initializes the attachment with a specified file name and
  81. pre-defined image content.
  82. """
  83. ia = ImageAttachment(
  84. object_type=self.ct_rack,
  85. object_id=object_id,
  86. name=name,
  87. image=SimpleUploadedFile(
  88. name=image_filename,
  89. content=self.image_content,
  90. content_type='image/jpeg',
  91. ),
  92. )
  93. return ia
  94. def _uploaded_png(self, filename):
  95. image = io.BytesIO()
  96. Image.new('RGB', (1, 1)).save(image, format='PNG')
  97. return SimpleUploadedFile(
  98. name=filename,
  99. content=image.getvalue(),
  100. content_type='image/png',
  101. )
  102. def test_filename_strips_expected_prefix(self):
  103. """
  104. Tests that the filename of the image attachment is stripped of the expected
  105. prefix.
  106. """
  107. ia = self._stub_image_attachment(12, 'image-attachments/rack_12_My_File.png')
  108. self.assertEqual(ia.filename, 'My_File.png')
  109. def test_filename_legacy_nested_path_returns_basename(self):
  110. """
  111. Tests if the filename of a legacy-nested path correctly returns only the basename.
  112. """
  113. # e.g. "image-attachments/rack_12_5/31/23.jpg" -> "23.jpg"
  114. ia = self._stub_image_attachment(12, 'image-attachments/rack_12_5/31/23.jpg')
  115. self.assertEqual(ia.filename, '23.jpg')
  116. def test_filename_no_prefix_returns_basename(self):
  117. """
  118. Tests that the filename property correctly returns the basename for an image
  119. attachment that has no leading prefix in its path.
  120. """
  121. ia = self._stub_image_attachment(42, 'image-attachments/just_name.webp')
  122. self.assertEqual(ia.filename, 'just_name.webp')
  123. def test_mismatched_prefix_is_not_stripped(self):
  124. """
  125. Tests that a mismatched prefix in the filename is not stripped.
  126. """
  127. # Prefix does not match object_id -> leave as-is (basename only)
  128. ia = self._stub_image_attachment(12, 'image-attachments/rack_13_other.png')
  129. self.assertEqual('rack_13_other.png', ia.filename)
  130. def test_str_uses_name_when_present(self):
  131. """
  132. Tests that the `str` representation of the object uses the
  133. `name` attribute when provided.
  134. """
  135. ia = self._stub_image_attachment(12, 'image-attachments/rack_12_file.png', name='Human title')
  136. self.assertEqual('Human title', str(ia))
  137. def test_str_falls_back_to_filename(self):
  138. """
  139. Tests that the `str` representation of the object falls back to
  140. the filename if the name attribute is not set.
  141. """
  142. ia = self._stub_image_attachment(12, 'image-attachments/rack_12_file.png', name='')
  143. self.assertEqual('file.png', str(ia))
  144. def test_duplicate_uploaded_names_get_suffixed_with_overwrite_style_storage(self):
  145. storage = OverwriteStyleMemoryStorage()
  146. field = ImageAttachment._meta.get_field('image')
  147. with patch.object(field, 'storage', storage):
  148. first = ImageAttachment(
  149. object_type=self.ct_site,
  150. object_id=self.site.pk,
  151. image=self._uploaded_png('action-buttons.png'),
  152. )
  153. first.save()
  154. second = ImageAttachment(
  155. object_type=self.ct_site,
  156. object_id=self.site.pk,
  157. image=self._uploaded_png('action-buttons.png'),
  158. )
  159. second.save()
  160. base_name = f'image-attachments/site_{self.site.pk}_action-buttons.png'
  161. suffixed_name = f'image-attachments/site_{self.site.pk}_action-buttons_sdmmer4.png'
  162. self.assertEqual(first.image.name, base_name)
  163. self.assertEqual(second.image.name, suffixed_name)
  164. self.assertNotEqual(first.image.name, second.image.name)
  165. self.assertEqual(first.filename, 'action-buttons.png')
  166. self.assertEqual(second.filename, 'action-buttons_sdmmer4.png')
  167. self.assertCountEqual(storage.files.keys(), {base_name, suffixed_name})
  168. def test_save_populates_image_size_on_create(self):
  169. """
  170. save() populates image_size from the uploaded file on creation.
  171. """
  172. storage = OverwriteStyleMemoryStorage()
  173. field = ImageAttachment._meta.get_field('image')
  174. with patch.object(field, 'storage', storage):
  175. ia = ImageAttachment(
  176. object_type=self.ct_site,
  177. object_id=self.site.pk,
  178. image=self._uploaded_png('size-on-create.png'),
  179. )
  180. ia.save()
  181. self.assertIsNotNone(ia.image_size)
  182. self.assertEqual(ia.image_size, ia.image.size)
  183. def test_size_property_returns_stored_value_without_storage_access(self):
  184. """
  185. The size property returns the cached image_size rather than the file's actual size. The stub's empty
  186. file reports size 0, so asserting the distinct stored value proves the property used the cached value.
  187. """
  188. ia = self._stub_image_attachment(self.site.pk, 'image-attachments/site_1_no-file.png')
  189. self.assertEqual(ia._read_image_size(), 0) # the stub's empty file genuinely reports 0
  190. ia.image_size = 9999
  191. self.assertEqual(ia.size, 9999)
  192. def test_size_property_falls_back_to_storage_when_unset(self):
  193. """
  194. For legacy rows where image_size is NULL, the size property falls back to reading storage
  195. (rather than reporting 0 bytes).
  196. """
  197. storage = OverwriteStyleMemoryStorage()
  198. field = ImageAttachment._meta.get_field('image')
  199. with patch.object(field, 'storage', storage):
  200. ia = ImageAttachment(
  201. object_type=self.ct_site,
  202. object_id=self.site.pk,
  203. image=self._uploaded_png('fallback.png'),
  204. )
  205. ia.save()
  206. # Simulate a legacy row that predates the image_size field.
  207. ia.image_size = None
  208. self.assertEqual(ia.size, ia.image.size)
  209. self.assertGreater(ia.size, 0)
  210. def test_save_does_not_clobber_existing_size_on_storage_error(self):
  211. """
  212. When the storage backend raises on a size read (modeled by a real Storage subclass, not a mock),
  213. save() must not overwrite an existing image_size with None.
  214. """
  215. field = ImageAttachment._meta.get_field('image')
  216. # Create a row with a real, readable size.
  217. with patch.object(field, 'storage', OverwriteStyleMemoryStorage()):
  218. ia = ImageAttachment(
  219. object_type=self.ct_site,
  220. object_id=self.site.pk,
  221. image=self._uploaded_png('keep-size.png'),
  222. )
  223. ia.save()
  224. original_size = ia.image_size
  225. self.assertIsNotNone(original_size)
  226. # Reload from the DB so the FieldFile has no cached size and must consult storage (as it would for a
  227. # row loaded fresh in production). With the backend unable to report size, the read fails (returns None),
  228. # and save() must keep the previously-stored value rather than clobbering it with None.
  229. with patch.object(field, 'storage', UnreadableSizeMemoryStorage()):
  230. reloaded = ImageAttachment.objects.get(pk=ia.pk)
  231. self.assertIsNone(reloaded._read_image_size()) # the read genuinely fails (returns None)
  232. # Make the image look replaced by perturbing the cached identity (different name component).
  233. reloaded._orig_image_key = ('image-attachments/site_1_old.png', reloaded.image_height, reloaded.image_width)
  234. reloaded.save()
  235. # In-memory value is preserved, and the persisted value is unchanged.
  236. self.assertEqual(reloaded.image_size, original_size)
  237. self.assertEqual(ImageAttachment.objects.get(pk=ia.pk).image_size, original_size)
  238. def test_save_recomputes_image_size_when_image_replaced(self):
  239. """
  240. Replacing the image on an existing row recomputes image_size (Cable-style change detection).
  241. """
  242. storage = OverwriteStyleMemoryStorage()
  243. field = ImageAttachment._meta.get_field('image')
  244. with patch.object(field, 'storage', storage):
  245. ia = ImageAttachment(
  246. object_type=self.ct_site,
  247. object_id=self.site.pk,
  248. image=self._uploaded_png('original.png'),
  249. )
  250. ia.save()
  251. original_size = ia.image_size
  252. self.assertIsNotNone(original_size)
  253. # Replace the image with a larger file and save again.
  254. larger = SimpleUploadedFile(
  255. name='replacement.png',
  256. content=self._uploaded_png('replacement.png').read() + b'\x00' * 100,
  257. content_type='image/png',
  258. )
  259. ia.image = larger
  260. ia.save()
  261. self.assertEqual(ia.image_size, ia.image.size)
  262. self.assertNotEqual(ia.image_size, original_size)
  263. def test_image_identity_includes_dimensions(self):
  264. """
  265. The change-detection key combines the image name with its dimensions, so a replacement that reuses the
  266. same name but changes dimensions produces a different key (which name alone would not).
  267. """
  268. ia = self._stub_image_attachment(self.site.pk, 'image-attachments/site_1_same.png')
  269. ia.image_height, ia.image_width = 10, 10
  270. key_small = ia._image_identity()
  271. # Same name, different dimensions (as Django would set when a same-named file is replaced).
  272. ia.image_height, ia.image_width = 40, 40
  273. key_large = ia._image_identity()
  274. self.assertEqual(key_small[0], key_large[0]) # name component unchanged
  275. self.assertNotEqual(key_small, key_large) # but the key differs, so save() will recompute
  276. def test_save_recomputes_image_size_when_dimensions_change_under_same_name(self):
  277. """
  278. When the image is replaced by a file with the same stored name but different dimensions, save()
  279. recomputes image_size. Name-only detection would miss this; the dimension component catches it.
  280. Simulates the same-name case by priming the cached identity with the old dimensions.
  281. """
  282. storage = OverwriteStyleMemoryStorage()
  283. field = ImageAttachment._meta.get_field('image')
  284. with patch.object(field, 'storage', storage):
  285. ia = ImageAttachment(
  286. object_type=self.ct_site,
  287. object_id=self.site.pk,
  288. image=self._uploaded_png('same-name.png'),
  289. )
  290. ia.save()
  291. name = ia.image.name
  292. # Force the cached identity to reflect the SAME name but different (old) dimensions, then bump the
  293. # current dimensions to mimic a same-name replacement with a differently-sized image.
  294. ia._orig_image_key = (name, ia.image_height + 5, ia.image_width + 5)
  295. ia.save()
  296. self.assertEqual(ia.image.name, name) # name unchanged
  297. self.assertEqual(ia.image_size, ia.image.size) # size recomputed despite same name
  298. def test_save_without_touching_image_does_not_recompute_or_read_storage(self):
  299. """
  300. Editing an existing row without replacing the image leaves image_size untouched and does not
  301. hit storage. Directly guards against the change-detection comparison misfiring.
  302. """
  303. storage = OverwriteStyleMemoryStorage()
  304. field = ImageAttachment._meta.get_field('image')
  305. with patch.object(field, 'storage', storage):
  306. ia = ImageAttachment(
  307. object_type=self.ct_site,
  308. object_id=self.site.pk,
  309. name='Original',
  310. image=self._uploaded_png('untouched.png'),
  311. )
  312. ia.save()
  313. stored_size = ia.image_size
  314. # Reload from the DB so the cached image identity is set from the persisted value, then edit only the name.
  315. reloaded = ImageAttachment.objects.get(pk=ia.pk)
  316. reloaded.name = 'Renamed'
  317. with patch.object(ImageAttachment, '_read_image_size', side_effect=AssertionError('storage accessed')):
  318. reloaded.save()
  319. self.assertEqual(reloaded.image_size, stored_size)
  320. def test_save_populates_image_size_via_constructor_kwarg(self):
  321. """
  322. The non-UI create path (constructor kwarg / REST / bulk) populates image_size correctly,
  323. confirming change detection behaves when image is passed as a FieldFile.
  324. """
  325. storage = OverwriteStyleMemoryStorage()
  326. field = ImageAttachment._meta.get_field('image')
  327. with patch.object(field, 'storage', storage):
  328. ia = ImageAttachment(
  329. object_type=self.ct_site,
  330. object_id=self.site.pk,
  331. image=self._uploaded_png('kwarg.png'),
  332. )
  333. ia.save()
  334. self.assertIsNotNone(ia.image_size)
  335. self.assertEqual(ia.image_size, ia.image.size)
  336. class TableConfigTestCase(TestCase):
  337. @classmethod
  338. def setUpTestData(cls):
  339. cls.site_ct = ContentType.objects.get_for_model(Site)
  340. cls.table_name = get_table_for_model(Site).__name__
  341. def test_clean_accepts_ordering_none(self):
  342. """clean() must accept ordering=None (field is null=True)."""
  343. tc = TableConfig(
  344. object_type=self.site_ct,
  345. table=self.table_name,
  346. name='No ordering',
  347. columns=['name'],
  348. # ordering left unset (defaults to None)
  349. )
  350. # Must not raise TypeError: 'NoneType' object is not iterable
  351. tc.full_clean()
  352. def test_clean_without_object_type(self):
  353. """full_clean() on an instance missing its object type must raise ValidationError."""
  354. tc = TableConfig(
  355. table=self.table_name,
  356. name='No object type',
  357. columns=['name'],
  358. )
  359. with self.assertRaises(ValidationError):
  360. tc.full_clean()
  361. def test_clean_accepts_columns_none(self):
  362. """full_clean() must report missing columns rather than raise TypeError."""
  363. tc = TableConfig(
  364. object_type=self.site_ct,
  365. table=self.table_name,
  366. name='No columns',
  367. )
  368. with self.assertRaises(ValidationError):
  369. tc.full_clean()
  370. class TagTestCase(TestCase):
  371. def test_default_ordering_weight_then_name_is_set(self):
  372. Tag.objects.create(name='Tag 1', slug='tag-1', weight=3000)
  373. Tag.objects.create(name='Tag 2', slug='tag-2') # Default: 1000
  374. Tag.objects.create(name='Tag 3', slug='tag-3', weight=2000)
  375. Tag.objects.create(name='Tag 4', slug='tag-4', weight=2000)
  376. tags = Tag.objects.all()
  377. self.assertEqual(tags[0].slug, 'tag-2')
  378. self.assertEqual(tags[1].slug, 'tag-3')
  379. self.assertEqual(tags[2].slug, 'tag-4')
  380. self.assertEqual(tags[3].slug, 'tag-1')
  381. def test_tag_related_manager_ordering_weight_then_name(self):
  382. tags = [
  383. Tag.objects.create(name='Tag 1', slug='tag-1', weight=3000),
  384. Tag.objects.create(name='Tag 2', slug='tag-2'), # Default: 1000
  385. Tag.objects.create(name='Tag 3', slug='tag-3', weight=2000),
  386. Tag.objects.create(name='Tag 4', slug='tag-4', weight=2000),
  387. ]
  388. site = Site.objects.create(name='Site 1')
  389. for _tag in tags:
  390. site.tags.add(_tag)
  391. site.save()
  392. site = Site.objects.first()
  393. tags = site.tags.all()
  394. self.assertEqual(tags[0].slug, 'tag-2')
  395. self.assertEqual(tags[1].slug, 'tag-3')
  396. self.assertEqual(tags[2].slug, 'tag-4')
  397. self.assertEqual(tags[3].slug, 'tag-1')
  398. def test_create_tag_unicode(self):
  399. tag = Tag(name='Testing Unicode: 台灣')
  400. tag.save()
  401. self.assertEqual(tag.slug, 'testing-unicode-台灣')
  402. def test_object_type_validation(self):
  403. region = Region.objects.create(name='Region 1', slug='region-1')
  404. sitegroup = SiteGroup.objects.create(name='Site Group 1', slug='site-group-1')
  405. # Create a Tag that can only be applied to Regions
  406. tag = Tag.objects.create(name='Tag 1', slug='tag-1')
  407. tag.object_types.add(ObjectType.objects.get_by_natural_key('dcim', 'region'))
  408. # Apply the Tag to a Region
  409. region.tags.add(tag)
  410. self.assertIn(tag, region.tags.all())
  411. # Apply the Tag to a SiteGroup
  412. with self.assertRaises(AbortRequest):
  413. sitegroup.tags.add(tag)
  414. class ConfigContextTestCase(TestCase):
  415. """
  416. These test cases deal with the weighting, ordering, and deep merge logic of config context data.
  417. It also ensures the various config context querysets are consistent.
  418. """
  419. @classmethod
  420. def setUpTestData(cls):
  421. manufacturer = Manufacturer.objects.create(name='Manufacturer 1', slug='manufacturer-1')
  422. devicetype = DeviceType.objects.create(manufacturer=manufacturer, model='Device Type 1', slug='device-type-1')
  423. role = DeviceRole.objects.create(name='Device Role 1', slug='device-role-1')
  424. region = Region.objects.create(name='Region')
  425. sitegroup = SiteGroup.objects.create(name='Site Group')
  426. site = Site.objects.create(name='Site 1', slug='site-1', region=region, group=sitegroup)
  427. location = Location.objects.create(name='Location 1', slug='location-1', site=site)
  428. Platform.objects.create(name='Platform')
  429. tenantgroup = TenantGroup.objects.create(name='Tenant Group')
  430. Tenant.objects.create(name='Tenant', group=tenantgroup)
  431. Tag.objects.create(name='Tag', slug='tag')
  432. Tag.objects.create(name='Tag2', slug='tag2')
  433. Device.objects.create(
  434. name='Device 1',
  435. device_type=devicetype,
  436. role=role,
  437. site=site,
  438. location=location
  439. )
  440. def test_higher_weight_wins(self):
  441. device = Device.objects.first()
  442. context1 = ConfigContext(
  443. name="context 1",
  444. weight=101,
  445. data={
  446. "a": 123,
  447. "b": 456,
  448. "c": 777
  449. }
  450. )
  451. context2 = ConfigContext(
  452. name="context 2",
  453. weight=100,
  454. data={
  455. "a": 123,
  456. "b": 456,
  457. "c": 789
  458. }
  459. )
  460. ConfigContext.objects.bulk_create([context1, context2])
  461. expected_data = {
  462. "a": 123,
  463. "b": 456,
  464. "c": 777
  465. }
  466. self.assertEqual(device.get_config_context(), expected_data)
  467. def test_name_ordering_after_weight(self):
  468. device = Device.objects.first()
  469. context1 = ConfigContext(
  470. name="context 1",
  471. weight=100,
  472. data={
  473. "a": 123,
  474. "b": 456,
  475. "c": 777
  476. }
  477. )
  478. context2 = ConfigContext(
  479. name="context 2",
  480. weight=100,
  481. data={
  482. "a": 123,
  483. "b": 456,
  484. "c": 789
  485. }
  486. )
  487. ConfigContext.objects.bulk_create([context1, context2])
  488. expected_data = {
  489. "a": 123,
  490. "b": 456,
  491. "c": 789
  492. }
  493. self.assertEqual(device.get_config_context(), expected_data)
  494. def test_schema_validation(self):
  495. """
  496. Check that the JSON schema defined by the assigned profile is enforced.
  497. """
  498. profile = ConfigContextProfile.objects.create(
  499. name="Config context profile 1",
  500. schema={
  501. "properties": {
  502. "foo": {
  503. "type": "string"
  504. }
  505. },
  506. "required": [
  507. "foo"
  508. ]
  509. }
  510. )
  511. with self.assertRaises(ValidationError):
  512. # Missing required attribute
  513. ConfigContext(name="CC1", profile=profile, data={}).clean()
  514. with self.assertRaises(ValidationError):
  515. # Invalid attribute type
  516. ConfigContext(name="CC1", profile=profile, data={"foo": 123}).clean()
  517. ConfigContext(name="CC1", profile=profile, data={"foo": "bar"}).clean()
  518. def test_annotation_same_as_get_for_object(self):
  519. """
  520. This test incorporates features from all of the above tests cases to ensure
  521. the annotate_config_context_data() and get_for_object() queryset methods are the same.
  522. """
  523. device = Device.objects.first()
  524. context1 = ConfigContext(
  525. name="context 1",
  526. weight=101,
  527. data={
  528. "a": 123,
  529. "b": 456,
  530. "c": 777
  531. }
  532. )
  533. context2 = ConfigContext(
  534. name="context 2",
  535. weight=100,
  536. data={
  537. "a": 123,
  538. "b": 456,
  539. "c": 789
  540. }
  541. )
  542. context3 = ConfigContext(
  543. name="context 3",
  544. weight=99,
  545. data={
  546. "d": 1
  547. }
  548. )
  549. context4 = ConfigContext(
  550. name="context 4",
  551. weight=99,
  552. data={
  553. "d": 2
  554. }
  555. )
  556. ConfigContext.objects.bulk_create([context1, context2, context3, context4])
  557. annotated_queryset = Device.objects.filter(name=device.name).annotate_config_context_data()
  558. self.assertEqual(device.get_config_context(), annotated_queryset[0].get_config_context())
  559. def test_annotation_same_as_get_for_object_device_relations(self):
  560. region = Region.objects.first()
  561. sitegroup = SiteGroup.objects.first()
  562. site = Site.objects.first()
  563. location = Location.objects.first()
  564. platform = Platform.objects.first()
  565. tenantgroup = TenantGroup.objects.first()
  566. tenant = Tenant.objects.first()
  567. tag = Tag.objects.first()
  568. region_context = ConfigContext.objects.create(
  569. name="region",
  570. weight=100,
  571. data={
  572. "region": 1
  573. }
  574. )
  575. region_context.regions.add(region)
  576. sitegroup_context = ConfigContext.objects.create(
  577. name="sitegroup",
  578. weight=100,
  579. data={
  580. "sitegroup": 1
  581. }
  582. )
  583. sitegroup_context.site_groups.add(sitegroup)
  584. site_context = ConfigContext.objects.create(
  585. name="site",
  586. weight=100,
  587. data={
  588. "site": 1
  589. }
  590. )
  591. site_context.sites.add(site)
  592. location_context = ConfigContext.objects.create(
  593. name="location",
  594. weight=100,
  595. data={
  596. "location": 1
  597. }
  598. )
  599. location_context.locations.add(location)
  600. platform_context = ConfigContext.objects.create(
  601. name="platform",
  602. weight=100,
  603. data={
  604. "platform": 1
  605. }
  606. )
  607. platform_context.platforms.add(platform)
  608. tenant_group_context = ConfigContext.objects.create(
  609. name="tenant group",
  610. weight=100,
  611. data={
  612. "tenant_group": 1
  613. }
  614. )
  615. tenant_group_context.tenant_groups.add(tenantgroup)
  616. tenant_context = ConfigContext.objects.create(
  617. name="tenant",
  618. weight=100,
  619. data={
  620. "tenant": 1
  621. }
  622. )
  623. tenant_context.tenants.add(tenant)
  624. tag_context = ConfigContext.objects.create(
  625. name="tag",
  626. weight=100,
  627. data={
  628. "tag": 1
  629. }
  630. )
  631. tag_context.tags.add(tag)
  632. device = Device.objects.create(
  633. name="Device 2",
  634. site=site,
  635. location=location,
  636. tenant=tenant,
  637. platform=platform,
  638. role=DeviceRole.objects.first(),
  639. device_type=DeviceType.objects.first()
  640. )
  641. device.tags.add(tag)
  642. annotated_queryset = Device.objects.filter(name=device.name).annotate_config_context_data()
  643. self.assertEqual(device.get_config_context(), annotated_queryset[0].get_config_context())
  644. def test_annotation_same_as_get_for_object_virtualmachine_relations(self):
  645. region = Region.objects.first()
  646. sitegroup = SiteGroup.objects.first()
  647. site = Site.objects.first()
  648. platform = Platform.objects.first()
  649. tenantgroup = TenantGroup.objects.first()
  650. tenant = Tenant.objects.first()
  651. tag = Tag.objects.first()
  652. cluster_type = ClusterType.objects.create(name="Cluster Type")
  653. cluster_group = ClusterGroup.objects.create(name="Cluster Group")
  654. cluster = Cluster.objects.create(
  655. name="Cluster",
  656. group=cluster_group,
  657. type=cluster_type,
  658. scope=site,
  659. )
  660. region_context = ConfigContext.objects.create(
  661. name="region",
  662. weight=100,
  663. data={"region": 1}
  664. )
  665. region_context.regions.add(region)
  666. sitegroup_context = ConfigContext.objects.create(
  667. name="sitegroup",
  668. weight=100,
  669. data={"sitegroup": 1}
  670. )
  671. sitegroup_context.site_groups.add(sitegroup)
  672. site_context = ConfigContext.objects.create(
  673. name="site",
  674. weight=100,
  675. data={"site": 1}
  676. )
  677. site_context.sites.add(site)
  678. platform_context = ConfigContext.objects.create(
  679. name="platform",
  680. weight=100,
  681. data={"platform": 1}
  682. )
  683. platform_context.platforms.add(platform)
  684. tenant_group_context = ConfigContext.objects.create(
  685. name="tenant group",
  686. weight=100,
  687. data={"tenant_group": 1}
  688. )
  689. tenant_group_context.tenant_groups.add(tenantgroup)
  690. tenant_context = ConfigContext.objects.create(
  691. name="tenant",
  692. weight=100,
  693. data={"tenant": 1}
  694. )
  695. tenant_context.tenants.add(tenant)
  696. tag_context = ConfigContext.objects.create(
  697. name="tag",
  698. weight=100,
  699. data={"tag": 1}
  700. )
  701. tag_context.tags.add(tag)
  702. cluster_type_context = ConfigContext.objects.create(
  703. name="cluster type",
  704. weight=100,
  705. data={"cluster_type": 1}
  706. )
  707. cluster_type_context.cluster_types.add(cluster_type)
  708. cluster_group_context = ConfigContext.objects.create(
  709. name="cluster group",
  710. weight=100,
  711. data={"cluster_group": 1}
  712. )
  713. cluster_group_context.cluster_groups.add(cluster_group)
  714. cluster_context = ConfigContext.objects.create(
  715. name="cluster",
  716. weight=100,
  717. data={"cluster": 1}
  718. )
  719. cluster_context.clusters.add(cluster)
  720. virtual_machine = VirtualMachine.objects.create(
  721. name="VM 1",
  722. cluster=cluster,
  723. tenant=tenant,
  724. platform=platform,
  725. role=DeviceRole.objects.first()
  726. )
  727. virtual_machine.tags.add(tag)
  728. annotated_queryset = VirtualMachine.objects.filter(name=virtual_machine.name).annotate_config_context_data()
  729. self.assertEqual(virtual_machine.get_config_context(), annotated_queryset[0].get_config_context())
  730. def test_virtualmachine_site_context(self):
  731. """
  732. Check that config context associated with a site applies to a VM whether the VM is assigned
  733. directly to that site or via its cluster.
  734. """
  735. site = Site.objects.first()
  736. cluster_type = ClusterType.objects.create(name="Cluster Type")
  737. cluster = Cluster.objects.create(name="Cluster", type=cluster_type, scope=site)
  738. vm_role = DeviceRole.objects.first()
  739. # Create a ConfigContext associated with the site
  740. context = ConfigContext.objects.create(
  741. name="context1",
  742. weight=100,
  743. data={"foo": True}
  744. )
  745. context.sites.add(site)
  746. # Create one VM assigned directly to the site, and one assigned via the cluster
  747. vm1 = VirtualMachine.objects.create(name="VM 1", site=site, role=vm_role)
  748. vm2 = VirtualMachine.objects.create(name="VM 2", cluster=cluster, role=vm_role)
  749. # Check that their individually rendered config contexts are identical
  750. self.assertEqual(
  751. vm1.get_config_context(),
  752. vm2.get_config_context()
  753. )
  754. # Check that their annotated config contexts are identical
  755. vms = VirtualMachine.objects.filter(pk__in=(vm1.pk, vm2.pk)).annotate_config_context_data()
  756. self.assertEqual(
  757. vms[0].get_config_context(),
  758. vms[1].get_config_context()
  759. )
  760. def test_valid_local_context_data(self):
  761. device = Device.objects.first()
  762. device.local_context_data = None
  763. device.clean()
  764. device.local_context_data = {"foo": "bar"}
  765. device.clean()
  766. def test_invalid_local_context_data(self):
  767. device = Device.objects.first()
  768. device.local_context_data = ""
  769. with self.assertRaises(ValidationError):
  770. device.clean()
  771. device.local_context_data = 0
  772. with self.assertRaises(ValidationError):
  773. device.clean()
  774. device.local_context_data = False
  775. with self.assertRaises(ValidationError):
  776. device.clean()
  777. device.local_context_data = 'foo'
  778. with self.assertRaises(ValidationError):
  779. device.clean()
  780. @tag('regression')
  781. def test_multiple_tags_return_distinct_objects(self):
  782. """
  783. Tagged items use a generic relationship, which results in duplicate rows being returned when queried.
  784. This is combated by appending distinct() to the config context querysets. This test creates a config
  785. context assigned to two tags and ensures objects related to those same two tags result in only a single
  786. config context record being returned.
  787. See https://github.com/netbox-community/netbox/issues/5314
  788. """
  789. site = Site.objects.first()
  790. platform = Platform.objects.first()
  791. tenant = Tenant.objects.first()
  792. tags = Tag.objects.all()
  793. tag_context = ConfigContext.objects.create(
  794. name="tag",
  795. weight=100,
  796. data={
  797. "tag": 1
  798. }
  799. )
  800. tag_context.tags.set(tags)
  801. device = Device.objects.create(
  802. name="Device 3",
  803. site=site,
  804. tenant=tenant,
  805. platform=platform,
  806. role=DeviceRole.objects.first(),
  807. device_type=DeviceType.objects.first()
  808. )
  809. device.tags.set(tags)
  810. annotated_queryset = Device.objects.filter(name=device.name).annotate_config_context_data()
  811. self.assertEqual(ConfigContext.objects.get_for_object(device).count(), 1)
  812. self.assertEqual(device.get_config_context(), annotated_queryset[0].get_config_context())
  813. @tag('regression')
  814. def test_multiple_tags_return_distinct_objects_with_separate_config_contexts(self):
  815. """
  816. Tagged items use a generic relationship, which results in duplicate rows being returned when queried.
  817. This is combated by appending distinct() to the config context querysets. This test creates a config
  818. context assigned to two tags and ensures objects related to those same two tags result in only a single
  819. config context record being returned.
  820. This test case is separate from the above in that it deals with multiple config context objects in play.
  821. See https://github.com/netbox-community/netbox/issues/5387
  822. """
  823. site = Site.objects.first()
  824. platform = Platform.objects.first()
  825. tenant = Tenant.objects.first()
  826. tag1, tag2 = list(Tag.objects.all())
  827. tag_context_1 = ConfigContext.objects.create(
  828. name="tag-1",
  829. weight=100,
  830. data={
  831. "tag": 1
  832. }
  833. )
  834. tag_context_1.tags.add(tag1)
  835. tag_context_2 = ConfigContext.objects.create(
  836. name="tag-2",
  837. weight=100,
  838. data={
  839. "tag": 1
  840. }
  841. )
  842. tag_context_2.tags.add(tag2)
  843. device = Device.objects.create(
  844. name="Device 3",
  845. site=site,
  846. tenant=tenant,
  847. platform=platform,
  848. role=DeviceRole.objects.first(),
  849. device_type=DeviceType.objects.first()
  850. )
  851. device.tags.set([tag1, tag2])
  852. annotated_queryset = Device.objects.filter(name=device.name).annotate_config_context_data()
  853. self.assertEqual(ConfigContext.objects.get_for_object(device).count(), 2)
  854. self.assertEqual(device.get_config_context(), annotated_queryset[0].get_config_context())
  855. @tag('performance', 'regression')
  856. def test_config_context_annotation_query_optimization(self):
  857. """
  858. Regression test for issue #20327: Ensure config context annotation
  859. doesn't use expensive DISTINCT on main query.
  860. Verifies that DISTINCT is only used in tag subquery where needed,
  861. not on the main device query which is expensive for large datasets.
  862. """
  863. device = Device.objects.first()
  864. queryset = Device.objects.filter(pk=device.pk).annotate_config_context_data()
  865. # Main device query should NOT use DISTINCT
  866. self.assertFalse(queryset.query.distinct)
  867. # Check that tag subqueries DO use DISTINCT by inspecting the annotation
  868. config_annotation = queryset.query.annotations.get('config_context_data')
  869. self.assertIsNotNone(config_annotation)
  870. def find_tag_subqueries(where_node):
  871. """Find subqueries in WHERE clause that relate to tag filtering"""
  872. subqueries = []
  873. def traverse(node):
  874. if hasattr(node, 'children'):
  875. for child in node.children:
  876. try:
  877. # In Django 6.0+, rhs is a Query directly; older Django wraps it in Subquery
  878. rhs_query = getattr(child.rhs, 'query', child.rhs)
  879. if rhs_query.model is TaggedItem:
  880. subqueries.append(rhs_query)
  881. except AttributeError:
  882. traverse(child)
  883. traverse(where_node)
  884. return subqueries
  885. # In Django 6.0+, the annotation is a Query directly; older Django wraps it in Subquery
  886. annotation_query = getattr(config_annotation, 'query', config_annotation)
  887. # Find subqueries in the WHERE clause that should have DISTINCT
  888. tag_subqueries = find_tag_subqueries(annotation_query.where)
  889. distinct_subqueries = [sq for sq in tag_subqueries if sq.distinct]
  890. # Verify we found at least one DISTINCT subquery for tags
  891. self.assertEqual(len(distinct_subqueries), 1)
  892. self.assertTrue(distinct_subqueries[0].distinct)
  893. class ConfigTemplateTestCase(TestCase):
  894. """
  895. TODO: These test cases deal with the weighting, ordering, and deep merge logic of config context data.
  896. """
  897. MAIN_TEMPLATE = """
  898. {%- include 'base.j2' %}
  899. """.strip()
  900. BASE_TEMPLATE = """
  901. Hi
  902. """.strip()
  903. @classmethod
  904. def _create_template_file(cls, templates_dir, file_name, content):
  905. template_file_name = file_name
  906. if not template_file_name.endswith('j2'):
  907. template_file_name += '.j2'
  908. temp_file_path = templates_dir / template_file_name
  909. with open(temp_file_path, 'w') as f:
  910. f.write(content)
  911. @classmethod
  912. def setUpTestData(cls):
  913. temp_dir = tempfile.TemporaryDirectory()
  914. templates_dir = Path(temp_dir.name) / "templates"
  915. templates_dir.mkdir(parents=True, exist_ok=True)
  916. cls._create_template_file(templates_dir, 'base.j2', cls.BASE_TEMPLATE)
  917. cls._create_template_file(templates_dir, 'main.j2', cls.MAIN_TEMPLATE)
  918. data_source = DataSource(
  919. name="Test DataSource",
  920. type="local",
  921. source_url=str(templates_dir),
  922. )
  923. data_source.save()
  924. data_source.sync()
  925. base_config_template = ConfigTemplate(
  926. name="BaseTemplate",
  927. data_file=data_source.datafiles.filter(path__endswith='base.j2').first()
  928. )
  929. base_config_template.clean()
  930. base_config_template.save()
  931. cls.base_config_template = base_config_template
  932. main_config_template = ConfigTemplate(
  933. name="MainTemplate",
  934. data_file=data_source.datafiles.filter(path__endswith='main.j2').first()
  935. )
  936. main_config_template.clean()
  937. main_config_template.save()
  938. cls.main_config_template = main_config_template
  939. @tag('regression')
  940. def test_config_template_with_data_source(self):
  941. self.assertEqual(self.BASE_TEMPLATE, self.base_config_template.render({}))
  942. @tag('regression')
  943. def test_config_template_with_data_source_nested_templates(self):
  944. self.assertEqual(self.BASE_TEMPLATE, self.main_config_template.render({}))
  945. @tag('regression')
  946. def test_autosyncrecord_cleanup_on_detach(self):
  947. """Test that AutoSyncRecord is deleted when detaching from DataSource."""
  948. with tempfile.TemporaryDirectory() as temp_dir:
  949. templates_dir = Path(temp_dir) / "templates"
  950. templates_dir.mkdir(parents=True, exist_ok=True)
  951. self._create_template_file(templates_dir, 'test.j2', 'Test content')
  952. data_source = DataSource(
  953. name="Test DataSource for Detach",
  954. type="local",
  955. source_url=str(templates_dir),
  956. )
  957. data_source.save()
  958. data_source.sync()
  959. data_file = data_source.datafiles.filter(path__endswith='test.j2').first()
  960. # Create a ConfigTemplate with data_file and auto_sync_enabled
  961. config_template = ConfigTemplate(
  962. name="TestTemplateForDetach",
  963. data_file=data_file,
  964. auto_sync_enabled=True
  965. )
  966. config_template.clean()
  967. config_template.save()
  968. # Verify AutoSyncRecord was created
  969. object_type = ObjectType.objects.get_for_model(ConfigTemplate)
  970. autosync_records = AutoSyncRecord.objects.filter(
  971. object_type=object_type,
  972. object_id=config_template.pk
  973. )
  974. self.assertEqual(autosync_records.count(), 1, "AutoSyncRecord should be created")
  975. # Detach from DataSource
  976. config_template.data_file = None
  977. config_template.data_source = None
  978. config_template.auto_sync_enabled = False
  979. config_template.clean()
  980. config_template.save()
  981. # Verify AutoSyncRecord was deleted
  982. autosync_records = AutoSyncRecord.objects.filter(
  983. object_type=object_type,
  984. object_id=config_template.pk
  985. )
  986. self.assertEqual(autosync_records.count(), 0, "AutoSyncRecord should be deleted after detaching")
  987. class ConfigTemplateDebugTestCase(TestCase):
  988. """
  989. Tests for the ConfigTemplate debug field and its effect on template rendering error output.
  990. """
  991. def _make_template(self, template_code, debug=False):
  992. t = ConfigTemplate(
  993. name=f"DebugTestTemplate-{debug}",
  994. template_code=template_code,
  995. debug=debug,
  996. )
  997. t.save()
  998. return t
  999. def test_debug_default_is_false(self):
  1000. t = ConfigTemplate(name="t", template_code="hello")
  1001. self.assertFalse(t.debug)
  1002. def test_template_error_non_debug_no_traceback(self):
  1003. """In non-debug mode, a TemplateError raises with no traceback exposure."""
  1004. t = self._make_template("{{ unclosed", debug=False)
  1005. with self.assertRaises(TemplateError):
  1006. t.render({})
  1007. def test_template_error_debug_mode_raises(self):
  1008. """In debug mode, a TemplateError still raises (callers handle display)."""
  1009. t = self._make_template("{{ unclosed", debug=True)
  1010. with self.assertRaises(TemplateError):
  1011. t.render({})
  1012. def test_render_jinja2_debug_extension_enabled(self):
  1013. """When debug=True, the Jinja2 debug extension is loaded in the environment."""
  1014. # The {% debug %} tag is only available when the debug extension is loaded.
  1015. output = render_jinja2("{% debug %}", {}, debug=True)
  1016. self.assertIsInstance(output, str)
  1017. def test_render_jinja2_debug_extension_not_loaded_by_default(self):
  1018. """When debug=False, the {% debug %} tag is not available."""
  1019. with self.assertRaises(TemplateSyntaxError):
  1020. render_jinja2("{% debug %}", {}, debug=False)
  1021. class JinjaEnvFilterTestCase(TestCase):
  1022. """
  1023. Tests for the env() Jinja2 filter and the JINJA_ENVIRONMENT_PARAMS configuration parameter.
  1024. """
  1025. def test_env_filter_returns_value_for_matching_name(self):
  1026. with patch.dict('os.environ', {'NETBOX_TEST_TOKEN': 'secret'}, clear=False), \
  1027. self.settings(JINJA_ENVIRONMENT_PARAMS=['NETBOX_TEST_TOKEN']):
  1028. self.assertEqual(env_filter('NETBOX_TEST_TOKEN'), 'secret')
  1029. def test_env_filter_returns_none_for_unmatched_name(self):
  1030. with patch.dict('os.environ', {'NETBOX_OTHER_TOKEN': 'secret'}, clear=False), \
  1031. self.settings(JINJA_ENVIRONMENT_PARAMS=['NETBOX_TEST_TOKEN']):
  1032. self.assertIsNone(env_filter('NETBOX_OTHER_TOKEN'))
  1033. def test_env_filter_wildcard_match(self):
  1034. with patch.dict('os.environ', {'NETBOX_TEST_TOKEN_1': 'one', 'NETBOX_TEST_TOKEN_2': 'two'}, clear=False), \
  1035. self.settings(JINJA_ENVIRONMENT_PARAMS=['NETBOX_TEST_TOKEN_*']):
  1036. self.assertEqual(env_filter('NETBOX_TEST_TOKEN_1'), 'one')
  1037. self.assertEqual(env_filter('NETBOX_TEST_TOKEN_2'), 'two')
  1038. def test_env_filter_returns_none_for_missing_env_var(self):
  1039. with self.settings(JINJA_ENVIRONMENT_PARAMS=['NETBOX_MISSING_VAR']):
  1040. self.assertIsNone(env_filter('NETBOX_MISSING_VAR'))
  1041. def test_env_filter_empty_whitelist_returns_none(self):
  1042. with patch.dict('os.environ', {'NETBOX_TEST_TOKEN': 'secret'}, clear=False), \
  1043. self.settings(JINJA_ENVIRONMENT_PARAMS=[]):
  1044. self.assertIsNone(env_filter('NETBOX_TEST_TOKEN'))
  1045. def test_env_filter_registered_by_default(self):
  1046. with patch.dict('os.environ', {'NETBOX_TEST_TOKEN': 'secret'}, clear=False), \
  1047. self.settings(JINJA_ENVIRONMENT_PARAMS=['NETBOX_TEST_TOKEN']):
  1048. output = render_jinja2("{{ 'NETBOX_TEST_TOKEN' | env }}", {})
  1049. self.assertEqual(output, 'secret')
  1050. def test_user_defined_filter_overrides_default(self):
  1051. with self.settings(JINJA_FILTERS={'env': lambda name: 'overridden'}):
  1052. output = render_jinja2("{{ 'NETBOX_TEST_TOKEN' | env }}", {})
  1053. self.assertEqual(output, 'overridden')
  1054. class ExportTemplateContextTestCase(TestCase):
  1055. """
  1056. Tests for ExportTemplate.get_context() including public model population.
  1057. """
  1058. def test_get_context_includes_public_models(self):
  1059. et = ExportTemplate(name='test', template_code='test')
  1060. ctx = et.get_context()
  1061. self.assertIs(ctx['dcim']['Site'], Site)
  1062. self.assertIs(ctx['dcim']['Device'], Device)
  1063. def test_get_context_includes_queryset(self):
  1064. et = ExportTemplate(name='test', template_code='test')
  1065. qs = Site.objects.all()
  1066. ctx = et.get_context(queryset=qs)
  1067. self.assertIs(ctx['queryset'], qs)
  1068. def test_get_context_applies_extra_context(self):
  1069. et = ExportTemplate(name='test', template_code='test')
  1070. ctx = et.get_context(context={'custom_key': 'custom_value'})
  1071. self.assertEqual(ctx['custom_key'], 'custom_value')
  1072. self.assertIs(ctx['dcim']['Site'], Site)
  1073. def test_config_template_get_context_includes_public_models(self):
  1074. ct = ConfigTemplate(name='test', template_code='test')
  1075. ctx = ct.get_context()
  1076. self.assertIs(ctx['dcim']['Site'], Site)
  1077. def finalize_none_to_dash(value):
  1078. """
  1079. Module-level helper used by RenderTemplateMixinRenderTestCase.test_environment_params_finalize_path_import.
  1080. Exported so it can be referenced by dotted path from a Jinja environment_params value.
  1081. """
  1082. return '-' if value is None else value
  1083. class RenderTemplateMixinRenderTestCase(TestCase):
  1084. """
  1085. Tests for RenderTemplateMixin.render() and get_environment_params(), exercised via ConfigTemplate.
  1086. """
  1087. def test_render_basic_context(self):
  1088. t = ConfigTemplate(name='basic', template_code='Hello {{ name }}')
  1089. self.assertEqual(t.render({'name': 'world'}), 'Hello world')
  1090. def test_render_normalizes_crlf(self):
  1091. t = ConfigTemplate(name='crlf', template_code='line1\r\nline2\r\nline3')
  1092. self.assertEqual(t.render({}), 'line1\nline2\nline3')
  1093. def test_render_passes_environment_params(self):
  1094. # With trim_blocks + lstrip_blocks, block tags don't emit their surrounding whitespace.
  1095. template_code = '{% if x %}\n {% if y %}\n VALUE\n {% endif %}\n{% endif %}'
  1096. plain = ConfigTemplate(name='plain', template_code=template_code)
  1097. trimmed = ConfigTemplate(
  1098. name='trimmed',
  1099. template_code=template_code,
  1100. environment_params={'trim_blocks': True, 'lstrip_blocks': True},
  1101. )
  1102. ctx = {'x': True, 'y': True}
  1103. self.assertNotEqual(plain.render(ctx), trimmed.render(ctx))
  1104. self.assertEqual(trimmed.render(ctx).strip(), 'VALUE')
  1105. def test_environment_params_undefined_path_import(self):
  1106. # Default Undefined renders nothing for a missing variable.
  1107. default = ConfigTemplate(name='default', template_code='{{ missing }}')
  1108. self.assertEqual(default.render({}), '')
  1109. # StrictUndefined (resolved from its dotted path) raises on access.
  1110. strict = ConfigTemplate(
  1111. name='strict',
  1112. template_code='{{ missing }}',
  1113. environment_params={'undefined': 'jinja2.StrictUndefined'},
  1114. )
  1115. with self.assertRaises(UndefinedError):
  1116. strict.render({})
  1117. def test_environment_params_finalize_legacy_resolution(self):
  1118. """
  1119. Existing finalize values continue to resolve via import_string() as a
  1120. legacy carve-out (CVE-2026-29514). New use is blocked by clean().
  1121. """
  1122. t = ConfigTemplate(
  1123. name='finalize',
  1124. template_code='{{ v }}',
  1125. environment_params={'finalize': 'extras.tests.test_models.finalize_none_to_dash'},
  1126. )
  1127. self.assertEqual(t.render({'v': None}), '-')
  1128. self.assertEqual(t.render({'v': 'abc'}), 'abc')
  1129. def test_get_environment_params_handles_none(self):
  1130. # The environment_params field may be cleared; ensure the mixin returns a dict (not None).
  1131. t = ConfigTemplate(name='empty', template_code='ok', environment_params=None)
  1132. self.assertEqual(t.get_environment_params(), {})
  1133. def test_get_environment_params_resolves_path_imports(self):
  1134. t = ConfigTemplate(
  1135. name='resolve',
  1136. template_code='ok',
  1137. environment_params={'undefined': 'jinja2.StrictUndefined', 'trim_blocks': True},
  1138. )
  1139. params = t.get_environment_params()
  1140. self.assertIs(params['undefined'], StrictUndefined)
  1141. self.assertIs(params['trim_blocks'], True)
  1142. def test_get_environment_params_does_not_mutate_field(self):
  1143. # Resolving path imports must not replace the string values stored on the model field.
  1144. t = ConfigTemplate(
  1145. name='no-mutate',
  1146. template_code='ok',
  1147. environment_params={'undefined': 'jinja2.StrictUndefined'},
  1148. )
  1149. t.get_environment_params()
  1150. t.get_environment_params()
  1151. self.assertEqual(t.environment_params, {'undefined': 'jinja2.StrictUndefined'})
  1152. class RenderTemplateMixinResponseTestCase(TestCase):
  1153. """
  1154. Tests for RenderTemplateMixin.render_to_response() HTTP behavior.
  1155. """
  1156. def test_response_default_mime_type(self):
  1157. t = ConfigTemplate(name='t', template_code='ok')
  1158. response = t.render_to_response({})
  1159. self.assertEqual(response.status_code, 200)
  1160. self.assertEqual(response['Content-Type'], DEFAULT_MIME_TYPE)
  1161. def test_response_custom_mime_type(self):
  1162. t = ConfigTemplate(name='t', template_code='{}', mime_type='application/json')
  1163. response = t.render_to_response({})
  1164. self.assertEqual(response['Content-Type'], 'application/json')
  1165. def test_response_attachment_with_file_name(self):
  1166. t = ConfigTemplate(
  1167. name='t', template_code='ok', file_name='router1', file_extension='cfg', as_attachment=True,
  1168. )
  1169. response = t.render_to_response({})
  1170. self.assertEqual(response['Content-Disposition'], 'attachment; filename="router1.cfg"')
  1171. def test_response_attachment_filename_from_queryset(self):
  1172. Site.objects.create(name='Site 1', slug='site-1')
  1173. t = ExportTemplate(
  1174. name='t',
  1175. template_code='{% for obj in queryset %}{{ obj.name }}{% endfor %}',
  1176. file_extension='txt',
  1177. as_attachment=True,
  1178. )
  1179. response = t.render_to_response(queryset=Site.objects.all())
  1180. self.assertEqual(response['Content-Disposition'], 'attachment; filename="netbox_sites.txt"')
  1181. def test_response_attachment_filename_from_device_context(self):
  1182. t = ConfigTemplate(name='t', template_code='ok', as_attachment=True)
  1183. device = SimpleNamespace(name='router1')
  1184. response = t.render_to_response(context={'device': device})
  1185. self.assertEqual(response['Content-Disposition'], 'attachment; filename="router1"')
  1186. def test_response_attachment_fallback_filename(self):
  1187. # No file_name, no queryset, no device/vm key in context: filename falls back to "output".
  1188. t = ConfigTemplate(name='t', template_code='ok', as_attachment=True)
  1189. response = t.render_to_response({})
  1190. self.assertEqual(response['Content-Disposition'], 'attachment; filename="output"')
  1191. def test_response_as_attachment_false_omits_disposition(self):
  1192. t = ConfigTemplate(name='t', template_code='ok', file_name='router1', as_attachment=False)
  1193. response = t.render_to_response({})
  1194. self.assertNotIn('Content-Disposition', response)
  1195. def test_response_body_matches_render(self):
  1196. t = ConfigTemplate(name='t', template_code='Hello {{ name }}')
  1197. rendered = t.render({'name': 'world'})
  1198. response = t.render_to_response({'name': 'world'})
  1199. self.assertEqual(response.content.decode(), rendered)
  1200. class ExportTemplateRenderTestCase(TestCase):
  1201. """
  1202. Tests for ExportTemplate.render() with a queryset bound into the template context.
  1203. """
  1204. @classmethod
  1205. def setUpTestData(cls):
  1206. Site.objects.bulk_create([
  1207. Site(name='Site A', slug='site-a'),
  1208. Site(name='Site B', slug='site-b'),
  1209. Site(name='Site C', slug='site-c'),
  1210. ])
  1211. def test_render_iterates_queryset(self):
  1212. t = ExportTemplate(
  1213. name='sites',
  1214. template_code='{% for obj in queryset %}{{ obj.name }}\n{% endfor %}',
  1215. )
  1216. queryset = Site.objects.order_by('name')
  1217. output = t.render(queryset=queryset)
  1218. self.assertEqual(output, 'Site A\nSite B\nSite C\n')
  1219. def test_render_to_response_for_queryset(self):
  1220. t = ExportTemplate(
  1221. name='sites',
  1222. template_code='{% for obj in queryset %}{{ obj.name }}\n{% endfor %}',
  1223. file_extension='txt',
  1224. )
  1225. response = t.render_to_response(queryset=Site.objects.order_by('name'))
  1226. self.assertEqual(response.status_code, 200)
  1227. self.assertEqual(response['Content-Type'], DEFAULT_MIME_TYPE)
  1228. self.assertEqual(response['Content-Disposition'], 'attachment; filename="netbox_sites.txt"')
  1229. self.assertEqual(response.content.decode(), 'Site A\nSite B\nSite C\n')
  1230. class EventRuleTestCase(TestCase):
  1231. def test_action_data_clean_accepts_dict(self):
  1232. """
  1233. clean() should accept a JSON object (or null) as action_data.
  1234. """
  1235. for value in ({'key': 'value'}, None):
  1236. rule = EventRule(name='test', event_types=[OBJECT_CREATED], action_data=value)
  1237. rule.clean()
  1238. def test_action_data_clean_rejects_non_dict(self):
  1239. """
  1240. clean() should reject action_data that is valid JSON but not an object (#21989).
  1241. """
  1242. for value in ('test', 42, [1, 2, 3], True):
  1243. rule = EventRule(name='test', event_types=[OBJECT_CREATED], action_data=value)
  1244. with self.assertRaises(ValidationError) as cm:
  1245. rule.clean()
  1246. self.assertIn('action_data', cm.exception.message_dict)
  1247. class JinjaEnvironmentParamsCleanTestCase(TestCase):
  1248. """Tests for RenderTemplateMixin.clean() validation of environment_params."""
  1249. def _make_template(self, environment_params):
  1250. return ConfigTemplate(
  1251. name='test',
  1252. template_code='{{ "test" }}',
  1253. environment_params=environment_params,
  1254. )
  1255. def test_allowed_scalar_params_pass(self):
  1256. template = self._make_template({'trim_blocks': True, 'lstrip_blocks': True})
  1257. template.clean()
  1258. def test_autoescape_boolean_passes(self):
  1259. template = self._make_template({'autoescape': True})
  1260. template.clean()
  1261. def test_valid_undefined_passes(self):
  1262. for value in (
  1263. 'jinja2.Undefined',
  1264. 'jinja2.ChainableUndefined',
  1265. 'jinja2.DebugUndefined',
  1266. 'jinja2.StrictUndefined',
  1267. ):
  1268. template = self._make_template({'undefined': value})
  1269. template.clean()
  1270. def test_invalid_undefined_rejected(self):
  1271. template = self._make_template({'undefined': 'subprocess.getoutput'})
  1272. with self.assertRaises(ValidationError) as cm:
  1273. template.clean()
  1274. self.assertIn('environment_params', cm.exception.message_dict)
  1275. def test_unknown_key_rejected(self):
  1276. template = self._make_template({'extensions': ['os']})
  1277. with self.assertRaises(ValidationError) as cm:
  1278. template.clean()
  1279. self.assertIn('environment_params', cm.exception.message_dict)
  1280. def test_finalize_blocked_from_new_use(self):
  1281. template = self._make_template({'finalize': 'subprocess.getoutput'})
  1282. with self.assertRaises(ValidationError) as cm:
  1283. template.clean()
  1284. self.assertIn('environment_params', cm.exception.message_dict)
  1285. def test_empty_params_pass(self):
  1286. template = self._make_template({})
  1287. template.clean()
  1288. def test_none_params_pass(self):
  1289. template = self._make_template(None)
  1290. template.clean()
  1291. def test_exporttemplate_clean_rejects_unknown_key(self):
  1292. """MRO smoke test: ExportTemplate.clean() reaches RenderTemplateMixin.clean()."""
  1293. obj = ExportTemplate(
  1294. name='test',
  1295. template_code='{{ "test" }}',
  1296. environment_params={'loader': 'some.loader'},
  1297. )
  1298. with self.assertRaises(ValidationError) as cm:
  1299. obj.clean()
  1300. self.assertIn('environment_params', cm.exception.message_dict)
  1301. def test_configtemplate_clean_rejects_finalize(self):
  1302. """MRO smoke test: ConfigTemplate.clean() reaches RenderTemplateMixin.clean()."""
  1303. obj = ConfigTemplate(
  1304. name='test',
  1305. template_code='{{ "test" }}',
  1306. environment_params={'finalize': 'subprocess.getoutput'},
  1307. )
  1308. with self.assertRaises(ValidationError) as cm:
  1309. obj.clean()
  1310. self.assertIn('environment_params', cm.exception.message_dict)
  1311. class JinjaEnvironmentParamsFilterTestCase(TestCase):
  1312. """Tests for RenderTemplateMixin._filter_environment_params()."""
  1313. def test_allowed_keys_pass_through(self):
  1314. params = {'trim_blocks': True, 'autoescape': False}
  1315. result = RenderTemplateMixin._filter_environment_params(params)
  1316. self.assertEqual(result, params)
  1317. def test_unknown_keys_stripped(self):
  1318. params = {'extensions': ['os'], 'loader': 'x', 'trim_blocks': True}
  1319. result = RenderTemplateMixin._filter_environment_params(params)
  1320. self.assertEqual(result, {'trim_blocks': True})
  1321. def test_finalize_preserved_as_legacy(self):
  1322. params = {'finalize': 'some.module.func', 'trim_blocks': True}
  1323. result = RenderTemplateMixin._filter_environment_params(params)
  1324. self.assertEqual(result, params)
  1325. def test_empty_params(self):
  1326. self.assertEqual(RenderTemplateMixin._filter_environment_params({}), {})
  1327. class JinjaEnvironmentParamsResolveTestCase(TestCase):
  1328. """Tests for RenderTemplateMixin._resolve_mapped_params()."""
  1329. def test_undefined_resolved_to_class(self):
  1330. params = {'undefined': 'jinja2.StrictUndefined'}
  1331. result = RenderTemplateMixin._resolve_mapped_params(params)
  1332. self.assertIs(result['undefined'], StrictUndefined)
  1333. def test_unrecognized_undefined_value_passed_through(self):
  1334. params = {'undefined': 'not.a.real.class'}
  1335. result = RenderTemplateMixin._resolve_mapped_params(params)
  1336. self.assertEqual(result['undefined'], 'not.a.real.class')
  1337. def test_scalar_params_passed_through(self):
  1338. params = {'trim_blocks': True, 'autoescape': False}
  1339. result = RenderTemplateMixin._resolve_mapped_params(params)
  1340. self.assertEqual(result, params)
  1341. def test_empty_params(self):
  1342. self.assertEqual(RenderTemplateMixin._resolve_mapped_params({}), {})
  1343. class JinjaEnvironmentParamsFinalizeTestCase(TestCase):
  1344. """Tests for RenderTemplateMixin._resolve_finalize() legacy carve-out."""
  1345. def test_finalize_string_resolved_via_import_string(self):
  1346. params = {'finalize': 'extras.tests.test_models.finalize_none_to_dash'}
  1347. result = RenderTemplateMixin._resolve_finalize(params)
  1348. self.assertIs(result['finalize'], finalize_none_to_dash)
  1349. def test_finalize_non_string_passed_through(self):
  1350. params = {'finalize': 42}
  1351. result = RenderTemplateMixin._resolve_finalize(params)
  1352. self.assertEqual(result['finalize'], 42)
  1353. def test_no_finalize_key_unchanged(self):
  1354. params = {'trim_blocks': True}
  1355. result = RenderTemplateMixin._resolve_finalize(params)
  1356. self.assertEqual(result, {'trim_blocks': True})
  1357. def test_invalid_import_path_raises_import_error(self):
  1358. params = {'finalize': 'nonexistent.module.func'}
  1359. with self.assertRaises(ImportError):
  1360. RenderTemplateMixin._resolve_finalize(params)
  1361. def test_empty_params(self):
  1362. self.assertEqual(RenderTemplateMixin._resolve_finalize({}), {})
  1363. class JinjaEnvironmentParamsIntegrationTestCase(TestCase):
  1364. """Integration tests for get_environment_params() end-to-end."""
  1365. def _make_template(self, environment_params):
  1366. return ConfigTemplate(
  1367. name='test',
  1368. template_code='{{ "test" }}',
  1369. environment_params=environment_params,
  1370. )
  1371. def test_full_pipeline_with_undefined(self):
  1372. template = self._make_template({'undefined': 'jinja2.StrictUndefined', 'trim_blocks': True})
  1373. params = template.get_environment_params()
  1374. self.assertIs(params['undefined'], StrictUndefined)
  1375. self.assertIs(params['trim_blocks'], True)
  1376. def test_full_pipeline_strips_unknown_and_resolves(self):
  1377. template = self._make_template({
  1378. 'extensions': ['os'],
  1379. 'undefined': 'jinja2.DebugUndefined',
  1380. 'trim_blocks': True,
  1381. })
  1382. params = template.get_environment_params()
  1383. self.assertNotIn('extensions', params)
  1384. self.assertIs(params['undefined'], DebugUndefined)
  1385. self.assertIs(params['trim_blocks'], True)
  1386. def test_full_pipeline_finalize_resolves(self):
  1387. template = self._make_template({
  1388. 'finalize': 'extras.tests.test_models.finalize_none_to_dash',
  1389. })
  1390. params = template.get_environment_params()
  1391. self.assertIs(params['finalize'], finalize_none_to_dash)
  1392. def test_does_not_mutate_stored_value(self):
  1393. template = self._make_template({'undefined': 'jinja2.StrictUndefined'})
  1394. template.get_environment_params()
  1395. self.assertEqual(template.environment_params['undefined'], 'jinja2.StrictUndefined')
  1396. def test_none_environment_params(self):
  1397. template = self._make_template(None)
  1398. self.assertEqual(template.get_environment_params(), {})
  1399. def test_empty_environment_params(self):
  1400. template = self._make_template({})
  1401. self.assertEqual(template.get_environment_params(), {})