test_views.py 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363
  1. import uuid
  2. from unittest.mock import PropertyMock, patch
  3. from django.contrib.contenttypes.models import ContentType
  4. from django.contrib.messages import get_messages
  5. from django.test import tag
  6. from django.urls import reverse
  7. from core.choices import JobStatusChoices, ManagedFileRootPathChoices
  8. from core.events import *
  9. from core.models import Job, ObjectType
  10. from dcim.models import DeviceType, Manufacturer, Site
  11. from extras.choices import *
  12. from extras.models import *
  13. from extras.scripts import BooleanVar, IntegerVar
  14. from extras.scripts import Script as PythonClass
  15. from users.models import Group, ObjectPermission, User
  16. from utilities.testing import TestCase, ViewTestCases
  17. class CustomFieldTestCase(ViewTestCases.PrimaryObjectViewTestCase):
  18. model = CustomField
  19. @classmethod
  20. def setUpTestData(cls):
  21. site_type = ObjectType.objects.get_for_model(Site)
  22. CustomFieldChoiceSet.objects.create(
  23. name='Choice Set 1',
  24. extra_choices=(
  25. ('A', 'A'),
  26. ('B', 'B'),
  27. ('C', 'C'),
  28. )
  29. )
  30. custom_fields = (
  31. CustomField(name='field1', label='Field 1', type=CustomFieldTypeChoices.TYPE_TEXT),
  32. CustomField(name='field2', label='Field 2', type=CustomFieldTypeChoices.TYPE_TEXT),
  33. CustomField(name='field3', label='Field 3', type=CustomFieldTypeChoices.TYPE_TEXT),
  34. )
  35. for customfield in custom_fields:
  36. customfield.save()
  37. customfield.object_types.add(site_type)
  38. cls.form_data = {
  39. 'name': 'field_x',
  40. 'label': 'Field X',
  41. 'type': 'text',
  42. 'object_types': [site_type.pk],
  43. 'search_weight': 2000,
  44. 'filter_logic': CustomFieldFilterLogicChoices.FILTER_EXACT,
  45. 'default': None,
  46. 'weight': 200,
  47. 'required': True,
  48. 'ui_visible': CustomFieldUIVisibleChoices.ALWAYS,
  49. 'ui_editable': CustomFieldUIEditableChoices.YES,
  50. }
  51. cls.csv_data = (
  52. 'name,label,type,object_types,related_object_type,weight,search_weight,filter_logic,choice_set,validation_minimum,validation_maximum,validation_regex,ui_visible,ui_editable',
  53. 'field4,Field 4,text,dcim.site,,100,1000,exact,,,,[a-z]{3},always,yes',
  54. 'field5,Field 5,integer,dcim.site,,100,2000,exact,,1,100,,always,yes',
  55. 'field6,Field 6,select,dcim.site,,100,3000,exact,Choice Set 1,,,,always,yes',
  56. 'field7,Field 7,object,dcim.site,dcim.region,100,4000,exact,,,,,always,yes',
  57. )
  58. cls.csv_update_data = (
  59. 'id,label',
  60. f'{custom_fields[0].pk},New label 1',
  61. f'{custom_fields[1].pk},New label 2',
  62. f'{custom_fields[2].pk},New label 3',
  63. )
  64. cls.bulk_edit_data = {
  65. 'required': True,
  66. 'weight': 200,
  67. }
  68. class CustomFieldChoiceSetTestCase(ViewTestCases.PrimaryObjectViewTestCase):
  69. model = CustomFieldChoiceSet
  70. @classmethod
  71. def setUpTestData(cls):
  72. choice_sets = (
  73. CustomFieldChoiceSet(
  74. name='Choice Set 1',
  75. extra_choices=(('A1', 'Choice 1'), ('A2', 'Choice 2'), ('A3', 'Choice 3'))
  76. ),
  77. CustomFieldChoiceSet(
  78. name='Choice Set 2',
  79. extra_choices=(('B1', 'Choice 1'), ('B2', 'Choice 2'), ('B3', 'Choice 3'))
  80. ),
  81. CustomFieldChoiceSet(
  82. name='Choice Set 3',
  83. extra_choices=(('C1', 'Choice 1'), ('C2', 'Choice 2'), ('C3', 'Choice 3'))
  84. ),
  85. CustomFieldChoiceSet(
  86. name='Choice Set 4',
  87. extra_choices=(('D1', 'Choice 1'), ('D2', 'Choice 2'), ('D3', 'Choice 3'))
  88. ),
  89. )
  90. CustomFieldChoiceSet.objects.bulk_create(choice_sets)
  91. cls.form_data = {
  92. 'name': 'Choice Set X',
  93. 'extra_choices': '\n'.join(['X1:Choice 1', 'X2:Choice 2', 'X3:Choice 3'])
  94. }
  95. cls.csv_data = (
  96. 'name,extra_choices',
  97. 'Choice Set 5,"D1,D2,D3"',
  98. 'Choice Set 6,"E1,E2,E3"',
  99. 'Choice Set 7,"F1,F2,F3"',
  100. 'Choice Set 8,"F1:L1,F2:L2,F3:L3"',
  101. )
  102. cls.csv_update_data = (
  103. 'id,extra_choices',
  104. f'{choice_sets[0].pk},"A,B,C"',
  105. f'{choice_sets[1].pk},"A,B,C"',
  106. f'{choice_sets[2].pk},"A,B,C"',
  107. f'{choice_sets[3].pk},"A:L1,B:L2,C:L3"',
  108. )
  109. cls.bulk_edit_data = {
  110. 'description': 'New description',
  111. }
  112. # This is here as extra_choices field splits on colon, but is returned
  113. # from DB as comma separated.
  114. def assertInstanceEqual(self, instance, data, exclude=None, api=False):
  115. if 'extra_choices' in data:
  116. data['extra_choices'] = data['extra_choices'].replace(':', ',')
  117. return super().assertInstanceEqual(instance, data, exclude, api)
  118. class CustomLinkTestCase(ViewTestCases.PrimaryObjectViewTestCase):
  119. model = CustomLink
  120. @classmethod
  121. def setUpTestData(cls):
  122. site_type = ObjectType.objects.get_for_model(Site)
  123. custom_links = (
  124. CustomLink(name='Custom Link 1', enabled=True, link_text='Link 1', link_url='http://example.com/?1'),
  125. CustomLink(name='Custom Link 2', enabled=True, link_text='Link 2', link_url='http://example.com/?2'),
  126. CustomLink(name='Custom Link 3', enabled=False, link_text='Link 3', link_url='http://example.com/?3'),
  127. )
  128. CustomLink.objects.bulk_create(custom_links)
  129. for i, custom_link in enumerate(custom_links):
  130. custom_link.object_types.set([site_type])
  131. cls.form_data = {
  132. 'name': 'Custom Link X',
  133. 'object_types': [site_type.pk],
  134. 'enabled': False,
  135. 'weight': 100,
  136. 'button_class': CustomLinkButtonClassChoices.DEFAULT,
  137. 'link_text': 'Link X',
  138. 'link_url': 'http://example.com/?x'
  139. }
  140. cls.csv_data = (
  141. "name,object_types,enabled,weight,button_class,link_text,link_url",
  142. "Custom Link 4,dcim.site,True,100,blue,Link 4,http://exmaple.com/?4",
  143. "Custom Link 5,dcim.site,True,100,blue,Link 5,http://exmaple.com/?5",
  144. "Custom Link 6,dcim.site,False,100,blue,Link 6,http://exmaple.com/?6",
  145. )
  146. cls.csv_update_data = (
  147. "id,name",
  148. f"{custom_links[0].pk},Custom Link 7",
  149. f"{custom_links[1].pk},Custom Link 8",
  150. f"{custom_links[2].pk},Custom Link 9",
  151. )
  152. cls.bulk_edit_data = {
  153. 'button_class': CustomLinkButtonClassChoices.CYAN,
  154. 'enabled': False,
  155. 'weight': 200,
  156. }
  157. class CustomLinkRenderingTestCase(TestCase):
  158. user_permissions = ['dcim.view_site', 'extras.view_customlink']
  159. def test_view_object_with_custom_link(self):
  160. customlink = CustomLink(
  161. name='Test',
  162. link_text='FOO {{ object.name }} BAR',
  163. link_url='http://example.com/?site={{ object.slug }}',
  164. new_window=False
  165. )
  166. customlink.save()
  167. customlink.object_types.set([ObjectType.objects.get_for_model(Site)])
  168. site = Site(name='Test Site', slug='test-site')
  169. site.save()
  170. response = self.client.get(site.get_absolute_url(), follow=True)
  171. self.assertEqual(response.status_code, 200)
  172. self.assertIn(f'FOO {site.name} BAR', str(response.content))
  173. def test_list_view_custom_link_column(self):
  174. # A custom link column must render in the list view when the user can view the CustomLink.
  175. customlink = CustomLink(
  176. name='Test',
  177. link_text='FOO {{ object.name }} BAR',
  178. link_url='http://example.com/?site={{ object.slug }}',
  179. new_window=False
  180. )
  181. customlink.save()
  182. customlink.object_types.set([ObjectType.objects.get_for_model(Site)])
  183. site = Site(name='Test Site', slug='test-site')
  184. site.save()
  185. # Custom link columns are hidden by default; explicitly include the column
  186. response = self.client.get(f"{reverse('dcim:site_list')}?include_columns=cl_Test")
  187. self.assertEqual(response.status_code, 200)
  188. self.assertIn(f'FOO {site.name} BAR', str(response.content))
  189. def test_list_view_custom_link_column_hidden_without_permission(self):
  190. # A custom link column must be excluded from the list view when the user cannot view the
  191. # CustomLink, even if explicitly requested (#22439).
  192. customlink = CustomLink(
  193. name='Test',
  194. link_text='FOO {{ object.name }} BAR',
  195. link_url='http://example.com/?site={{ object.slug }}',
  196. new_window=False
  197. )
  198. customlink.save()
  199. customlink.object_types.set([ObjectType.objects.get_for_model(Site)])
  200. site = Site(name='Test Site', slug='test-site')
  201. site.save()
  202. # Revoke permission to view custom links
  203. self.remove_permissions('extras.view_customlink')
  204. response = self.client.get(f"{reverse('dcim:site_list')}?include_columns=cl_Test")
  205. self.assertEqual(response.status_code, 200)
  206. self.assertNotIn(f'FOO {site.name} BAR', str(response.content))
  207. class SavedFilterTestCase(ViewTestCases.PrimaryObjectViewTestCase):
  208. model = SavedFilter
  209. @classmethod
  210. def setUpTestData(cls):
  211. site_type = ObjectType.objects.get_for_model(Site)
  212. users = (
  213. User(username='User 1'),
  214. User(username='User 2'),
  215. User(username='User 3'),
  216. )
  217. User.objects.bulk_create(users)
  218. saved_filters = (
  219. SavedFilter(
  220. name='Saved Filter 1',
  221. slug='saved-filter-1',
  222. user=users[0],
  223. weight=100,
  224. parameters={'status': ['active']}
  225. ),
  226. SavedFilter(
  227. name='Saved Filter 2',
  228. slug='saved-filter-2',
  229. user=users[1],
  230. weight=200,
  231. parameters={'status': ['planned']}
  232. ),
  233. SavedFilter(
  234. name='Saved Filter 3',
  235. slug='saved-filter-3',
  236. user=users[2],
  237. weight=300,
  238. parameters={'status': ['retired']}
  239. ),
  240. )
  241. SavedFilter.objects.bulk_create(saved_filters)
  242. for i, savedfilter in enumerate(saved_filters):
  243. savedfilter.object_types.set([site_type])
  244. cls.form_data = {
  245. 'name': 'Saved Filter X',
  246. 'slug': 'saved-filter-x',
  247. 'object_types': [site_type.pk],
  248. 'description': 'Foo',
  249. 'weight': 1000,
  250. 'enabled': True,
  251. 'shared': True,
  252. 'parameters': '{"foo": 123}',
  253. }
  254. cls.csv_data = (
  255. 'name,slug,object_types,weight,enabled,shared,parameters',
  256. 'Saved Filter 4,saved-filter-4,dcim.device,400,True,True,{"foo": "a"}',
  257. 'Saved Filter 5,saved-filter-5,dcim.device,500,True,True,{"foo": "b"}',
  258. 'Saved Filter 6,saved-filter-6,dcim.device,600,True,True,{"foo": "c"}',
  259. )
  260. cls.csv_update_data = (
  261. "id,name",
  262. f"{saved_filters[0].pk},Saved Filter 7",
  263. f"{saved_filters[1].pk},Saved Filter 8",
  264. f"{saved_filters[2].pk},Saved Filter 9",
  265. )
  266. cls.bulk_edit_data = {
  267. 'weight': 999,
  268. }
  269. class TableConfigTestCase(
  270. ViewTestCases.GetObjectViewTestCase,
  271. ViewTestCases.GetObjectChangelogViewTestCase,
  272. ViewTestCases.CreateObjectViewTestCase,
  273. ViewTestCases.EditObjectViewTestCase,
  274. ViewTestCases.DeleteObjectViewTestCase,
  275. ViewTestCases.ListObjectsViewTestCase,
  276. ViewTestCases.BulkEditObjectsViewTestCase,
  277. ViewTestCases.BulkDeleteObjectsViewTestCase,
  278. ):
  279. model = TableConfig
  280. # Selected columns are POSTed as a list but compared as a CSV string
  281. validation_excluded_fields = ('columns',)
  282. @classmethod
  283. def setUpTestData(cls):
  284. site_type = ObjectType.objects.get_for_model(Site)
  285. users = (
  286. User(username='User 1'),
  287. User(username='User 2'),
  288. User(username='User 3'),
  289. )
  290. User.objects.bulk_create(users)
  291. table_configs = (
  292. TableConfig(
  293. name='Table Config 1',
  294. object_type=site_type,
  295. table='SiteTable',
  296. user=users[0],
  297. columns=['name', 'status'],
  298. ),
  299. TableConfig(
  300. name='Table Config 2',
  301. object_type=site_type,
  302. table='SiteTable',
  303. user=users[1],
  304. columns=['name', 'region'],
  305. ),
  306. TableConfig(
  307. name='Table Config 3',
  308. object_type=site_type,
  309. table='SiteTable',
  310. user=users[2],
  311. columns=['name', 'tenant'],
  312. ),
  313. )
  314. TableConfig.objects.bulk_create(table_configs)
  315. cls.form_data = {
  316. 'name': 'Table Config X',
  317. 'object_type': site_type.pk,
  318. 'table': 'SiteTable',
  319. 'description': 'A table config',
  320. 'weight': 100,
  321. 'enabled': True,
  322. 'shared': True,
  323. 'columns': ['name', 'status'],
  324. 'ordering': 'name',
  325. }
  326. cls.bulk_edit_data = {
  327. 'weight': 999,
  328. }
  329. def _get_url(self, action, instance=None):
  330. url = super()._get_url(action, instance)
  331. # The add view requires the table context from the source table view
  332. if action == 'add':
  333. site_type = ObjectType.objects.get_for_model(Site)
  334. url = f'{url}?object_type={site_type.pk}&table=SiteTable'
  335. return url
  336. def test_add_view_without_table_context(self):
  337. """A GET without the table context params must redirect to the home page."""
  338. self.add_permissions('extras.add_tableconfig')
  339. response = self.client.get(reverse('extras:tableconfig_add'))
  340. self.assertRedirects(response, reverse('home'))
  341. messages_list = list(get_messages(response.wsgi_request))
  342. self.assertEqual(len(messages_list), 1)
  343. self.assertEqual(str(messages_list[0]), 'Table configurations must be created from an object list view.')
  344. def test_add_view_post_without_table_context(self):
  345. """A POST without the table context must return form errors rather than a server error."""
  346. self.add_permissions('extras.add_tableconfig')
  347. response = self.client.post(reverse('extras:tableconfig_add'), data={})
  348. self.assertHttpStatus(response, 200)
  349. class BookmarkTestCase(
  350. ViewTestCases.DeleteObjectViewTestCase,
  351. ViewTestCases.ListObjectsViewTestCase,
  352. ViewTestCases.BulkDeleteObjectsViewTestCase
  353. ):
  354. model = Bookmark
  355. @classmethod
  356. def setUpTestData(cls):
  357. site_ct = ContentType.objects.get_for_model(Site)
  358. sites = (
  359. Site(name='Site 1', slug='site-1'),
  360. Site(name='Site 2', slug='site-2'),
  361. Site(name='Site 3', slug='site-3'),
  362. Site(name='Site 4', slug='site-4'),
  363. )
  364. Site.objects.bulk_create(sites)
  365. cls.form_data = {
  366. 'object_type': site_ct.pk,
  367. 'object_id': sites[3].pk,
  368. }
  369. def setUp(self):
  370. super().setUp()
  371. sites = Site.objects.all()
  372. user = self.user
  373. bookmarks = (
  374. Bookmark(object=sites[0], user=user),
  375. Bookmark(object=sites[1], user=user),
  376. Bookmark(object=sites[2], user=user),
  377. )
  378. Bookmark.objects.bulk_create(bookmarks)
  379. def _get_url(self, action, instance=None):
  380. if action == 'list':
  381. return reverse('account:bookmarks')
  382. return super()._get_url(action, instance)
  383. def test_list_objects_anonymous(self):
  384. return
  385. def test_export_objects_anonymous(self):
  386. return
  387. def test_list_objects_with_constrained_permission(self):
  388. return
  389. class ImageAttachmentTestCase(
  390. ViewTestCases.GetObjectViewTestCase,
  391. ViewTestCases.ListObjectsViewTestCase,
  392. ViewTestCases.DeleteObjectViewTestCase,
  393. ViewTestCases.BulkDeleteObjectsViewTestCase,
  394. ):
  395. # Add/Edit/BulkEdit are omitted: ImageField.save() re-reads the file to
  396. # populate image_height / image_width, which fails when fixtures use
  397. # placeholder URLs instead of real images on disk.
  398. model = ImageAttachment
  399. @classmethod
  400. def setUpTestData(cls):
  401. ct = ContentType.objects.get_for_model(Site)
  402. site = Site.objects.create(name='Site 1', slug='site-1')
  403. ImageAttachment.objects.bulk_create(
  404. [
  405. ImageAttachment(
  406. object_type=ct,
  407. object_id=site.pk,
  408. name='Image Attachment 1',
  409. image='http://example.com/image1.png',
  410. image_height=100,
  411. image_width=100,
  412. image_size=1024,
  413. ),
  414. ImageAttachment(
  415. object_type=ct,
  416. object_id=site.pk,
  417. name='Image Attachment 2',
  418. image='http://example.com/image2.png',
  419. image_height=100,
  420. image_width=100,
  421. image_size=2048,
  422. ),
  423. ImageAttachment(
  424. object_type=ct,
  425. object_id=site.pk,
  426. name='Image Attachment 3',
  427. image='http://example.com/image3.png',
  428. image_height=100,
  429. image_width=100,
  430. image_size=4096,
  431. ),
  432. ]
  433. )
  434. class ExportTemplateTestCase(ViewTestCases.PrimaryObjectViewTestCase):
  435. model = ExportTemplate
  436. @classmethod
  437. def setUpTestData(cls):
  438. site_type = ObjectType.objects.get_for_model(Site)
  439. TEMPLATE_CODE = """{% for object in queryset %}{{ object }}{% endfor %}"""
  440. ENVIRONMENT_PARAMS = """{"trim_blocks": true}"""
  441. export_templates = (
  442. ExportTemplate(name='Export Template 1', template_code=TEMPLATE_CODE),
  443. ExportTemplate(
  444. name='Export Template 2', template_code=TEMPLATE_CODE, environment_params={"trim_blocks": True}
  445. ),
  446. ExportTemplate(name='Export Template 3', template_code=TEMPLATE_CODE, file_name='export_template_3')
  447. )
  448. ExportTemplate.objects.bulk_create(export_templates)
  449. for et in export_templates:
  450. et.object_types.set([site_type])
  451. cls.form_data = {
  452. 'name': 'Export Template X',
  453. 'object_types': [site_type.pk],
  454. 'template_code': TEMPLATE_CODE,
  455. 'environment_params': ENVIRONMENT_PARAMS,
  456. 'file_name': 'template_x',
  457. }
  458. cls.csv_data = (
  459. "name,object_types,template_code,file_name",
  460. f"Export Template 4,dcim.site,{TEMPLATE_CODE},",
  461. f"Export Template 5,dcim.site,{TEMPLATE_CODE},template_5",
  462. f"Export Template 6,dcim.site,{TEMPLATE_CODE},",
  463. )
  464. cls.csv_update_data = (
  465. "id,name",
  466. f"{export_templates[0].pk},Export Template 7",
  467. f"{export_templates[1].pk},Export Template 8",
  468. f"{export_templates[2].pk},Export Template 9",
  469. )
  470. cls.bulk_edit_data = {
  471. 'mime_type': 'text/html',
  472. 'file_extension': 'html',
  473. 'as_attachment': True,
  474. }
  475. class ExportTemplateExportFlowTestCase(TestCase):
  476. """
  477. End-to-end test for ExportTemplate invocation via a list view's ?export=<name> query param.
  478. """
  479. @classmethod
  480. def setUpTestData(cls):
  481. Site.objects.bulk_create([
  482. Site(name='Site A', slug='site-a'),
  483. Site(name='Site B', slug='site-b'),
  484. ])
  485. site_type = ObjectType.objects.get_for_model(Site)
  486. ok_template = ExportTemplate.objects.create(
  487. name='Sites Export',
  488. template_code='{% for obj in queryset %}{{ obj.name }}\n{% endfor %}',
  489. mime_type='text/plain',
  490. file_extension='txt',
  491. )
  492. ok_template.object_types.set([site_type])
  493. broken_template = ExportTemplate.objects.create(
  494. name='Broken Export',
  495. template_code='{% for obj in queryset %}{{ obj.name ', # unterminated expression
  496. )
  497. broken_template.object_types.set([site_type])
  498. def test_export_template_invocation(self):
  499. self.add_permissions('dcim.view_site', 'extras.view_exporttemplate')
  500. url = reverse('dcim:site_list')
  501. response = self.client.get(f'{url}?export=Sites Export')
  502. self.assertEqual(response.status_code, 200)
  503. self.assertEqual(response['Content-Type'], 'text/plain')
  504. self.assertEqual(response['Content-Disposition'], 'attachment; filename="netbox_sites.txt"')
  505. # The rendered queryset reflects whatever ordering the list view applies. Assert on set
  506. # membership rather than line order so the test isn't coupled to Site's natural ordering.
  507. rendered_names = set(filter(None, response.content.decode().split('\n')))
  508. self.assertEqual(rendered_names, {'Site A', 'Site B'})
  509. def test_export_template_render_error_redirects(self):
  510. self.add_permissions('dcim.view_site', 'extras.view_exporttemplate')
  511. url = reverse('dcim:site_list')
  512. # A broken template surfaces an exception during render; the view catches it and redirects
  513. # back to the (filtered) list view rather than returning a 500.
  514. response = self.client.get(f'{url}?export=Broken Export')
  515. self.assertEqual(response.status_code, 302)
  516. self.assertTrue(response['Location'].startswith(url))
  517. self.assertNotIn('export=', response['Location'])
  518. class WebhookTestCase(ViewTestCases.PrimaryObjectViewTestCase):
  519. model = Webhook
  520. @classmethod
  521. def setUpTestData(cls):
  522. webhooks = (
  523. Webhook(name='Webhook 1', payload_url='http://example.com/?1', http_method='POST'),
  524. Webhook(name='Webhook 2', payload_url='http://example.com/?2', http_method='POST'),
  525. Webhook(name='Webhook 3', payload_url='http://example.com/?3', http_method='POST'),
  526. )
  527. for webhook in webhooks:
  528. webhook.save()
  529. cls.form_data = {
  530. 'name': 'Webhook X',
  531. 'payload_url': 'http://example.com/?x',
  532. 'http_method': 'GET',
  533. 'http_content_type': 'application/foo',
  534. 'description': 'My webhook',
  535. }
  536. cls.csv_data = (
  537. "name,payload_url,http_method,http_content_type,description",
  538. "Webhook 4,http://example.com/?4,GET,application/json,Foo",
  539. "Webhook 5,http://example.com/?5,GET,application/json,Bar",
  540. "Webhook 6,http://example.com/?6,GET,application/json,Baz",
  541. )
  542. cls.csv_update_data = (
  543. "id,name,description",
  544. f"{webhooks[0].pk},Webhook 7,Foo",
  545. f"{webhooks[1].pk},Webhook 8,Bar",
  546. f"{webhooks[2].pk},Webhook 9,Baz",
  547. )
  548. cls.bulk_edit_data = {
  549. 'http_method': 'GET',
  550. }
  551. class EventRulesTestCase(ViewTestCases.PrimaryObjectViewTestCase):
  552. model = EventRule
  553. @classmethod
  554. def setUpTestData(cls):
  555. webhooks = (
  556. Webhook(name='Webhook 1', payload_url='http://example.com/?1', http_method='POST'),
  557. Webhook(name='Webhook 2', payload_url='http://example.com/?2', http_method='POST'),
  558. Webhook(name='Webhook 3', payload_url='http://example.com/?3', http_method='POST'),
  559. )
  560. for webhook in webhooks:
  561. webhook.save()
  562. site_type = ObjectType.objects.get_for_model(Site)
  563. event_rules = (
  564. EventRule(name='EventRule 1', event_types=[OBJECT_CREATED], action_object=webhooks[0]),
  565. EventRule(name='EventRule 2', event_types=[OBJECT_CREATED], action_object=webhooks[1]),
  566. EventRule(name='EventRule 3', event_types=[OBJECT_CREATED], action_object=webhooks[2]),
  567. )
  568. for event in event_rules:
  569. event.save()
  570. event.object_types.add(site_type)
  571. webhook_ct = ContentType.objects.get_for_model(Webhook)
  572. cls.form_data = {
  573. 'name': 'Event X',
  574. 'object_types': [site_type.pk],
  575. 'event_types': [OBJECT_UPDATED, OBJECT_DELETED],
  576. 'conditions': None,
  577. 'action_type': 'webhook',
  578. 'action_object_type': webhook_ct.pk,
  579. 'action_object_id': webhooks[0].pk,
  580. 'action_choice': webhooks[0],
  581. 'description': 'New description',
  582. }
  583. cls.csv_data = (
  584. 'name,object_types,event_types,action_type,action_object',
  585. f'Webhook 4,dcim.site,"{OBJECT_CREATED},{OBJECT_UPDATED}",webhook,Webhook 1',
  586. )
  587. cls.csv_update_data = (
  588. "id,name",
  589. f"{event_rules[0].pk},Event 7",
  590. f"{event_rules[1].pk},Event 8",
  591. f"{event_rules[2].pk},Event 9",
  592. )
  593. cls.bulk_edit_data = {
  594. 'description': 'New description',
  595. }
  596. class TagTestCase(ViewTestCases.OrganizationalObjectViewTestCase):
  597. model = Tag
  598. @classmethod
  599. def setUpTestData(cls):
  600. site_ct = ContentType.objects.get_for_model(Site)
  601. tags = (
  602. Tag(name='Tag 1', slug='tag-1'),
  603. Tag(name='Tag 2', slug='tag-2', weight=1),
  604. Tag(name='Tag 3', slug='tag-3', weight=32767),
  605. )
  606. Tag.objects.bulk_create(tags)
  607. cls.form_data = {
  608. 'name': 'Tag X',
  609. 'slug': 'tag-x',
  610. 'color': 'c0c0c0',
  611. 'comments': 'Some comments',
  612. 'object_types': [site_ct.pk],
  613. 'weight': 11,
  614. }
  615. cls.csv_data = (
  616. "name,slug,color,description,object_types,weight",
  617. "Tag 4,tag-4,ff0000,Fourth tag,dcim.interface,0",
  618. "Tag 5,tag-5,00ff00,Fifth tag,'dcim.device,dcim.site',1111",
  619. "Tag 6,tag-6,0000ff,Sixth tag,dcim.site,0",
  620. )
  621. cls.csv_update_data = (
  622. "id,name,description",
  623. f"{tags[0].pk},Tag 7,Fourth tag7",
  624. f"{tags[1].pk},Tag 8,Fifth tag8",
  625. f"{tags[2].pk},Tag 9,Sixth tag9",
  626. )
  627. cls.bulk_edit_data = {
  628. 'color': '00ff00',
  629. }
  630. class ConfigContextProfileTestCase(ViewTestCases.PrimaryObjectViewTestCase):
  631. model = ConfigContextProfile
  632. @classmethod
  633. def setUpTestData(cls):
  634. profiles = (
  635. ConfigContextProfile(
  636. name='Config Context Profile 1',
  637. schema={
  638. "properties": {
  639. "foo": {
  640. "type": "string"
  641. }
  642. },
  643. "required": [
  644. "foo"
  645. ]
  646. }
  647. ),
  648. ConfigContextProfile(
  649. name='Config Context Profile 2',
  650. schema={
  651. "properties": {
  652. "bar": {
  653. "type": "string"
  654. }
  655. },
  656. "required": [
  657. "bar"
  658. ]
  659. }
  660. ),
  661. ConfigContextProfile(
  662. name='Config Context Profile 3',
  663. schema={
  664. "properties": {
  665. "baz": {
  666. "type": "string"
  667. }
  668. },
  669. "required": [
  670. "baz"
  671. ]
  672. }
  673. ),
  674. )
  675. ConfigContextProfile.objects.bulk_create(profiles)
  676. cls.form_data = {
  677. 'name': 'Config Context Profile X',
  678. 'description': 'A new config context profile',
  679. }
  680. cls.bulk_edit_data = {
  681. 'description': 'New description',
  682. }
  683. cls.csv_data = (
  684. 'name,description',
  685. 'Config context profile 1,Foo',
  686. 'Config context profile 2,Bar',
  687. 'Config context profile 3,Baz',
  688. )
  689. cls.csv_update_data = (
  690. "id,description",
  691. f"{profiles[0].pk},New description",
  692. f"{profiles[1].pk},New description",
  693. f"{profiles[2].pk},New description",
  694. )
  695. # TODO: Change base class to PrimaryObjectViewTestCase
  696. # Blocked by absence of standard create/edit, bulk create views
  697. class ConfigContextTestCase(
  698. ViewTestCases.GetObjectViewTestCase,
  699. ViewTestCases.GetObjectChangelogViewTestCase,
  700. ViewTestCases.DeleteObjectViewTestCase,
  701. ViewTestCases.ListObjectsViewTestCase,
  702. ViewTestCases.BulkEditObjectsViewTestCase,
  703. ViewTestCases.BulkDeleteObjectsViewTestCase
  704. ):
  705. model = ConfigContext
  706. @classmethod
  707. def setUpTestData(cls):
  708. manufacturer = Manufacturer.objects.create(name='Manufacturer 1', slug='manufacturer-1')
  709. devicetype = DeviceType.objects.create(manufacturer=manufacturer, model='Device Type 1', slug='device-type-1')
  710. # Create three ConfigContexts
  711. for i in range(1, 4):
  712. configcontext = ConfigContext(
  713. name='Config Context {}'.format(i),
  714. data={'foo': i}
  715. )
  716. configcontext.save()
  717. configcontext.device_types.add(devicetype)
  718. cls.form_data = {
  719. 'name': 'Config Context X',
  720. 'weight': 200,
  721. 'description': 'A new config context',
  722. 'is_active': True,
  723. 'regions': [],
  724. 'sites': [],
  725. 'roles': [],
  726. 'platforms': [],
  727. 'tenant_groups': [],
  728. 'tenants': [],
  729. 'device_types': [devicetype.id],
  730. 'tags': [],
  731. 'data': '{"foo": 123}',
  732. }
  733. cls.bulk_edit_data = {
  734. 'weight': 300,
  735. 'is_active': False,
  736. 'description': 'New description',
  737. }
  738. class ConfigTemplateTestCase(
  739. ViewTestCases.GetObjectViewTestCase,
  740. ViewTestCases.GetObjectChangelogViewTestCase,
  741. ViewTestCases.DeleteObjectViewTestCase,
  742. ViewTestCases.ListObjectsViewTestCase,
  743. ViewTestCases.BulkEditObjectsViewTestCase,
  744. ViewTestCases.BulkDeleteObjectsViewTestCase
  745. ):
  746. model = ConfigTemplate
  747. @classmethod
  748. def setUpTestData(cls):
  749. TEMPLATE_CODE = """Foo: {{ foo }}"""
  750. ENVIRONMENT_PARAMS = """{"trim_blocks": true}"""
  751. config_templates = (
  752. ConfigTemplate(
  753. name='Config Template 1',
  754. template_code=TEMPLATE_CODE)
  755. ,
  756. ConfigTemplate(
  757. name='Config Template 2',
  758. template_code=TEMPLATE_CODE,
  759. environment_params={"trim_blocks": True},
  760. ),
  761. ConfigTemplate(
  762. name='Config Template 3',
  763. template_code=TEMPLATE_CODE,
  764. file_name='config_template_3',
  765. ),
  766. )
  767. ConfigTemplate.objects.bulk_create(config_templates)
  768. cls.form_data = {
  769. 'name': 'Config Template X',
  770. 'description': 'Config template',
  771. 'template_code': TEMPLATE_CODE,
  772. 'environment_params': ENVIRONMENT_PARAMS,
  773. 'file_name': 'config_x',
  774. }
  775. cls.csv_update_data = (
  776. "id,name",
  777. f"{config_templates[0].pk},Config Template 7",
  778. f"{config_templates[1].pk},Config Template 8",
  779. f"{config_templates[2].pk},Config Template 9",
  780. )
  781. cls.bulk_edit_data = {
  782. 'description': 'New description',
  783. 'mime_type': 'text/html',
  784. 'file_name': 'output',
  785. 'file_extension': 'html',
  786. 'as_attachment': True,
  787. }
  788. class JournalEntryTestCase(
  789. # ViewTestCases.GetObjectViewTestCase,
  790. ViewTestCases.CreateObjectViewTestCase,
  791. ViewTestCases.EditObjectViewTestCase,
  792. ViewTestCases.DeleteObjectViewTestCase,
  793. ViewTestCases.ListObjectsViewTestCase,
  794. ViewTestCases.BulkEditObjectsViewTestCase,
  795. ViewTestCases.BulkDeleteObjectsViewTestCase
  796. ):
  797. model = JournalEntry
  798. @classmethod
  799. def setUpTestData(cls):
  800. site_ct = ContentType.objects.get_for_model(Site)
  801. site = Site.objects.create(name='Site 1', slug='site-1')
  802. user = User.objects.create(username='User 1')
  803. JournalEntry.objects.bulk_create((
  804. JournalEntry(assigned_object=site, created_by=user, comments='First entry'),
  805. JournalEntry(assigned_object=site, created_by=user, comments='Second entry'),
  806. JournalEntry(assigned_object=site, created_by=user, comments='Third entry'),
  807. ))
  808. cls.form_data = {
  809. 'assigned_object_type': site_ct.pk,
  810. 'assigned_object_id': site.pk,
  811. 'kind': 'info',
  812. 'comments': 'A new entry',
  813. }
  814. cls.bulk_edit_data = {
  815. 'kind': 'success',
  816. 'comments': 'Overwritten',
  817. }
  818. class SubscriptionTestCase(
  819. ViewTestCases.CreateObjectViewTestCase,
  820. ViewTestCases.DeleteObjectViewTestCase,
  821. ViewTestCases.ListObjectsViewTestCase,
  822. ViewTestCases.BulkDeleteObjectsViewTestCase
  823. ):
  824. model = Subscription
  825. @classmethod
  826. def setUpTestData(cls):
  827. site_ct = ContentType.objects.get_for_model(Site)
  828. sites = (
  829. Site(name='Site 1', slug='site-1'),
  830. Site(name='Site 2', slug='site-2'),
  831. Site(name='Site 3', slug='site-3'),
  832. Site(name='Site 4', slug='site-4'),
  833. )
  834. Site.objects.bulk_create(sites)
  835. cls.form_data = {
  836. 'object_type': site_ct.pk,
  837. 'object_id': sites[3].pk,
  838. }
  839. def setUp(self):
  840. super().setUp()
  841. sites = Site.objects.all()
  842. user = self.user
  843. subscriptions = (
  844. Subscription(object=sites[0], user=user),
  845. Subscription(object=sites[1], user=user),
  846. Subscription(object=sites[2], user=user),
  847. )
  848. Subscription.objects.bulk_create(subscriptions)
  849. def _get_url(self, action, instance=None):
  850. if action == 'list':
  851. return reverse('account:subscriptions')
  852. return super()._get_url(action, instance)
  853. def test_list_objects_anonymous(self):
  854. self.client.logout()
  855. url = reverse('account:subscriptions')
  856. login_url = reverse('login')
  857. self.assertRedirects(self.client.get(url), f'{login_url}?next={url}')
  858. def test_export_objects_anonymous(self):
  859. return
  860. def test_list_objects_with_permission(self):
  861. return
  862. def test_list_objects_with_constrained_permission(self):
  863. return
  864. class NotificationGroupTestCase(ViewTestCases.PrimaryObjectViewTestCase):
  865. model = NotificationGroup
  866. @classmethod
  867. def setUpTestData(cls):
  868. users = (
  869. User(username='User 1'),
  870. User(username='User 2'),
  871. User(username='User 3'),
  872. )
  873. User.objects.bulk_create(users)
  874. groups = (
  875. Group(name='Group 1'),
  876. Group(name='Group 2'),
  877. Group(name='Group 3'),
  878. )
  879. Group.objects.bulk_create(groups)
  880. notification_groups = (
  881. NotificationGroup(name='Notification Group 1'),
  882. NotificationGroup(name='Notification Group 2'),
  883. NotificationGroup(name='Notification Group 3'),
  884. )
  885. NotificationGroup.objects.bulk_create(notification_groups)
  886. for i, notification_group in enumerate(notification_groups):
  887. notification_group.users.add(users[i])
  888. notification_group.groups.add(groups[i])
  889. cls.form_data = {
  890. 'name': 'Notification Group X',
  891. 'description': 'Blah',
  892. 'users': [users[0].pk, users[1].pk],
  893. 'groups': [groups[0].pk, groups[1].pk],
  894. }
  895. cls.csv_data = (
  896. 'name,description,users,groups',
  897. 'Notification Group 4,Foo,"User 1,User 2","Group 1,Group 2"',
  898. 'Notification Group 5,Bar,"User 1,User 2","Group 1,Group 2"',
  899. 'Notification Group 6,Baz,"User 1,User 2","Group 1,Group 2"',
  900. )
  901. cls.csv_update_data = (
  902. "id,name",
  903. f"{notification_groups[0].pk},Notification Group 7",
  904. f"{notification_groups[1].pk},Notification Group 8",
  905. f"{notification_groups[2].pk},Notification Group 9",
  906. )
  907. cls.bulk_edit_data = {
  908. 'description': 'New description',
  909. }
  910. class NotificationTestCase(
  911. ViewTestCases.DeleteObjectViewTestCase,
  912. ViewTestCases.ListObjectsViewTestCase,
  913. ViewTestCases.BulkDeleteObjectsViewTestCase
  914. ):
  915. model = Notification
  916. @classmethod
  917. def setUpTestData(cls):
  918. site_ct = ContentType.objects.get_for_model(Site)
  919. sites = (
  920. Site(name='Site 1', slug='site-1'),
  921. Site(name='Site 2', slug='site-2'),
  922. Site(name='Site 3', slug='site-3'),
  923. Site(name='Site 4', slug='site-4'),
  924. )
  925. Site.objects.bulk_create(sites)
  926. cls.form_data = {
  927. 'object_type': site_ct.pk,
  928. 'object_id': sites[3].pk,
  929. }
  930. def setUp(self):
  931. super().setUp()
  932. sites = Site.objects.all()
  933. user = self.user
  934. notifications = (
  935. Notification(object=sites[0], user=user),
  936. Notification(object=sites[1], user=user),
  937. Notification(object=sites[2], user=user),
  938. )
  939. Notification.objects.bulk_create(notifications)
  940. def _get_url(self, action, instance=None):
  941. if action == 'list':
  942. return reverse('account:notifications')
  943. return super()._get_url(action, instance)
  944. def test_list_objects_anonymous(self):
  945. self.client.logout()
  946. url = reverse('account:notifications')
  947. login_url = reverse('login')
  948. self.assertRedirects(self.client.get(url), f'{login_url}?next={url}')
  949. def test_export_objects_anonymous(self):
  950. return
  951. def test_list_objects_with_permission(self):
  952. return
  953. def test_list_objects_with_constrained_permission(self):
  954. return
  955. class ScriptListViewTestCase(TestCase):
  956. user_permissions = ['extras.view_script']
  957. def test_script_list_embedded_parameter(self):
  958. """Test that ScriptListView accepts embedded parameter without error"""
  959. url = reverse('extras:script_list')
  960. # Test normal request
  961. response = self.client.get(url)
  962. self.assertEqual(response.status_code, 200)
  963. self.assertTemplateUsed(response, 'extras/script_list.html')
  964. # Test embedded request
  965. response = self.client.get(url, {'embedded': 'true'})
  966. self.assertEqual(response.status_code, 200)
  967. self.assertTemplateUsed(response, 'extras/inc/script_list_content.html')
  968. class ScriptModuleCreateViewTestCase(TestCase):
  969. user_permissions = ['core.add_managedfile', 'extras.add_scriptmodule']
  970. @tag('regression')
  971. def test_default_return_url(self):
  972. """
  973. The add view should fall back to the scripts list as its return URL.
  974. """
  975. response = self.client.get(reverse('extras:scriptmodule_add'))
  976. self.assertEqual(response.status_code, 200)
  977. self.assertEqual(response.context['return_url'], reverse('extras:script_list'))
  978. class ScriptValidationErrorTestCase(TestCase):
  979. user_permissions = ['extras.view_script', 'extras.run_script']
  980. class TestScriptMixin:
  981. bar = IntegerVar(min_value=0, max_value=30)
  982. class TestScriptClass(TestScriptMixin, PythonClass):
  983. class Meta:
  984. name = 'Test script'
  985. commit_default = False
  986. fieldsets = (("Logging", ("debug_mode",)),)
  987. debug_mode = BooleanVar(default=False)
  988. def run(self, data, commit):
  989. return "Complete"
  990. @classmethod
  991. def setUpTestData(cls):
  992. # Avoid trying to import a non-existent on-disk module during setup.
  993. # This test creates the Script row explicitly and monkey-patches
  994. # Script.python_class below.
  995. with patch.object(ScriptModule, 'sync_classes'):
  996. module = ScriptModule.objects.create(
  997. file_root=ManagedFileRootPathChoices.SCRIPTS,
  998. file_path='test_script.py',
  999. )
  1000. cls.script = Script.objects.create(module=module, name='Test script', is_executable=True)
  1001. def setUp(self):
  1002. super().setUp()
  1003. Script.python_class = property(lambda self: ScriptValidationErrorTestCase.TestScriptClass)
  1004. @tag('regression')
  1005. def test_script_validation_error_displays_message(self):
  1006. url = reverse('extras:script', kwargs={'pk': self.script.pk})
  1007. with patch('extras.views.any_workers_for_queue', return_value=True):
  1008. response = self.client.post(url, {'debug_mode': 'true', '_commit': 'true'})
  1009. self.assertEqual(response.status_code, 200)
  1010. messages = list(response.context['messages'])
  1011. self.assertEqual(len(messages), 1)
  1012. self.assertEqual(str(messages[0]), "bar: This field is required.")
  1013. @tag('regression')
  1014. def test_script_validation_error_no_toast_for_fieldset_fields(self):
  1015. class FieldsetScript(PythonClass):
  1016. class Meta:
  1017. name = 'Fieldset test'
  1018. commit_default = False
  1019. fieldsets = (("Fields", ("required_field",)),)
  1020. required_field = IntegerVar(min_value=10)
  1021. def run(self, data, commit):
  1022. return "Complete"
  1023. url = reverse('extras:script', kwargs={'pk': self.script.pk})
  1024. with patch.object(Script, 'python_class', new_callable=PropertyMock) as mock_python_class:
  1025. mock_python_class.return_value = FieldsetScript
  1026. with patch('extras.views.any_workers_for_queue', return_value=True):
  1027. response = self.client.post(url, {'required_field': '5', '_commit': 'true'})
  1028. self.assertEqual(response.status_code, 200)
  1029. messages = list(response.context['messages'])
  1030. self.assertEqual(len(messages), 0)
  1031. class ScriptDefaultValuesTestCase(TestCase):
  1032. user_permissions = ['extras.view_script', 'extras.run_script']
  1033. class TestScriptClass(PythonClass):
  1034. class Meta:
  1035. name = 'Test script'
  1036. commit_default = False
  1037. bool_default_true = BooleanVar(default=True)
  1038. bool_default_false = BooleanVar(default=False)
  1039. int_with_default = IntegerVar(default=0)
  1040. int_without_default = IntegerVar(required=False)
  1041. def run(self, data, commit):
  1042. return "Complete"
  1043. @classmethod
  1044. def setUpTestData(cls):
  1045. # Avoid trying to import a non-existent on-disk module during setup.
  1046. # This test creates the Script row explicitly and monkey-patches
  1047. # Script.python_class below.
  1048. with patch.object(ScriptModule, 'sync_classes'):
  1049. module = ScriptModule.objects.create(
  1050. file_root=ManagedFileRootPathChoices.SCRIPTS,
  1051. file_path='test_script.py',
  1052. )
  1053. cls.script = Script.objects.create(module=module, name='Test script', is_executable=True)
  1054. def setUp(self):
  1055. super().setUp()
  1056. Script.python_class = property(lambda self: ScriptDefaultValuesTestCase.TestScriptClass)
  1057. def test_default_values_are_used(self):
  1058. url = reverse('extras:script', kwargs={'pk': self.script.pk})
  1059. with patch('extras.views.any_workers_for_queue', return_value=True):
  1060. with patch('extras.jobs.ScriptJob.enqueue') as mock_enqueue:
  1061. mock_enqueue.return_value.pk = 1
  1062. self.client.post(url, {})
  1063. call_kwargs = mock_enqueue.call_args.kwargs
  1064. self.assertEqual(call_kwargs['data']['bool_default_true'], True)
  1065. self.assertEqual(call_kwargs['data']['bool_default_false'], False)
  1066. self.assertEqual(call_kwargs['data']['int_with_default'], 0)
  1067. self.assertIsNone(call_kwargs['data']['int_without_default'])
  1068. class ScriptResultViewTestCase(TestCase):
  1069. SECRET_OUTPUT = 'my secret script output'
  1070. @classmethod
  1071. def setUpTestData(cls):
  1072. with patch.object(ScriptModule, 'sync_classes'):
  1073. module = ScriptModule.objects.create(
  1074. file_root=ManagedFileRootPathChoices.SCRIPTS,
  1075. file_path='test_script.py',
  1076. )
  1077. cls.allowed_script = Script.objects.create(
  1078. module=module, name='Allowed script', is_executable=True
  1079. )
  1080. cls.secret_script = Script.objects.create(
  1081. module=module, name='Secret script', is_executable=True
  1082. )
  1083. script_type = ObjectType.objects.get_for_model(Script)
  1084. cls.allowed_job = Job.objects.create(
  1085. object_type=script_type,
  1086. object_id=cls.allowed_script.pk,
  1087. name='allowed-job',
  1088. job_id=uuid.uuid4(),
  1089. status=JobStatusChoices.STATUS_COMPLETED,
  1090. data={'log': [], 'output': 'benign output'},
  1091. )
  1092. cls.secret_job = Job.objects.create(
  1093. object_type=script_type,
  1094. object_id=cls.secret_script.pk,
  1095. name='secret-job',
  1096. job_id=uuid.uuid4(),
  1097. status=JobStatusChoices.STATUS_COMPLETED,
  1098. data={'log': [], 'output': cls.SECRET_OUTPUT},
  1099. )
  1100. def test_get_without_view_job_permission_returns_404(self):
  1101. """
  1102. A user with extras.view_script but no core.view_job must not retrieve any job result
  1103. via ScriptResultView, even for the script whose object-level permission they hold.
  1104. """
  1105. self.add_permissions('extras.view_script')
  1106. url = reverse('extras:script_result', kwargs={'job_pk': self.allowed_job.pk})
  1107. self.assertHttpStatus(self.client.get(url), 404)
  1108. url = reverse('extras:script_result', kwargs={'job_pk': self.secret_job.pk})
  1109. self.assertHttpStatus(self.client.get(url), 404)
  1110. def test_get_export_output_without_view_job_permission_returns_404(self):
  1111. """
  1112. Regression for the PoC: the ?export=output path must not leak job.data['output']
  1113. when the user lacks core.view_job.
  1114. """
  1115. self.add_permissions('extras.view_script')
  1116. url = reverse('extras:script_result', kwargs={'job_pk': self.secret_job.pk})
  1117. response = self.client.get(url, {'export': 'output'})
  1118. self.assertHttpStatus(response, 404)
  1119. self.assertNotIn(self.SECRET_OUTPUT.encode(), response.content)
  1120. def test_get_with_constrained_view_job_permission(self):
  1121. """
  1122. With core.view_job constrained to the allowed job only, the user can fetch the allowed
  1123. result but the secret result is hidden (404).
  1124. """
  1125. self.add_permissions('extras.view_script')
  1126. obj_perm = ObjectPermission(
  1127. name='View allowed job only',
  1128. constraints={'pk': self.allowed_job.pk},
  1129. actions=['view'],
  1130. )
  1131. obj_perm.save()
  1132. obj_perm.users.add(self.user)
  1133. obj_perm.object_types.add(ObjectType.objects.get_for_model(Job))
  1134. url = reverse('extras:script_result', kwargs={'job_pk': self.allowed_job.pk})
  1135. self.assertHttpStatus(self.client.get(url), 200)
  1136. url = reverse('extras:script_result', kwargs={'job_pk': self.secret_job.pk})
  1137. response = self.client.get(url, {'export': 'output'})
  1138. self.assertHttpStatus(response, 404)
  1139. self.assertNotIn(self.SECRET_OUTPUT.encode(), response.content)