test_api.py 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126
  1. import datetime
  2. from django.contrib.contenttypes.models import ContentType
  3. from django.urls import reverse
  4. from django.utils.timezone import make_aware
  5. from rest_framework import status
  6. from core.choices import ManagedFileRootPathChoices
  7. from core.events import *
  8. from core.models import ObjectType
  9. from dcim.models import Device, DeviceRole, DeviceType, Manufacturer, Rack, Location, RackRole, Site
  10. from extras.choices import *
  11. from extras.models import *
  12. from extras.scripts import BooleanVar, IntegerVar, Script as PythonClass, StringVar
  13. from users.models import Group, User
  14. from utilities.testing import APITestCase, APIViewTestCases
  15. class AppTest(APITestCase):
  16. def test_root(self):
  17. url = reverse('extras-api:api-root')
  18. response = self.client.get('{}?format=api'.format(url), **self.header)
  19. self.assertEqual(response.status_code, 200)
  20. class WebhookTest(APIViewTestCases.APIViewTestCase):
  21. model = Webhook
  22. brief_fields = ['description', 'display', 'id', 'name', 'url']
  23. create_data = [
  24. {
  25. 'name': 'Webhook 4',
  26. 'payload_url': 'http://example.com/?4',
  27. },
  28. {
  29. 'name': 'Webhook 5',
  30. 'payload_url': 'http://example.com/?5',
  31. },
  32. {
  33. 'name': 'Webhook 6',
  34. 'payload_url': 'http://example.com/?6',
  35. },
  36. ]
  37. bulk_update_data = {
  38. 'description': 'New description',
  39. 'ssl_verification': False,
  40. }
  41. @classmethod
  42. def setUpTestData(cls):
  43. webhooks = (
  44. Webhook(
  45. name='Webhook 1',
  46. payload_url='http://example.com/?1',
  47. ),
  48. Webhook(
  49. name='Webhook 2',
  50. payload_url='http://example.com/?1',
  51. ),
  52. Webhook(
  53. name='Webhook 3',
  54. payload_url='http://example.com/?1',
  55. ),
  56. )
  57. Webhook.objects.bulk_create(webhooks)
  58. class EventRuleTest(APIViewTestCases.APIViewTestCase):
  59. model = EventRule
  60. brief_fields = ['description', 'display', 'id', 'name', 'url']
  61. bulk_update_data = {
  62. 'enabled': False,
  63. 'description': 'New description',
  64. }
  65. update_data = {
  66. 'name': 'Event Rule X',
  67. 'enabled': False,
  68. 'description': 'New description',
  69. }
  70. @classmethod
  71. def setUpTestData(cls):
  72. webhooks = (
  73. Webhook(
  74. name='Webhook 1',
  75. payload_url='http://example.com/?1',
  76. ),
  77. Webhook(
  78. name='Webhook 2',
  79. payload_url='http://example.com/?1',
  80. ),
  81. Webhook(
  82. name='Webhook 3',
  83. payload_url='http://example.com/?1',
  84. ),
  85. Webhook(
  86. name='Webhook 4',
  87. payload_url='http://example.com/?1',
  88. ),
  89. Webhook(
  90. name='Webhook 5',
  91. payload_url='http://example.com/?1',
  92. ),
  93. Webhook(
  94. name='Webhook 6',
  95. payload_url='http://example.com/?1',
  96. ),
  97. )
  98. Webhook.objects.bulk_create(webhooks)
  99. event_rules = (
  100. EventRule(name='EventRule 1', event_types=[OBJECT_CREATED], action_object=webhooks[0]),
  101. EventRule(name='EventRule 2', event_types=[OBJECT_CREATED], action_object=webhooks[1]),
  102. EventRule(name='EventRule 3', event_types=[OBJECT_CREATED], action_object=webhooks[2]),
  103. )
  104. EventRule.objects.bulk_create(event_rules)
  105. cls.create_data = [
  106. {
  107. 'name': 'EventRule 4',
  108. 'object_types': ['dcim.device', 'dcim.devicetype'],
  109. 'event_types': [OBJECT_CREATED],
  110. 'action_type': EventRuleActionChoices.WEBHOOK,
  111. 'action_object_type': 'extras.webhook',
  112. 'action_object_id': webhooks[3].pk,
  113. },
  114. {
  115. 'name': 'EventRule 5',
  116. 'object_types': ['dcim.device', 'dcim.devicetype'],
  117. 'event_types': [OBJECT_CREATED],
  118. 'action_type': EventRuleActionChoices.WEBHOOK,
  119. 'action_object_type': 'extras.webhook',
  120. 'action_object_id': webhooks[4].pk,
  121. },
  122. {
  123. 'name': 'EventRule 6',
  124. 'object_types': ['dcim.device', 'dcim.devicetype'],
  125. 'event_types': [OBJECT_CREATED],
  126. 'action_type': EventRuleActionChoices.WEBHOOK,
  127. 'action_object_type': 'extras.webhook',
  128. 'action_object_id': webhooks[5].pk,
  129. },
  130. ]
  131. class CustomFieldTest(APIViewTestCases.APIViewTestCase):
  132. model = CustomField
  133. brief_fields = ['description', 'display', 'id', 'name', 'url']
  134. create_data = [
  135. {
  136. 'object_types': ['dcim.site'],
  137. 'name': 'cf4',
  138. 'type': 'date',
  139. },
  140. {
  141. 'object_types': ['dcim.site'],
  142. 'name': 'cf5',
  143. 'type': 'url',
  144. },
  145. {
  146. 'object_types': ['dcim.site'],
  147. 'name': 'cf6',
  148. 'type': 'text',
  149. },
  150. ]
  151. bulk_update_data = {
  152. 'description': 'New description',
  153. }
  154. update_data = {
  155. 'object_types': ['dcim.device'],
  156. 'name': 'New_Name',
  157. 'description': 'New description',
  158. }
  159. @classmethod
  160. def setUpTestData(cls):
  161. site_ct = ObjectType.objects.get_for_model(Site)
  162. custom_fields = (
  163. CustomField(
  164. name='cf1',
  165. type='text'
  166. ),
  167. CustomField(
  168. name='cf2',
  169. type='integer'
  170. ),
  171. CustomField(
  172. name='cf3',
  173. type='boolean'
  174. ),
  175. )
  176. CustomField.objects.bulk_create(custom_fields)
  177. for cf in custom_fields:
  178. cf.object_types.add(site_ct)
  179. class CustomFieldChoiceSetTest(APIViewTestCases.APIViewTestCase):
  180. model = CustomFieldChoiceSet
  181. brief_fields = ['choices_count', 'description', 'display', 'id', 'name', 'url']
  182. create_data = [
  183. {
  184. 'name': 'Choice Set 4',
  185. 'extra_choices': [
  186. ['4A', 'Choice 1'],
  187. ['4B', 'Choice 2'],
  188. ['4C', 'Choice 3'],
  189. ],
  190. },
  191. {
  192. 'name': 'Choice Set 5',
  193. 'extra_choices': [
  194. ['5A', 'Choice 1'],
  195. ['5B', 'Choice 2'],
  196. ['5C', 'Choice 3'],
  197. ],
  198. },
  199. {
  200. 'name': 'Choice Set 6',
  201. 'extra_choices': [
  202. ['6A', 'Choice 1'],
  203. ['6B', 'Choice 2'],
  204. ['6C', 'Choice 3'],
  205. ],
  206. },
  207. ]
  208. bulk_update_data = {
  209. 'description': 'New description',
  210. }
  211. update_data = {
  212. 'name': 'Choice Set X',
  213. 'extra_choices': [
  214. ['X1', 'Choice 1'],
  215. ['X2', 'Choice 2'],
  216. ['X3', 'Choice 3'],
  217. ],
  218. 'description': 'New description',
  219. }
  220. @classmethod
  221. def setUpTestData(cls):
  222. choice_sets = (
  223. CustomFieldChoiceSet(
  224. name='Choice Set 1',
  225. extra_choices=[['1A', '1A'], ['1B', '1B'], ['1C', '1C'], ['1D', '1D'], ['1E', '1E']],
  226. ),
  227. CustomFieldChoiceSet(
  228. name='Choice Set 2',
  229. extra_choices=[['2A', '2A'], ['2B', '2B'], ['2C', '2C'], ['2D', '2D'], ['2E', '2E']],
  230. ),
  231. CustomFieldChoiceSet(
  232. name='Choice Set 3',
  233. extra_choices=[['3A', '3A'], ['3B', '3B'], ['3C', '3C'], ['3D', '3D'], ['3E', '3E']],
  234. ),
  235. )
  236. CustomFieldChoiceSet.objects.bulk_create(choice_sets)
  237. def test_invalid_choice_items(self):
  238. """
  239. Attempting to define each choice as a single-item list should return a 400 error.
  240. """
  241. self.add_permissions('extras.add_customfieldchoiceset')
  242. data = {
  243. "name": "test",
  244. "extra_choices": [
  245. ["choice1"],
  246. ["choice2"],
  247. ["choice3"],
  248. ]
  249. }
  250. response = self.client.post(self._get_list_url(), data, format='json', **self.header)
  251. self.assertEqual(response.status_code, 400)
  252. class CustomLinkTest(APIViewTestCases.APIViewTestCase):
  253. model = CustomLink
  254. brief_fields = ['display', 'id', 'name', 'url']
  255. create_data = [
  256. {
  257. 'object_types': ['dcim.site'],
  258. 'name': 'Custom Link 4',
  259. 'enabled': True,
  260. 'link_text': 'Link 4',
  261. 'link_url': 'http://example.com/?4',
  262. },
  263. {
  264. 'object_types': ['dcim.site'],
  265. 'name': 'Custom Link 5',
  266. 'enabled': True,
  267. 'link_text': 'Link 5',
  268. 'link_url': 'http://example.com/?5',
  269. },
  270. {
  271. 'object_types': ['dcim.site'],
  272. 'name': 'Custom Link 6',
  273. 'enabled': False,
  274. 'link_text': 'Link 6',
  275. 'link_url': 'http://example.com/?6',
  276. },
  277. ]
  278. bulk_update_data = {
  279. 'new_window': True,
  280. 'enabled': False,
  281. }
  282. @classmethod
  283. def setUpTestData(cls):
  284. site_type = ObjectType.objects.get_for_model(Site)
  285. custom_links = (
  286. CustomLink(
  287. name='Custom Link 1',
  288. enabled=True,
  289. link_text='Link 1',
  290. link_url='http://example.com/?1',
  291. ),
  292. CustomLink(
  293. name='Custom Link 2',
  294. enabled=True,
  295. link_text='Link 2',
  296. link_url='http://example.com/?2',
  297. ),
  298. CustomLink(
  299. name='Custom Link 3',
  300. enabled=False,
  301. link_text='Link 3',
  302. link_url='http://example.com/?3',
  303. ),
  304. )
  305. CustomLink.objects.bulk_create(custom_links)
  306. for i, custom_link in enumerate(custom_links):
  307. custom_link.object_types.set([site_type])
  308. class SavedFilterTest(APIViewTestCases.APIViewTestCase):
  309. model = SavedFilter
  310. brief_fields = ['description', 'display', 'id', 'name', 'slug', 'url']
  311. create_data = [
  312. {
  313. 'object_types': ['dcim.site'],
  314. 'name': 'Saved Filter 4',
  315. 'slug': 'saved-filter-4',
  316. 'weight': 100,
  317. 'enabled': True,
  318. 'shared': True,
  319. 'parameters': {'status': ['active']},
  320. },
  321. {
  322. 'object_types': ['dcim.site'],
  323. 'name': 'Saved Filter 5',
  324. 'slug': 'saved-filter-5',
  325. 'weight': 200,
  326. 'enabled': True,
  327. 'shared': True,
  328. 'parameters': {'status': ['planned']},
  329. },
  330. {
  331. 'object_types': ['dcim.site'],
  332. 'name': 'Saved Filter 6',
  333. 'slug': 'saved-filter-6',
  334. 'weight': 300,
  335. 'enabled': True,
  336. 'shared': True,
  337. 'parameters': {'status': ['retired']},
  338. },
  339. ]
  340. bulk_update_data = {
  341. 'weight': 1000,
  342. 'enabled': False,
  343. 'shared': False,
  344. }
  345. @classmethod
  346. def setUpTestData(cls):
  347. site_type = ObjectType.objects.get_for_model(Site)
  348. saved_filters = (
  349. SavedFilter(
  350. name='Saved Filter 1',
  351. slug='saved-filter-1',
  352. weight=100,
  353. enabled=True,
  354. shared=True,
  355. parameters={'status': ['active']}
  356. ),
  357. SavedFilter(
  358. name='Saved Filter 2',
  359. slug='saved-filter-2',
  360. weight=200,
  361. enabled=True,
  362. shared=True,
  363. parameters={'status': ['planned']}
  364. ),
  365. SavedFilter(
  366. name='Saved Filter 3',
  367. slug='saved-filter-3',
  368. weight=300,
  369. enabled=True,
  370. shared=True,
  371. parameters={'status': ['retired']}
  372. ),
  373. )
  374. SavedFilter.objects.bulk_create(saved_filters)
  375. for i, savedfilter in enumerate(saved_filters):
  376. savedfilter.object_types.set([site_type])
  377. class BookmarkTest(
  378. APIViewTestCases.GetObjectViewTestCase,
  379. APIViewTestCases.ListObjectsViewTestCase,
  380. APIViewTestCases.CreateObjectViewTestCase,
  381. APIViewTestCases.DeleteObjectViewTestCase
  382. ):
  383. model = Bookmark
  384. brief_fields = ['display', 'id', 'object_id', 'object_type', 'url']
  385. @classmethod
  386. def setUpTestData(cls):
  387. sites = (
  388. Site(name='Site 1', slug='site-1'),
  389. Site(name='Site 2', slug='site-2'),
  390. Site(name='Site 3', slug='site-3'),
  391. Site(name='Site 4', slug='site-4'),
  392. Site(name='Site 5', slug='site-5'),
  393. Site(name='Site 6', slug='site-6'),
  394. )
  395. Site.objects.bulk_create(sites)
  396. def setUp(self):
  397. super().setUp()
  398. sites = Site.objects.all()
  399. bookmarks = (
  400. Bookmark(object=sites[0], user=self.user),
  401. Bookmark(object=sites[1], user=self.user),
  402. Bookmark(object=sites[2], user=self.user),
  403. )
  404. Bookmark.objects.bulk_create(bookmarks)
  405. self.create_data = [
  406. {
  407. 'object_type': 'dcim.site',
  408. 'object_id': sites[3].pk,
  409. 'user': self.user.pk,
  410. },
  411. {
  412. 'object_type': 'dcim.site',
  413. 'object_id': sites[4].pk,
  414. 'user': self.user.pk,
  415. },
  416. {
  417. 'object_type': 'dcim.site',
  418. 'object_id': sites[5].pk,
  419. 'user': self.user.pk,
  420. },
  421. ]
  422. class ExportTemplateTest(APIViewTestCases.APIViewTestCase):
  423. model = ExportTemplate
  424. brief_fields = ['description', 'display', 'id', 'name', 'url']
  425. create_data = [
  426. {
  427. 'object_types': ['dcim.device'],
  428. 'name': 'Test Export Template 4',
  429. 'template_code': '{% for obj in queryset %}{{ obj.name }}\n{% endfor %}',
  430. },
  431. {
  432. 'object_types': ['dcim.device'],
  433. 'name': 'Test Export Template 5',
  434. 'template_code': '{% for obj in queryset %}{{ obj.name }}\n{% endfor %}',
  435. },
  436. {
  437. 'object_types': ['dcim.device'],
  438. 'name': 'Test Export Template 6',
  439. 'template_code': '{% for obj in queryset %}{{ obj.name }}\n{% endfor %}',
  440. 'file_name': 'test_export_template_6',
  441. },
  442. ]
  443. bulk_update_data = {
  444. 'description': 'New description',
  445. }
  446. @classmethod
  447. def setUpTestData(cls):
  448. export_templates = (
  449. ExportTemplate(
  450. name='Export Template 1',
  451. template_code='{% for obj in queryset %}{{ obj.name }}\n{% endfor %}'
  452. ),
  453. ExportTemplate(
  454. name='Export Template 2',
  455. template_code='{% for obj in queryset %}{{ obj.name }}\n{% endfor %}',
  456. file_name='export_template_2',
  457. file_extension='test',
  458. ),
  459. ExportTemplate(
  460. name='Export Template 3',
  461. template_code='{% for obj in queryset %}{{ obj.name }}\n{% endfor %}'
  462. ),
  463. )
  464. ExportTemplate.objects.bulk_create(export_templates)
  465. device_object_type = ObjectType.objects.get_for_model(Device)
  466. for et in export_templates:
  467. et.object_types.set([device_object_type])
  468. class TagTest(APIViewTestCases.APIViewTestCase):
  469. model = Tag
  470. brief_fields = ['color', 'description', 'display', 'id', 'name', 'slug', 'url']
  471. create_data = [
  472. {
  473. 'name': 'Tag 4',
  474. 'slug': 'tag-4',
  475. 'weight': 1000,
  476. },
  477. {
  478. 'name': 'Tag 5',
  479. 'slug': 'tag-5',
  480. },
  481. {
  482. 'name': 'Tag 6',
  483. 'slug': 'tag-6',
  484. },
  485. ]
  486. bulk_update_data = {
  487. 'description': 'New description',
  488. }
  489. @classmethod
  490. def setUpTestData(cls):
  491. tags = (
  492. Tag(name='Tag 1', slug='tag-1'),
  493. Tag(name='Tag 2', slug='tag-2'),
  494. Tag(name='Tag 3', slug='tag-3', weight=26),
  495. )
  496. Tag.objects.bulk_create(tags)
  497. class TaggedItemTest(
  498. APIViewTestCases.GetObjectViewTestCase,
  499. APIViewTestCases.ListObjectsViewTestCase
  500. ):
  501. model = TaggedItem
  502. brief_fields = ['display', 'id', 'object', 'object_id', 'object_type', 'tag', 'url']
  503. @classmethod
  504. def setUpTestData(cls):
  505. tags = (
  506. Tag(name='Tag 1', slug='tag-1'),
  507. Tag(name='Tag 2', slug='tag-2'),
  508. Tag(name='Tag 3', slug='tag-3'),
  509. )
  510. Tag.objects.bulk_create(tags)
  511. sites = (
  512. Site(name='Site 1', slug='site-1'),
  513. Site(name='Site 2', slug='site-2'),
  514. Site(name='Site 3', slug='site-3'),
  515. )
  516. Site.objects.bulk_create(sites)
  517. sites[0].tags.set([tags[0], tags[1]])
  518. sites[1].tags.set([tags[1], tags[2]])
  519. sites[2].tags.set([tags[2], tags[0]])
  520. # TODO: Standardize to APIViewTestCase (needs create & update tests)
  521. class ImageAttachmentTest(
  522. APIViewTestCases.GetObjectViewTestCase,
  523. APIViewTestCases.ListObjectsViewTestCase,
  524. APIViewTestCases.DeleteObjectViewTestCase,
  525. APIViewTestCases.GraphQLTestCase
  526. ):
  527. model = ImageAttachment
  528. brief_fields = ['display', 'id', 'image', 'name', 'url']
  529. @classmethod
  530. def setUpTestData(cls):
  531. ct = ContentType.objects.get_for_model(Site)
  532. site = Site.objects.create(name='Site 1', slug='site-1')
  533. image_attachments = (
  534. ImageAttachment(
  535. object_type=ct,
  536. object_id=site.pk,
  537. name='Image Attachment 1',
  538. image='http://example.com/image1.png',
  539. image_height=100,
  540. image_width=100
  541. ),
  542. ImageAttachment(
  543. object_type=ct,
  544. object_id=site.pk,
  545. name='Image Attachment 2',
  546. image='http://example.com/image2.png',
  547. image_height=100,
  548. image_width=100
  549. ),
  550. ImageAttachment(
  551. object_type=ct,
  552. object_id=site.pk,
  553. name='Image Attachment 3',
  554. image='http://example.com/image3.png',
  555. image_height=100,
  556. image_width=100
  557. )
  558. )
  559. ImageAttachment.objects.bulk_create(image_attachments)
  560. class JournalEntryTest(APIViewTestCases.APIViewTestCase):
  561. model = JournalEntry
  562. brief_fields = ['created', 'display', 'id', 'url']
  563. bulk_update_data = {
  564. 'comments': 'Overwritten',
  565. }
  566. @classmethod
  567. def setUpTestData(cls):
  568. user = User.objects.first()
  569. site = Site.objects.create(name='Site 1', slug='site-1')
  570. journal_entries = (
  571. JournalEntry(
  572. created_by=user,
  573. assigned_object=site,
  574. comments='Fourth entry',
  575. ),
  576. JournalEntry(
  577. created_by=user,
  578. assigned_object=site,
  579. comments='Fifth entry',
  580. ),
  581. JournalEntry(
  582. created_by=user,
  583. assigned_object=site,
  584. comments='Sixth entry',
  585. ),
  586. )
  587. JournalEntry.objects.bulk_create(journal_entries)
  588. cls.create_data = [
  589. {
  590. 'assigned_object_type': 'dcim.site',
  591. 'assigned_object_id': site.pk,
  592. 'comments': 'First entry',
  593. },
  594. {
  595. 'assigned_object_type': 'dcim.site',
  596. 'assigned_object_id': site.pk,
  597. 'comments': 'Second entry',
  598. },
  599. {
  600. 'assigned_object_type': 'dcim.site',
  601. 'assigned_object_id': site.pk,
  602. 'comments': 'Third entry',
  603. },
  604. ]
  605. class ConfigContextTest(APIViewTestCases.APIViewTestCase):
  606. model = ConfigContext
  607. brief_fields = ['description', 'display', 'id', 'name', 'url']
  608. create_data = [
  609. {
  610. 'name': 'Config Context 4',
  611. 'data': {'more_foo': True},
  612. },
  613. {
  614. 'name': 'Config Context 5',
  615. 'data': {'more_bar': False},
  616. },
  617. {
  618. 'name': 'Config Context 6',
  619. 'data': {'more_baz': None},
  620. },
  621. ]
  622. bulk_update_data = {
  623. 'description': 'New description',
  624. }
  625. @classmethod
  626. def setUpTestData(cls):
  627. config_contexts = (
  628. ConfigContext(name='Config Context 1', weight=100, data={'foo': 123}),
  629. ConfigContext(name='Config Context 2', weight=200, data={'bar': 456}),
  630. ConfigContext(name='Config Context 3', weight=300, data={'baz': 789}),
  631. )
  632. ConfigContext.objects.bulk_create(config_contexts)
  633. def test_render_configcontext_for_object(self):
  634. """
  635. Test rendering config context data for a device.
  636. """
  637. manufacturer = Manufacturer.objects.create(name='Manufacturer 1', slug='manufacturer-1')
  638. devicetype = DeviceType.objects.create(manufacturer=manufacturer, model='Device Type 1', slug='device-type-1')
  639. role = DeviceRole.objects.create(name='Device Role 1', slug='device-role-1')
  640. site = Site.objects.create(name='Site-1', slug='site-1')
  641. device = Device.objects.create(name='Device 1', device_type=devicetype, role=role, site=site)
  642. # Test default config contexts (created at test setup)
  643. rendered_context = device.get_config_context()
  644. self.assertEqual(rendered_context['foo'], 123)
  645. self.assertEqual(rendered_context['bar'], 456)
  646. self.assertEqual(rendered_context['baz'], 789)
  647. # Add another context specific to the site
  648. configcontext4 = ConfigContext(
  649. name='Config Context 4',
  650. data={'site_data': 'ABC'}
  651. )
  652. configcontext4.save()
  653. configcontext4.sites.add(site)
  654. rendered_context = device.get_config_context()
  655. self.assertEqual(rendered_context['site_data'], 'ABC')
  656. # Override one of the default contexts
  657. configcontext5 = ConfigContext(
  658. name='Config Context 5',
  659. weight=2000,
  660. data={'foo': 999}
  661. )
  662. configcontext5.save()
  663. configcontext5.sites.add(site)
  664. rendered_context = device.get_config_context()
  665. self.assertEqual(rendered_context['foo'], 999)
  666. # Add a context which does NOT match our device and ensure it does not apply
  667. site2 = Site.objects.create(name='Site 2', slug='site-2')
  668. configcontext6 = ConfigContext(
  669. name='Config Context 6',
  670. weight=2000,
  671. data={'bar': 999}
  672. )
  673. configcontext6.save()
  674. configcontext6.sites.add(site2)
  675. rendered_context = device.get_config_context()
  676. self.assertEqual(rendered_context['bar'], 456)
  677. class ConfigTemplateTest(APIViewTestCases.APIViewTestCase):
  678. model = ConfigTemplate
  679. brief_fields = ['description', 'display', 'id', 'name', 'url']
  680. create_data = [
  681. {
  682. 'name': 'Config Template 4',
  683. 'template_code': 'Foo: {{ foo }}',
  684. },
  685. {
  686. 'name': 'Config Template 5',
  687. 'template_code': 'Bar: {{ bar }}',
  688. },
  689. {
  690. 'name': 'Config Template 6',
  691. 'template_code': 'Baz: {{ baz }}',
  692. },
  693. ]
  694. bulk_update_data = {
  695. 'description': 'New description',
  696. }
  697. @classmethod
  698. def setUpTestData(cls):
  699. config_templates = (
  700. ConfigTemplate(
  701. name='Config Template 1',
  702. template_code='Foo: {{ foo }}'
  703. ),
  704. ConfigTemplate(
  705. name='Config Template 2',
  706. template_code='Bar: {{ bar }}'
  707. ),
  708. ConfigTemplate(
  709. name='Config Template 3',
  710. template_code='Baz: {{ baz }}'
  711. ),
  712. )
  713. ConfigTemplate.objects.bulk_create(config_templates)
  714. class ScriptTest(APITestCase):
  715. class TestScriptClass(PythonClass):
  716. class Meta:
  717. name = "Test script"
  718. var1 = StringVar()
  719. var2 = IntegerVar()
  720. var3 = BooleanVar()
  721. def run(self, data, commit=True):
  722. self.log_info(data['var1'])
  723. self.log_success(data['var2'])
  724. self.log_failure(data['var3'])
  725. return 'Script complete'
  726. @classmethod
  727. def setUpTestData(cls):
  728. module = ScriptModule.objects.create(
  729. file_root=ManagedFileRootPathChoices.SCRIPTS,
  730. file_path='/var/tmp/script.py'
  731. )
  732. Script.objects.create(
  733. module=module,
  734. name="Test script",
  735. is_executable=True,
  736. )
  737. def python_class(self):
  738. return self.TestScriptClass
  739. def setUp(self):
  740. super().setUp()
  741. # Monkey-patch the Script model to return our TestScriptClass above
  742. Script.python_class = self.python_class
  743. def test_get_script(self):
  744. module = ScriptModule.objects.get(
  745. file_root=ManagedFileRootPathChoices.SCRIPTS,
  746. file_path='/var/tmp/script.py'
  747. )
  748. script = module.scripts.all().first()
  749. url = reverse('extras-api:script-detail', kwargs={'pk': script.pk})
  750. response = self.client.get(url, **self.header)
  751. self.assertEqual(response.data['name'], self.TestScriptClass.Meta.name)
  752. self.assertEqual(response.data['vars']['var1'], 'StringVar')
  753. self.assertEqual(response.data['vars']['var2'], 'IntegerVar')
  754. self.assertEqual(response.data['vars']['var3'], 'BooleanVar')
  755. class CreatedUpdatedFilterTest(APITestCase):
  756. @classmethod
  757. def setUpTestData(cls):
  758. site1 = Site.objects.create(name='Site 1', slug='site-1')
  759. location1 = Location.objects.create(site=site1, name='Location 1', slug='location-1')
  760. rackrole1 = RackRole.objects.create(name='Rack Role 1', slug='rack-role-1', color='ff0000')
  761. racks = (
  762. Rack(site=site1, location=location1, role=rackrole1, name='Rack 1', u_height=42),
  763. Rack(site=site1, location=location1, role=rackrole1, name='Rack 2', u_height=42)
  764. )
  765. Rack.objects.bulk_create(racks)
  766. # Change the created and last_updated of the second rack
  767. Rack.objects.filter(pk=racks[1].pk).update(
  768. last_updated=make_aware(datetime.datetime(2001, 2, 3, 1, 2, 3, 4)),
  769. created=make_aware(datetime.datetime(2001, 2, 3))
  770. )
  771. def test_get_rack_created(self):
  772. rack2 = Rack.objects.get(name='Rack 2')
  773. self.add_permissions('dcim.view_rack')
  774. url = reverse('dcim-api:rack-list')
  775. response = self.client.get('{}?created=2001-02-03'.format(url), **self.header)
  776. self.assertEqual(response.data['count'], 1)
  777. self.assertEqual(response.data['results'][0]['id'], rack2.pk)
  778. def test_get_rack_created_gte(self):
  779. rack1 = Rack.objects.get(name='Rack 1')
  780. self.add_permissions('dcim.view_rack')
  781. url = reverse('dcim-api:rack-list')
  782. response = self.client.get('{}?created__gte=2001-02-04'.format(url), **self.header)
  783. self.assertEqual(response.data['count'], 1)
  784. self.assertEqual(response.data['results'][0]['id'], rack1.pk)
  785. def test_get_rack_created_lte(self):
  786. rack2 = Rack.objects.get(name='Rack 2')
  787. self.add_permissions('dcim.view_rack')
  788. url = reverse('dcim-api:rack-list')
  789. response = self.client.get('{}?created__lte=2001-02-04'.format(url), **self.header)
  790. self.assertEqual(response.data['count'], 1)
  791. self.assertEqual(response.data['results'][0]['id'], rack2.pk)
  792. def test_get_rack_last_updated(self):
  793. rack2 = Rack.objects.get(name='Rack 2')
  794. self.add_permissions('dcim.view_rack')
  795. url = reverse('dcim-api:rack-list')
  796. response = self.client.get('{}?last_updated=2001-02-03%2001:02:03.000004'.format(url), **self.header)
  797. self.assertEqual(response.data['count'], 1)
  798. self.assertEqual(response.data['results'][0]['id'], rack2.pk)
  799. def test_get_rack_last_updated_gte(self):
  800. rack1 = Rack.objects.get(name='Rack 1')
  801. self.add_permissions('dcim.view_rack')
  802. url = reverse('dcim-api:rack-list')
  803. response = self.client.get('{}?last_updated__gte=2001-02-04%2001:02:03.000004'.format(url), **self.header)
  804. self.assertEqual(response.data['count'], 1)
  805. self.assertEqual(response.data['results'][0]['id'], rack1.pk)
  806. def test_get_rack_last_updated_lte(self):
  807. rack2 = Rack.objects.get(name='Rack 2')
  808. self.add_permissions('dcim.view_rack')
  809. url = reverse('dcim-api:rack-list')
  810. response = self.client.get('{}?last_updated__lte=2001-02-04%2001:02:03.000004'.format(url), **self.header)
  811. self.assertEqual(response.data['count'], 1)
  812. self.assertEqual(response.data['results'][0]['id'], rack2.pk)
  813. class ObjectTypeTest(APITestCase):
  814. def test_list_objects(self):
  815. object_type_count = ObjectType.objects.count()
  816. response = self.client.get(reverse('extras-api:objecttype-list'), **self.header)
  817. self.assertHttpStatus(response, status.HTTP_200_OK)
  818. self.assertEqual(response.data['count'], object_type_count)
  819. def test_get_object(self):
  820. object_type = ObjectType.objects.first()
  821. url = reverse('extras-api:objecttype-detail', kwargs={'pk': object_type.pk})
  822. self.assertHttpStatus(self.client.get(url, **self.header), status.HTTP_200_OK)
  823. class SubscriptionTest(APIViewTestCases.APIViewTestCase):
  824. model = Subscription
  825. brief_fields = ['display', 'id', 'object_id', 'object_type', 'url', 'user']
  826. @classmethod
  827. def setUpTestData(cls):
  828. users = (
  829. User(username='User 1'),
  830. User(username='User 2'),
  831. User(username='User 3'),
  832. User(username='User 4'),
  833. )
  834. User.objects.bulk_create(users)
  835. sites = (
  836. Site(name='Site 1', slug='site-1'),
  837. Site(name='Site 2', slug='site-2'),
  838. Site(name='Site 3', slug='site-3'),
  839. )
  840. Site.objects.bulk_create(sites)
  841. subscriptions = (
  842. Subscription(
  843. object=sites[0],
  844. user=users[0],
  845. ),
  846. Subscription(
  847. object=sites[1],
  848. user=users[1],
  849. ),
  850. Subscription(
  851. object=sites[2],
  852. user=users[2],
  853. ),
  854. )
  855. Subscription.objects.bulk_create(subscriptions)
  856. cls.create_data = [
  857. {
  858. 'object_type': 'dcim.site',
  859. 'object_id': sites[0].pk,
  860. 'user': users[3].pk,
  861. },
  862. {
  863. 'object_type': 'dcim.site',
  864. 'object_id': sites[1].pk,
  865. 'user': users[3].pk,
  866. },
  867. {
  868. 'object_type': 'dcim.site',
  869. 'object_id': sites[2].pk,
  870. 'user': users[3].pk,
  871. },
  872. ]
  873. class NotificationGroupTest(APIViewTestCases.APIViewTestCase):
  874. model = NotificationGroup
  875. brief_fields = ['description', 'display', 'id', 'name', 'url']
  876. create_data = [
  877. {
  878. 'object_types': ['dcim.site'],
  879. 'name': 'Custom Link 4',
  880. 'enabled': True,
  881. 'link_text': 'Link 4',
  882. 'link_url': 'http://example.com/?4',
  883. },
  884. {
  885. 'object_types': ['dcim.site'],
  886. 'name': 'Custom Link 5',
  887. 'enabled': True,
  888. 'link_text': 'Link 5',
  889. 'link_url': 'http://example.com/?5',
  890. },
  891. {
  892. 'object_types': ['dcim.site'],
  893. 'name': 'Custom Link 6',
  894. 'enabled': False,
  895. 'link_text': 'Link 6',
  896. 'link_url': 'http://example.com/?6',
  897. },
  898. ]
  899. bulk_update_data = {
  900. 'description': 'New description',
  901. }
  902. @classmethod
  903. def setUpTestData(cls):
  904. users = (
  905. User(username='User 1'),
  906. User(username='User 2'),
  907. User(username='User 3'),
  908. )
  909. User.objects.bulk_create(users)
  910. groups = (
  911. Group(name='Group 1'),
  912. Group(name='Group 2'),
  913. Group(name='Group 3'),
  914. )
  915. Group.objects.bulk_create(groups)
  916. notification_groups = (
  917. NotificationGroup(name='Notification Group 1'),
  918. NotificationGroup(name='Notification Group 2'),
  919. NotificationGroup(name='Notification Group 3'),
  920. )
  921. NotificationGroup.objects.bulk_create(notification_groups)
  922. for i, notification_group in enumerate(notification_groups):
  923. notification_group.users.add(users[i])
  924. notification_group.groups.add(groups[i])
  925. cls.create_data = [
  926. {
  927. 'name': 'Notification Group 4',
  928. 'description': 'Foo',
  929. 'users': [users[0].pk],
  930. 'groups': [groups[0].pk],
  931. },
  932. {
  933. 'name': 'Notification Group 5',
  934. 'description': 'Bar',
  935. 'users': [users[1].pk],
  936. 'groups': [groups[1].pk],
  937. },
  938. {
  939. 'name': 'Notification Group 6',
  940. 'description': 'Baz',
  941. 'users': [users[2].pk],
  942. 'groups': [groups[2].pk],
  943. },
  944. ]
  945. class NotificationTest(APIViewTestCases.APIViewTestCase):
  946. model = Notification
  947. brief_fields = ['display', 'event_type', 'id', 'object_id', 'object_type', 'read', 'url', 'user']
  948. @classmethod
  949. def setUpTestData(cls):
  950. users = (
  951. User(username='User 1'),
  952. User(username='User 2'),
  953. User(username='User 3'),
  954. User(username='User 4'),
  955. )
  956. User.objects.bulk_create(users)
  957. sites = (
  958. Site(name='Site 1', slug='site-1'),
  959. Site(name='Site 2', slug='site-2'),
  960. Site(name='Site 3', slug='site-3'),
  961. )
  962. Site.objects.bulk_create(sites)
  963. notifications = (
  964. Notification(
  965. object=sites[0],
  966. event_type=OBJECT_CREATED,
  967. user=users[0],
  968. ),
  969. Notification(
  970. object=sites[1],
  971. event_type=OBJECT_UPDATED,
  972. user=users[1],
  973. ),
  974. Notification(
  975. object=sites[2],
  976. event_type=OBJECT_DELETED,
  977. user=users[2],
  978. ),
  979. )
  980. Notification.objects.bulk_create(notifications)
  981. cls.create_data = [
  982. {
  983. 'object_type': 'dcim.site',
  984. 'object_id': sites[0].pk,
  985. 'user': users[3].pk,
  986. 'event_type': OBJECT_CREATED,
  987. },
  988. {
  989. 'object_type': 'dcim.site',
  990. 'object_id': sites[1].pk,
  991. 'user': users[3].pk,
  992. 'event_type': OBJECT_UPDATED,
  993. },
  994. {
  995. 'object_type': 'dcim.site',
  996. 'object_id': sites[2].pk,
  997. 'user': users[3].pk,
  998. 'event_type': OBJECT_DELETED,
  999. },
  1000. ]