test_models.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756
  1. import tempfile
  2. from pathlib import Path
  3. from django.contrib.contenttypes.models import ContentType
  4. from django.core.files.uploadedfile import SimpleUploadedFile
  5. from django.forms import ValidationError
  6. from django.test import tag, TestCase
  7. from core.models import DataSource, ObjectType
  8. from dcim.models import Device, DeviceRole, DeviceType, Location, Manufacturer, Platform, Region, Site, SiteGroup
  9. from extras.models import ConfigContext, ConfigContextProfile, ConfigTemplate, ImageAttachment, Tag, TaggedItem
  10. from tenancy.models import Tenant, TenantGroup
  11. from utilities.exceptions import AbortRequest
  12. from virtualization.models import Cluster, ClusterGroup, ClusterType, VirtualMachine
  13. class ImageAttachmentTests(TestCase):
  14. @classmethod
  15. def setUpTestData(cls):
  16. cls.ct_rack = ContentType.objects.get(app_label='dcim', model='rack')
  17. cls.image_content = b''
  18. def _stub_image_attachment(self, object_id, image_filename, name=None):
  19. """
  20. Creates an instance of ImageAttachment with the provided object_id and image_name.
  21. This method prepares a stubbed image attachment to test functionalities that
  22. require an ImageAttachment object.
  23. The function initializes the attachment with a specified file name and
  24. pre-defined image content.
  25. """
  26. ia = ImageAttachment(
  27. object_type=self.ct_rack,
  28. object_id=object_id,
  29. name=name,
  30. image=SimpleUploadedFile(
  31. name=image_filename,
  32. content=self.image_content,
  33. content_type='image/jpeg',
  34. ),
  35. )
  36. return ia
  37. def test_filename_strips_expected_prefix(self):
  38. """
  39. Tests that the filename of the image attachment is stripped of the expected
  40. prefix.
  41. """
  42. ia = self._stub_image_attachment(12, 'image-attachments/rack_12_My_File.png')
  43. self.assertEqual(ia.filename, 'My_File.png')
  44. def test_filename_legacy_nested_path_returns_basename(self):
  45. """
  46. Tests if the filename of a legacy-nested path correctly returns only the basename.
  47. """
  48. # e.g. "image-attachments/rack_12_5/31/23.jpg" -> "23.jpg"
  49. ia = self._stub_image_attachment(12, 'image-attachments/rack_12_5/31/23.jpg')
  50. self.assertEqual(ia.filename, '23.jpg')
  51. def test_filename_no_prefix_returns_basename(self):
  52. """
  53. Tests that the filename property correctly returns the basename for an image
  54. attachment that has no leading prefix in its path.
  55. """
  56. ia = self._stub_image_attachment(42, 'image-attachments/just_name.webp')
  57. self.assertEqual(ia.filename, 'just_name.webp')
  58. def test_mismatched_prefix_is_not_stripped(self):
  59. """
  60. Tests that a mismatched prefix in the filename is not stripped.
  61. """
  62. # Prefix does not match object_id -> leave as-is (basename only)
  63. ia = self._stub_image_attachment(12, 'image-attachments/rack_13_other.png')
  64. self.assertEqual('rack_13_other.png', ia.filename)
  65. def test_str_uses_name_when_present(self):
  66. """
  67. Tests that the `str` representation of the object uses the
  68. `name` attribute when provided.
  69. """
  70. ia = self._stub_image_attachment(12, 'image-attachments/rack_12_file.png', name='Human title')
  71. self.assertEqual('Human title', str(ia))
  72. def test_str_falls_back_to_filename(self):
  73. """
  74. Tests that the `str` representation of the object falls back to
  75. the filename if the name attribute is not set.
  76. """
  77. ia = self._stub_image_attachment(12, 'image-attachments/rack_12_file.png', name='')
  78. self.assertEqual('file.png', str(ia))
  79. class TagTest(TestCase):
  80. def test_default_ordering_weight_then_name_is_set(self):
  81. Tag.objects.create(name='Tag 1', slug='tag-1', weight=3000)
  82. Tag.objects.create(name='Tag 2', slug='tag-2') # Default: 1000
  83. Tag.objects.create(name='Tag 3', slug='tag-3', weight=2000)
  84. Tag.objects.create(name='Tag 4', slug='tag-4', weight=2000)
  85. tags = Tag.objects.all()
  86. self.assertEqual(tags[0].slug, 'tag-2')
  87. self.assertEqual(tags[1].slug, 'tag-3')
  88. self.assertEqual(tags[2].slug, 'tag-4')
  89. self.assertEqual(tags[3].slug, 'tag-1')
  90. def test_tag_related_manager_ordering_weight_then_name(self):
  91. tags = [
  92. Tag.objects.create(name='Tag 1', slug='tag-1', weight=3000),
  93. Tag.objects.create(name='Tag 2', slug='tag-2'), # Default: 1000
  94. Tag.objects.create(name='Tag 3', slug='tag-3', weight=2000),
  95. Tag.objects.create(name='Tag 4', slug='tag-4', weight=2000),
  96. ]
  97. site = Site.objects.create(name='Site 1')
  98. for _tag in tags:
  99. site.tags.add(_tag)
  100. site.save()
  101. site = Site.objects.first()
  102. tags = site.tags.all()
  103. self.assertEqual(tags[0].slug, 'tag-2')
  104. self.assertEqual(tags[1].slug, 'tag-3')
  105. self.assertEqual(tags[2].slug, 'tag-4')
  106. self.assertEqual(tags[3].slug, 'tag-1')
  107. def test_create_tag_unicode(self):
  108. tag = Tag(name='Testing Unicode: 台灣')
  109. tag.save()
  110. self.assertEqual(tag.slug, 'testing-unicode-台灣')
  111. def test_object_type_validation(self):
  112. region = Region.objects.create(name='Region 1', slug='region-1')
  113. sitegroup = SiteGroup.objects.create(name='Site Group 1', slug='site-group-1')
  114. # Create a Tag that can only be applied to Regions
  115. tag = Tag.objects.create(name='Tag 1', slug='tag-1')
  116. tag.object_types.add(ObjectType.objects.get_by_natural_key('dcim', 'region'))
  117. # Apply the Tag to a Region
  118. region.tags.add(tag)
  119. self.assertIn(tag, region.tags.all())
  120. # Apply the Tag to a SiteGroup
  121. with self.assertRaises(AbortRequest):
  122. sitegroup.tags.add(tag)
  123. class ConfigContextTest(TestCase):
  124. """
  125. These test cases deal with the weighting, ordering, and deep merge logic of config context data.
  126. It also ensures the various config context querysets are consistent.
  127. """
  128. @classmethod
  129. def setUpTestData(cls):
  130. manufacturer = Manufacturer.objects.create(name='Manufacturer 1', slug='manufacturer-1')
  131. devicetype = DeviceType.objects.create(manufacturer=manufacturer, model='Device Type 1', slug='device-type-1')
  132. role = DeviceRole.objects.create(name='Device Role 1', slug='device-role-1')
  133. region = Region.objects.create(name='Region')
  134. sitegroup = SiteGroup.objects.create(name='Site Group')
  135. site = Site.objects.create(name='Site 1', slug='site-1', region=region, group=sitegroup)
  136. location = Location.objects.create(name='Location 1', slug='location-1', site=site)
  137. Platform.objects.create(name='Platform')
  138. tenantgroup = TenantGroup.objects.create(name='Tenant Group')
  139. Tenant.objects.create(name='Tenant', group=tenantgroup)
  140. Tag.objects.create(name='Tag', slug='tag')
  141. Tag.objects.create(name='Tag2', slug='tag2')
  142. Device.objects.create(
  143. name='Device 1',
  144. device_type=devicetype,
  145. role=role,
  146. site=site,
  147. location=location
  148. )
  149. def test_higher_weight_wins(self):
  150. device = Device.objects.first()
  151. context1 = ConfigContext(
  152. name="context 1",
  153. weight=101,
  154. data={
  155. "a": 123,
  156. "b": 456,
  157. "c": 777
  158. }
  159. )
  160. context2 = ConfigContext(
  161. name="context 2",
  162. weight=100,
  163. data={
  164. "a": 123,
  165. "b": 456,
  166. "c": 789
  167. }
  168. )
  169. ConfigContext.objects.bulk_create([context1, context2])
  170. expected_data = {
  171. "a": 123,
  172. "b": 456,
  173. "c": 777
  174. }
  175. self.assertEqual(device.get_config_context(), expected_data)
  176. def test_name_ordering_after_weight(self):
  177. device = Device.objects.first()
  178. context1 = ConfigContext(
  179. name="context 1",
  180. weight=100,
  181. data={
  182. "a": 123,
  183. "b": 456,
  184. "c": 777
  185. }
  186. )
  187. context2 = ConfigContext(
  188. name="context 2",
  189. weight=100,
  190. data={
  191. "a": 123,
  192. "b": 456,
  193. "c": 789
  194. }
  195. )
  196. ConfigContext.objects.bulk_create([context1, context2])
  197. expected_data = {
  198. "a": 123,
  199. "b": 456,
  200. "c": 789
  201. }
  202. self.assertEqual(device.get_config_context(), expected_data)
  203. def test_schema_validation(self):
  204. """
  205. Check that the JSON schema defined by the assigned profile is enforced.
  206. """
  207. profile = ConfigContextProfile.objects.create(
  208. name="Config context profile 1",
  209. schema={
  210. "properties": {
  211. "foo": {
  212. "type": "string"
  213. }
  214. },
  215. "required": [
  216. "foo"
  217. ]
  218. }
  219. )
  220. with self.assertRaises(ValidationError):
  221. # Missing required attribute
  222. ConfigContext(name="CC1", profile=profile, data={}).clean()
  223. with self.assertRaises(ValidationError):
  224. # Invalid attribute type
  225. ConfigContext(name="CC1", profile=profile, data={"foo": 123}).clean()
  226. ConfigContext(name="CC1", profile=profile, data={"foo": "bar"}).clean()
  227. def test_annotation_same_as_get_for_object(self):
  228. """
  229. This test incorporates features from all of the above tests cases to ensure
  230. the annotate_config_context_data() and get_for_object() queryset methods are the same.
  231. """
  232. device = Device.objects.first()
  233. context1 = ConfigContext(
  234. name="context 1",
  235. weight=101,
  236. data={
  237. "a": 123,
  238. "b": 456,
  239. "c": 777
  240. }
  241. )
  242. context2 = ConfigContext(
  243. name="context 2",
  244. weight=100,
  245. data={
  246. "a": 123,
  247. "b": 456,
  248. "c": 789
  249. }
  250. )
  251. context3 = ConfigContext(
  252. name="context 3",
  253. weight=99,
  254. data={
  255. "d": 1
  256. }
  257. )
  258. context4 = ConfigContext(
  259. name="context 4",
  260. weight=99,
  261. data={
  262. "d": 2
  263. }
  264. )
  265. ConfigContext.objects.bulk_create([context1, context2, context3, context4])
  266. annotated_queryset = Device.objects.filter(name=device.name).annotate_config_context_data()
  267. self.assertEqual(device.get_config_context(), annotated_queryset[0].get_config_context())
  268. def test_annotation_same_as_get_for_object_device_relations(self):
  269. region = Region.objects.first()
  270. sitegroup = SiteGroup.objects.first()
  271. site = Site.objects.first()
  272. location = Location.objects.first()
  273. platform = Platform.objects.first()
  274. tenantgroup = TenantGroup.objects.first()
  275. tenant = Tenant.objects.first()
  276. tag = Tag.objects.first()
  277. region_context = ConfigContext.objects.create(
  278. name="region",
  279. weight=100,
  280. data={
  281. "region": 1
  282. }
  283. )
  284. region_context.regions.add(region)
  285. sitegroup_context = ConfigContext.objects.create(
  286. name="sitegroup",
  287. weight=100,
  288. data={
  289. "sitegroup": 1
  290. }
  291. )
  292. sitegroup_context.site_groups.add(sitegroup)
  293. site_context = ConfigContext.objects.create(
  294. name="site",
  295. weight=100,
  296. data={
  297. "site": 1
  298. }
  299. )
  300. site_context.sites.add(site)
  301. location_context = ConfigContext.objects.create(
  302. name="location",
  303. weight=100,
  304. data={
  305. "location": 1
  306. }
  307. )
  308. location_context.locations.add(location)
  309. platform_context = ConfigContext.objects.create(
  310. name="platform",
  311. weight=100,
  312. data={
  313. "platform": 1
  314. }
  315. )
  316. platform_context.platforms.add(platform)
  317. tenant_group_context = ConfigContext.objects.create(
  318. name="tenant group",
  319. weight=100,
  320. data={
  321. "tenant_group": 1
  322. }
  323. )
  324. tenant_group_context.tenant_groups.add(tenantgroup)
  325. tenant_context = ConfigContext.objects.create(
  326. name="tenant",
  327. weight=100,
  328. data={
  329. "tenant": 1
  330. }
  331. )
  332. tenant_context.tenants.add(tenant)
  333. tag_context = ConfigContext.objects.create(
  334. name="tag",
  335. weight=100,
  336. data={
  337. "tag": 1
  338. }
  339. )
  340. tag_context.tags.add(tag)
  341. device = Device.objects.create(
  342. name="Device 2",
  343. site=site,
  344. location=location,
  345. tenant=tenant,
  346. platform=platform,
  347. role=DeviceRole.objects.first(),
  348. device_type=DeviceType.objects.first()
  349. )
  350. device.tags.add(tag)
  351. annotated_queryset = Device.objects.filter(name=device.name).annotate_config_context_data()
  352. self.assertEqual(device.get_config_context(), annotated_queryset[0].get_config_context())
  353. def test_annotation_same_as_get_for_object_virtualmachine_relations(self):
  354. region = Region.objects.first()
  355. sitegroup = SiteGroup.objects.first()
  356. site = Site.objects.first()
  357. platform = Platform.objects.first()
  358. tenantgroup = TenantGroup.objects.first()
  359. tenant = Tenant.objects.first()
  360. tag = Tag.objects.first()
  361. cluster_type = ClusterType.objects.create(name="Cluster Type")
  362. cluster_group = ClusterGroup.objects.create(name="Cluster Group")
  363. cluster = Cluster.objects.create(
  364. name="Cluster",
  365. group=cluster_group,
  366. type=cluster_type,
  367. scope=site,
  368. )
  369. region_context = ConfigContext.objects.create(
  370. name="region",
  371. weight=100,
  372. data={"region": 1}
  373. )
  374. region_context.regions.add(region)
  375. sitegroup_context = ConfigContext.objects.create(
  376. name="sitegroup",
  377. weight=100,
  378. data={"sitegroup": 1}
  379. )
  380. sitegroup_context.site_groups.add(sitegroup)
  381. site_context = ConfigContext.objects.create(
  382. name="site",
  383. weight=100,
  384. data={"site": 1}
  385. )
  386. site_context.sites.add(site)
  387. platform_context = ConfigContext.objects.create(
  388. name="platform",
  389. weight=100,
  390. data={"platform": 1}
  391. )
  392. platform_context.platforms.add(platform)
  393. tenant_group_context = ConfigContext.objects.create(
  394. name="tenant group",
  395. weight=100,
  396. data={"tenant_group": 1}
  397. )
  398. tenant_group_context.tenant_groups.add(tenantgroup)
  399. tenant_context = ConfigContext.objects.create(
  400. name="tenant",
  401. weight=100,
  402. data={"tenant": 1}
  403. )
  404. tenant_context.tenants.add(tenant)
  405. tag_context = ConfigContext.objects.create(
  406. name="tag",
  407. weight=100,
  408. data={"tag": 1}
  409. )
  410. tag_context.tags.add(tag)
  411. cluster_type_context = ConfigContext.objects.create(
  412. name="cluster type",
  413. weight=100,
  414. data={"cluster_type": 1}
  415. )
  416. cluster_type_context.cluster_types.add(cluster_type)
  417. cluster_group_context = ConfigContext.objects.create(
  418. name="cluster group",
  419. weight=100,
  420. data={"cluster_group": 1}
  421. )
  422. cluster_group_context.cluster_groups.add(cluster_group)
  423. cluster_context = ConfigContext.objects.create(
  424. name="cluster",
  425. weight=100,
  426. data={"cluster": 1}
  427. )
  428. cluster_context.clusters.add(cluster)
  429. virtual_machine = VirtualMachine.objects.create(
  430. name="VM 1",
  431. cluster=cluster,
  432. tenant=tenant,
  433. platform=platform,
  434. role=DeviceRole.objects.first()
  435. )
  436. virtual_machine.tags.add(tag)
  437. annotated_queryset = VirtualMachine.objects.filter(name=virtual_machine.name).annotate_config_context_data()
  438. self.assertEqual(virtual_machine.get_config_context(), annotated_queryset[0].get_config_context())
  439. def test_virtualmachine_site_context(self):
  440. """
  441. Check that config context associated with a site applies to a VM whether the VM is assigned
  442. directly to that site or via its cluster.
  443. """
  444. site = Site.objects.first()
  445. cluster_type = ClusterType.objects.create(name="Cluster Type")
  446. cluster = Cluster.objects.create(name="Cluster", type=cluster_type, scope=site)
  447. vm_role = DeviceRole.objects.first()
  448. # Create a ConfigContext associated with the site
  449. context = ConfigContext.objects.create(
  450. name="context1",
  451. weight=100,
  452. data={"foo": True}
  453. )
  454. context.sites.add(site)
  455. # Create one VM assigned directly to the site, and one assigned via the cluster
  456. vm1 = VirtualMachine.objects.create(name="VM 1", site=site, role=vm_role)
  457. vm2 = VirtualMachine.objects.create(name="VM 2", cluster=cluster, role=vm_role)
  458. # Check that their individually rendered config contexts are identical
  459. self.assertEqual(
  460. vm1.get_config_context(),
  461. vm2.get_config_context()
  462. )
  463. # Check that their annotated config contexts are identical
  464. vms = VirtualMachine.objects.filter(pk__in=(vm1.pk, vm2.pk)).annotate_config_context_data()
  465. self.assertEqual(
  466. vms[0].get_config_context(),
  467. vms[1].get_config_context()
  468. )
  469. def test_valid_local_context_data(self):
  470. device = Device.objects.first()
  471. device.local_context_data = None
  472. device.clean()
  473. device.local_context_data = {"foo": "bar"}
  474. device.clean()
  475. def test_invalid_local_context_data(self):
  476. device = Device.objects.first()
  477. device.local_context_data = ""
  478. with self.assertRaises(ValidationError):
  479. device.clean()
  480. device.local_context_data = 0
  481. with self.assertRaises(ValidationError):
  482. device.clean()
  483. device.local_context_data = False
  484. with self.assertRaises(ValidationError):
  485. device.clean()
  486. device.local_context_data = 'foo'
  487. with self.assertRaises(ValidationError):
  488. device.clean()
  489. @tag('regression')
  490. def test_multiple_tags_return_distinct_objects(self):
  491. """
  492. Tagged items use a generic relationship, which results in duplicate rows being returned when queried.
  493. This is combated by appending distinct() to the config context querysets. This test creates a config
  494. context assigned to two tags and ensures objects related to those same two tags result in only a single
  495. config context record being returned.
  496. See https://github.com/netbox-community/netbox/issues/5314
  497. """
  498. site = Site.objects.first()
  499. platform = Platform.objects.first()
  500. tenant = Tenant.objects.first()
  501. tags = Tag.objects.all()
  502. tag_context = ConfigContext.objects.create(
  503. name="tag",
  504. weight=100,
  505. data={
  506. "tag": 1
  507. }
  508. )
  509. tag_context.tags.set(tags)
  510. device = Device.objects.create(
  511. name="Device 3",
  512. site=site,
  513. tenant=tenant,
  514. platform=platform,
  515. role=DeviceRole.objects.first(),
  516. device_type=DeviceType.objects.first()
  517. )
  518. device.tags.set(tags)
  519. annotated_queryset = Device.objects.filter(name=device.name).annotate_config_context_data()
  520. self.assertEqual(ConfigContext.objects.get_for_object(device).count(), 1)
  521. self.assertEqual(device.get_config_context(), annotated_queryset[0].get_config_context())
  522. @tag('regression')
  523. def test_multiple_tags_return_distinct_objects_with_separate_config_contexts(self):
  524. """
  525. Tagged items use a generic relationship, which results in duplicate rows being returned when queried.
  526. This is combated by appending distinct() to the config context querysets. This test creates a config
  527. context assigned to two tags and ensures objects related to those same two tags result in only a single
  528. config context record being returned.
  529. This test case is separate from the above in that it deals with multiple config context objects in play.
  530. See https://github.com/netbox-community/netbox/issues/5387
  531. """
  532. site = Site.objects.first()
  533. platform = Platform.objects.first()
  534. tenant = Tenant.objects.first()
  535. tag1, tag2 = list(Tag.objects.all())
  536. tag_context_1 = ConfigContext.objects.create(
  537. name="tag-1",
  538. weight=100,
  539. data={
  540. "tag": 1
  541. }
  542. )
  543. tag_context_1.tags.add(tag1)
  544. tag_context_2 = ConfigContext.objects.create(
  545. name="tag-2",
  546. weight=100,
  547. data={
  548. "tag": 1
  549. }
  550. )
  551. tag_context_2.tags.add(tag2)
  552. device = Device.objects.create(
  553. name="Device 3",
  554. site=site,
  555. tenant=tenant,
  556. platform=platform,
  557. role=DeviceRole.objects.first(),
  558. device_type=DeviceType.objects.first()
  559. )
  560. device.tags.set([tag1, tag2])
  561. annotated_queryset = Device.objects.filter(name=device.name).annotate_config_context_data()
  562. self.assertEqual(ConfigContext.objects.get_for_object(device).count(), 2)
  563. self.assertEqual(device.get_config_context(), annotated_queryset[0].get_config_context())
  564. @tag('performance', 'regression')
  565. def test_config_context_annotation_query_optimization(self):
  566. """
  567. Regression test for issue #20327: Ensure config context annotation
  568. doesn't use expensive DISTINCT on main query.
  569. Verifies that DISTINCT is only used in tag subquery where needed,
  570. not on the main device query which is expensive for large datasets.
  571. """
  572. device = Device.objects.first()
  573. queryset = Device.objects.filter(pk=device.pk).annotate_config_context_data()
  574. # Main device query should NOT use DISTINCT
  575. self.assertFalse(queryset.query.distinct)
  576. # Check that tag subqueries DO use DISTINCT by inspecting the annotation
  577. config_annotation = queryset.query.annotations.get('config_context_data')
  578. self.assertIsNotNone(config_annotation)
  579. def find_tag_subqueries(where_node):
  580. """Find subqueries in WHERE clause that relate to tag filtering"""
  581. subqueries = []
  582. def traverse(node):
  583. if hasattr(node, 'children'):
  584. for child in node.children:
  585. try:
  586. if child.rhs.query.model is TaggedItem:
  587. subqueries.append(child.rhs.query)
  588. except AttributeError:
  589. traverse(child)
  590. traverse(where_node)
  591. return subqueries
  592. # Find subqueries in the WHERE clause that should have DISTINCT
  593. tag_subqueries = find_tag_subqueries(config_annotation.query.where)
  594. distinct_subqueries = [sq for sq in tag_subqueries if sq.distinct]
  595. # Verify we found at least one DISTINCT subquery for tags
  596. self.assertEqual(len(distinct_subqueries), 1)
  597. self.assertTrue(distinct_subqueries[0].distinct)
  598. class ConfigTemplateTest(TestCase):
  599. """
  600. TODO: These test cases deal with the weighting, ordering, and deep merge logic of config context data.
  601. """
  602. MAIN_TEMPLATE = """
  603. {%- include 'base.j2' %}
  604. """.strip()
  605. BASE_TEMPLATE = """
  606. Hi
  607. """.strip()
  608. @classmethod
  609. def _create_template_file(cls, templates_dir, file_name, content):
  610. template_file_name = file_name
  611. if not template_file_name.endswith('j2'):
  612. template_file_name += '.j2'
  613. temp_file_path = templates_dir / template_file_name
  614. with open(temp_file_path, 'w') as f:
  615. f.write(content)
  616. @classmethod
  617. def setUpTestData(cls):
  618. temp_dir = tempfile.TemporaryDirectory()
  619. templates_dir = Path(temp_dir.name) / "templates"
  620. templates_dir.mkdir(parents=True, exist_ok=True)
  621. cls._create_template_file(templates_dir, 'base.j2', cls.BASE_TEMPLATE)
  622. cls._create_template_file(templates_dir, 'main.j2', cls.MAIN_TEMPLATE)
  623. data_source = DataSource(
  624. name="Test DataSource",
  625. type="local",
  626. source_url=str(templates_dir),
  627. )
  628. data_source.save()
  629. data_source.sync()
  630. base_config_template = ConfigTemplate(
  631. name="BaseTemplate",
  632. data_file=data_source.datafiles.filter(path__endswith='base.j2').first()
  633. )
  634. base_config_template.clean()
  635. base_config_template.save()
  636. cls.base_config_template = base_config_template
  637. main_config_template = ConfigTemplate(
  638. name="MainTemplate",
  639. data_file=data_source.datafiles.filter(path__endswith='main.j2').first()
  640. )
  641. main_config_template.clean()
  642. main_config_template.save()
  643. cls.main_config_template = main_config_template
  644. @tag('regression')
  645. def test_config_template_with_data_source(self):
  646. self.assertEqual(self.BASE_TEMPLATE, self.base_config_template.render({}))
  647. @tag('regression')
  648. def test_config_template_with_data_source_nested_templates(self):
  649. self.assertEqual(self.BASE_TEMPLATE, self.main_config_template.render({}))