test_api.py 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121
  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. },
  441. ]
  442. bulk_update_data = {
  443. 'description': 'New description',
  444. }
  445. @classmethod
  446. def setUpTestData(cls):
  447. export_templates = (
  448. ExportTemplate(
  449. name='Export Template 1',
  450. template_code='{% for obj in queryset %}{{ obj.name }}\n{% endfor %}'
  451. ),
  452. ExportTemplate(
  453. name='Export Template 2',
  454. template_code='{% for obj in queryset %}{{ obj.name }}\n{% endfor %}'
  455. ),
  456. ExportTemplate(
  457. name='Export Template 3',
  458. template_code='{% for obj in queryset %}{{ obj.name }}\n{% endfor %}'
  459. ),
  460. )
  461. ExportTemplate.objects.bulk_create(export_templates)
  462. for et in export_templates:
  463. et.object_types.set([ObjectType.objects.get_for_model(Device)])
  464. class TagTest(APIViewTestCases.APIViewTestCase):
  465. model = Tag
  466. brief_fields = ['color', 'description', 'display', 'id', 'name', 'slug', 'url']
  467. create_data = [
  468. {
  469. 'name': 'Tag 4',
  470. 'slug': 'tag-4',
  471. 'weight': 1000,
  472. },
  473. {
  474. 'name': 'Tag 5',
  475. 'slug': 'tag-5',
  476. },
  477. {
  478. 'name': 'Tag 6',
  479. 'slug': 'tag-6',
  480. },
  481. ]
  482. bulk_update_data = {
  483. 'description': 'New description',
  484. }
  485. @classmethod
  486. def setUpTestData(cls):
  487. tags = (
  488. Tag(name='Tag 1', slug='tag-1'),
  489. Tag(name='Tag 2', slug='tag-2'),
  490. Tag(name='Tag 3', slug='tag-3', weight=26),
  491. )
  492. Tag.objects.bulk_create(tags)
  493. class TaggedItemTest(
  494. APIViewTestCases.GetObjectViewTestCase,
  495. APIViewTestCases.ListObjectsViewTestCase
  496. ):
  497. model = TaggedItem
  498. brief_fields = ['display', 'id', 'object', 'object_id', 'object_type', 'tag', 'url']
  499. @classmethod
  500. def setUpTestData(cls):
  501. tags = (
  502. Tag(name='Tag 1', slug='tag-1'),
  503. Tag(name='Tag 2', slug='tag-2'),
  504. Tag(name='Tag 3', slug='tag-3'),
  505. )
  506. Tag.objects.bulk_create(tags)
  507. sites = (
  508. Site(name='Site 1', slug='site-1'),
  509. Site(name='Site 2', slug='site-2'),
  510. Site(name='Site 3', slug='site-3'),
  511. )
  512. Site.objects.bulk_create(sites)
  513. sites[0].tags.set([tags[0], tags[1]])
  514. sites[1].tags.set([tags[1], tags[2]])
  515. sites[2].tags.set([tags[2], tags[0]])
  516. # TODO: Standardize to APIViewTestCase (needs create & update tests)
  517. class ImageAttachmentTest(
  518. APIViewTestCases.GetObjectViewTestCase,
  519. APIViewTestCases.ListObjectsViewTestCase,
  520. APIViewTestCases.DeleteObjectViewTestCase,
  521. APIViewTestCases.GraphQLTestCase
  522. ):
  523. model = ImageAttachment
  524. brief_fields = ['display', 'id', 'image', 'name', 'url']
  525. @classmethod
  526. def setUpTestData(cls):
  527. ct = ContentType.objects.get_for_model(Site)
  528. site = Site.objects.create(name='Site 1', slug='site-1')
  529. image_attachments = (
  530. ImageAttachment(
  531. object_type=ct,
  532. object_id=site.pk,
  533. name='Image Attachment 1',
  534. image='http://example.com/image1.png',
  535. image_height=100,
  536. image_width=100
  537. ),
  538. ImageAttachment(
  539. object_type=ct,
  540. object_id=site.pk,
  541. name='Image Attachment 2',
  542. image='http://example.com/image2.png',
  543. image_height=100,
  544. image_width=100
  545. ),
  546. ImageAttachment(
  547. object_type=ct,
  548. object_id=site.pk,
  549. name='Image Attachment 3',
  550. image='http://example.com/image3.png',
  551. image_height=100,
  552. image_width=100
  553. )
  554. )
  555. ImageAttachment.objects.bulk_create(image_attachments)
  556. class JournalEntryTest(APIViewTestCases.APIViewTestCase):
  557. model = JournalEntry
  558. brief_fields = ['created', 'display', 'id', 'url']
  559. bulk_update_data = {
  560. 'comments': 'Overwritten',
  561. }
  562. @classmethod
  563. def setUpTestData(cls):
  564. user = User.objects.first()
  565. site = Site.objects.create(name='Site 1', slug='site-1')
  566. journal_entries = (
  567. JournalEntry(
  568. created_by=user,
  569. assigned_object=site,
  570. comments='Fourth entry',
  571. ),
  572. JournalEntry(
  573. created_by=user,
  574. assigned_object=site,
  575. comments='Fifth entry',
  576. ),
  577. JournalEntry(
  578. created_by=user,
  579. assigned_object=site,
  580. comments='Sixth entry',
  581. ),
  582. )
  583. JournalEntry.objects.bulk_create(journal_entries)
  584. cls.create_data = [
  585. {
  586. 'assigned_object_type': 'dcim.site',
  587. 'assigned_object_id': site.pk,
  588. 'comments': 'First entry',
  589. },
  590. {
  591. 'assigned_object_type': 'dcim.site',
  592. 'assigned_object_id': site.pk,
  593. 'comments': 'Second entry',
  594. },
  595. {
  596. 'assigned_object_type': 'dcim.site',
  597. 'assigned_object_id': site.pk,
  598. 'comments': 'Third entry',
  599. },
  600. ]
  601. class ConfigContextTest(APIViewTestCases.APIViewTestCase):
  602. model = ConfigContext
  603. brief_fields = ['description', 'display', 'id', 'name', 'url']
  604. create_data = [
  605. {
  606. 'name': 'Config Context 4',
  607. 'data': {'more_foo': True},
  608. },
  609. {
  610. 'name': 'Config Context 5',
  611. 'data': {'more_bar': False},
  612. },
  613. {
  614. 'name': 'Config Context 6',
  615. 'data': {'more_baz': None},
  616. },
  617. ]
  618. bulk_update_data = {
  619. 'description': 'New description',
  620. }
  621. @classmethod
  622. def setUpTestData(cls):
  623. config_contexts = (
  624. ConfigContext(name='Config Context 1', weight=100, data={'foo': 123}),
  625. ConfigContext(name='Config Context 2', weight=200, data={'bar': 456}),
  626. ConfigContext(name='Config Context 3', weight=300, data={'baz': 789}),
  627. )
  628. ConfigContext.objects.bulk_create(config_contexts)
  629. def test_render_configcontext_for_object(self):
  630. """
  631. Test rendering config context data for a device.
  632. """
  633. manufacturer = Manufacturer.objects.create(name='Manufacturer 1', slug='manufacturer-1')
  634. devicetype = DeviceType.objects.create(manufacturer=manufacturer, model='Device Type 1', slug='device-type-1')
  635. role = DeviceRole.objects.create(name='Device Role 1', slug='device-role-1')
  636. site = Site.objects.create(name='Site-1', slug='site-1')
  637. device = Device.objects.create(name='Device 1', device_type=devicetype, role=role, site=site)
  638. # Test default config contexts (created at test setup)
  639. rendered_context = device.get_config_context()
  640. self.assertEqual(rendered_context['foo'], 123)
  641. self.assertEqual(rendered_context['bar'], 456)
  642. self.assertEqual(rendered_context['baz'], 789)
  643. # Add another context specific to the site
  644. configcontext4 = ConfigContext(
  645. name='Config Context 4',
  646. data={'site_data': 'ABC'}
  647. )
  648. configcontext4.save()
  649. configcontext4.sites.add(site)
  650. rendered_context = device.get_config_context()
  651. self.assertEqual(rendered_context['site_data'], 'ABC')
  652. # Override one of the default contexts
  653. configcontext5 = ConfigContext(
  654. name='Config Context 5',
  655. weight=2000,
  656. data={'foo': 999}
  657. )
  658. configcontext5.save()
  659. configcontext5.sites.add(site)
  660. rendered_context = device.get_config_context()
  661. self.assertEqual(rendered_context['foo'], 999)
  662. # Add a context which does NOT match our device and ensure it does not apply
  663. site2 = Site.objects.create(name='Site 2', slug='site-2')
  664. configcontext6 = ConfigContext(
  665. name='Config Context 6',
  666. weight=2000,
  667. data={'bar': 999}
  668. )
  669. configcontext6.save()
  670. configcontext6.sites.add(site2)
  671. rendered_context = device.get_config_context()
  672. self.assertEqual(rendered_context['bar'], 456)
  673. class ConfigTemplateTest(APIViewTestCases.APIViewTestCase):
  674. model = ConfigTemplate
  675. brief_fields = ['description', 'display', 'id', 'name', 'url']
  676. create_data = [
  677. {
  678. 'name': 'Config Template 4',
  679. 'template_code': 'Foo: {{ foo }}',
  680. },
  681. {
  682. 'name': 'Config Template 5',
  683. 'template_code': 'Bar: {{ bar }}',
  684. },
  685. {
  686. 'name': 'Config Template 6',
  687. 'template_code': 'Baz: {{ baz }}',
  688. },
  689. ]
  690. bulk_update_data = {
  691. 'description': 'New description',
  692. }
  693. @classmethod
  694. def setUpTestData(cls):
  695. config_templates = (
  696. ConfigTemplate(
  697. name='Config Template 1',
  698. template_code='Foo: {{ foo }}'
  699. ),
  700. ConfigTemplate(
  701. name='Config Template 2',
  702. template_code='Bar: {{ bar }}'
  703. ),
  704. ConfigTemplate(
  705. name='Config Template 3',
  706. template_code='Baz: {{ baz }}'
  707. ),
  708. )
  709. ConfigTemplate.objects.bulk_create(config_templates)
  710. class ScriptTest(APITestCase):
  711. class TestScriptClass(PythonClass):
  712. class Meta:
  713. name = "Test script"
  714. var1 = StringVar()
  715. var2 = IntegerVar()
  716. var3 = BooleanVar()
  717. def run(self, data, commit=True):
  718. self.log_info(data['var1'])
  719. self.log_success(data['var2'])
  720. self.log_failure(data['var3'])
  721. return 'Script complete'
  722. @classmethod
  723. def setUpTestData(cls):
  724. module = ScriptModule.objects.create(
  725. file_root=ManagedFileRootPathChoices.SCRIPTS,
  726. file_path='/var/tmp/script.py'
  727. )
  728. Script.objects.create(
  729. module=module,
  730. name="Test script",
  731. is_executable=True,
  732. )
  733. def python_class(self):
  734. return self.TestScriptClass
  735. def setUp(self):
  736. super().setUp()
  737. # Monkey-patch the Script model to return our TestScriptClass above
  738. Script.python_class = self.python_class
  739. def test_get_script(self):
  740. module = ScriptModule.objects.get(
  741. file_root=ManagedFileRootPathChoices.SCRIPTS,
  742. file_path='/var/tmp/script.py'
  743. )
  744. script = module.scripts.all().first()
  745. url = reverse('extras-api:script-detail', kwargs={'pk': script.pk})
  746. response = self.client.get(url, **self.header)
  747. self.assertEqual(response.data['name'], self.TestScriptClass.Meta.name)
  748. self.assertEqual(response.data['vars']['var1'], 'StringVar')
  749. self.assertEqual(response.data['vars']['var2'], 'IntegerVar')
  750. self.assertEqual(response.data['vars']['var3'], 'BooleanVar')
  751. class CreatedUpdatedFilterTest(APITestCase):
  752. @classmethod
  753. def setUpTestData(cls):
  754. site1 = Site.objects.create(name='Site 1', slug='site-1')
  755. location1 = Location.objects.create(site=site1, name='Location 1', slug='location-1')
  756. rackrole1 = RackRole.objects.create(name='Rack Role 1', slug='rack-role-1', color='ff0000')
  757. racks = (
  758. Rack(site=site1, location=location1, role=rackrole1, name='Rack 1', u_height=42),
  759. Rack(site=site1, location=location1, role=rackrole1, name='Rack 2', u_height=42)
  760. )
  761. Rack.objects.bulk_create(racks)
  762. # Change the created and last_updated of the second rack
  763. Rack.objects.filter(pk=racks[1].pk).update(
  764. last_updated=make_aware(datetime.datetime(2001, 2, 3, 1, 2, 3, 4)),
  765. created=make_aware(datetime.datetime(2001, 2, 3))
  766. )
  767. def test_get_rack_created(self):
  768. rack2 = Rack.objects.get(name='Rack 2')
  769. self.add_permissions('dcim.view_rack')
  770. url = reverse('dcim-api:rack-list')
  771. response = self.client.get('{}?created=2001-02-03'.format(url), **self.header)
  772. self.assertEqual(response.data['count'], 1)
  773. self.assertEqual(response.data['results'][0]['id'], rack2.pk)
  774. def test_get_rack_created_gte(self):
  775. rack1 = Rack.objects.get(name='Rack 1')
  776. self.add_permissions('dcim.view_rack')
  777. url = reverse('dcim-api:rack-list')
  778. response = self.client.get('{}?created__gte=2001-02-04'.format(url), **self.header)
  779. self.assertEqual(response.data['count'], 1)
  780. self.assertEqual(response.data['results'][0]['id'], rack1.pk)
  781. def test_get_rack_created_lte(self):
  782. rack2 = Rack.objects.get(name='Rack 2')
  783. self.add_permissions('dcim.view_rack')
  784. url = reverse('dcim-api:rack-list')
  785. response = self.client.get('{}?created__lte=2001-02-04'.format(url), **self.header)
  786. self.assertEqual(response.data['count'], 1)
  787. self.assertEqual(response.data['results'][0]['id'], rack2.pk)
  788. def test_get_rack_last_updated(self):
  789. rack2 = Rack.objects.get(name='Rack 2')
  790. self.add_permissions('dcim.view_rack')
  791. url = reverse('dcim-api:rack-list')
  792. response = self.client.get('{}?last_updated=2001-02-03%2001:02:03.000004'.format(url), **self.header)
  793. self.assertEqual(response.data['count'], 1)
  794. self.assertEqual(response.data['results'][0]['id'], rack2.pk)
  795. def test_get_rack_last_updated_gte(self):
  796. rack1 = Rack.objects.get(name='Rack 1')
  797. self.add_permissions('dcim.view_rack')
  798. url = reverse('dcim-api:rack-list')
  799. response = self.client.get('{}?last_updated__gte=2001-02-04%2001:02:03.000004'.format(url), **self.header)
  800. self.assertEqual(response.data['count'], 1)
  801. self.assertEqual(response.data['results'][0]['id'], rack1.pk)
  802. def test_get_rack_last_updated_lte(self):
  803. rack2 = Rack.objects.get(name='Rack 2')
  804. self.add_permissions('dcim.view_rack')
  805. url = reverse('dcim-api:rack-list')
  806. response = self.client.get('{}?last_updated__lte=2001-02-04%2001:02:03.000004'.format(url), **self.header)
  807. self.assertEqual(response.data['count'], 1)
  808. self.assertEqual(response.data['results'][0]['id'], rack2.pk)
  809. class ObjectTypeTest(APITestCase):
  810. def test_list_objects(self):
  811. object_type_count = ObjectType.objects.count()
  812. response = self.client.get(reverse('extras-api:objecttype-list'), **self.header)
  813. self.assertHttpStatus(response, status.HTTP_200_OK)
  814. self.assertEqual(response.data['count'], object_type_count)
  815. def test_get_object(self):
  816. object_type = ObjectType.objects.first()
  817. url = reverse('extras-api:objecttype-detail', kwargs={'pk': object_type.pk})
  818. self.assertHttpStatus(self.client.get(url, **self.header), status.HTTP_200_OK)
  819. class SubscriptionTest(APIViewTestCases.APIViewTestCase):
  820. model = Subscription
  821. brief_fields = ['display', 'id', 'object_id', 'object_type', 'url', 'user']
  822. @classmethod
  823. def setUpTestData(cls):
  824. users = (
  825. User(username='User 1'),
  826. User(username='User 2'),
  827. User(username='User 3'),
  828. User(username='User 4'),
  829. )
  830. User.objects.bulk_create(users)
  831. sites = (
  832. Site(name='Site 1', slug='site-1'),
  833. Site(name='Site 2', slug='site-2'),
  834. Site(name='Site 3', slug='site-3'),
  835. )
  836. Site.objects.bulk_create(sites)
  837. subscriptions = (
  838. Subscription(
  839. object=sites[0],
  840. user=users[0],
  841. ),
  842. Subscription(
  843. object=sites[1],
  844. user=users[1],
  845. ),
  846. Subscription(
  847. object=sites[2],
  848. user=users[2],
  849. ),
  850. )
  851. Subscription.objects.bulk_create(subscriptions)
  852. cls.create_data = [
  853. {
  854. 'object_type': 'dcim.site',
  855. 'object_id': sites[0].pk,
  856. 'user': users[3].pk,
  857. },
  858. {
  859. 'object_type': 'dcim.site',
  860. 'object_id': sites[1].pk,
  861. 'user': users[3].pk,
  862. },
  863. {
  864. 'object_type': 'dcim.site',
  865. 'object_id': sites[2].pk,
  866. 'user': users[3].pk,
  867. },
  868. ]
  869. class NotificationGroupTest(APIViewTestCases.APIViewTestCase):
  870. model = NotificationGroup
  871. brief_fields = ['description', 'display', 'id', 'name', 'url']
  872. create_data = [
  873. {
  874. 'object_types': ['dcim.site'],
  875. 'name': 'Custom Link 4',
  876. 'enabled': True,
  877. 'link_text': 'Link 4',
  878. 'link_url': 'http://example.com/?4',
  879. },
  880. {
  881. 'object_types': ['dcim.site'],
  882. 'name': 'Custom Link 5',
  883. 'enabled': True,
  884. 'link_text': 'Link 5',
  885. 'link_url': 'http://example.com/?5',
  886. },
  887. {
  888. 'object_types': ['dcim.site'],
  889. 'name': 'Custom Link 6',
  890. 'enabled': False,
  891. 'link_text': 'Link 6',
  892. 'link_url': 'http://example.com/?6',
  893. },
  894. ]
  895. bulk_update_data = {
  896. 'description': 'New description',
  897. }
  898. @classmethod
  899. def setUpTestData(cls):
  900. users = (
  901. User(username='User 1'),
  902. User(username='User 2'),
  903. User(username='User 3'),
  904. )
  905. User.objects.bulk_create(users)
  906. groups = (
  907. Group(name='Group 1'),
  908. Group(name='Group 2'),
  909. Group(name='Group 3'),
  910. )
  911. Group.objects.bulk_create(groups)
  912. notification_groups = (
  913. NotificationGroup(name='Notification Group 1'),
  914. NotificationGroup(name='Notification Group 2'),
  915. NotificationGroup(name='Notification Group 3'),
  916. )
  917. NotificationGroup.objects.bulk_create(notification_groups)
  918. for i, notification_group in enumerate(notification_groups):
  919. notification_group.users.add(users[i])
  920. notification_group.groups.add(groups[i])
  921. cls.create_data = [
  922. {
  923. 'name': 'Notification Group 4',
  924. 'description': 'Foo',
  925. 'users': [users[0].pk],
  926. 'groups': [groups[0].pk],
  927. },
  928. {
  929. 'name': 'Notification Group 5',
  930. 'description': 'Bar',
  931. 'users': [users[1].pk],
  932. 'groups': [groups[1].pk],
  933. },
  934. {
  935. 'name': 'Notification Group 6',
  936. 'description': 'Baz',
  937. 'users': [users[2].pk],
  938. 'groups': [groups[2].pk],
  939. },
  940. ]
  941. class NotificationTest(APIViewTestCases.APIViewTestCase):
  942. model = Notification
  943. brief_fields = ['display', 'event_type', 'id', 'object_id', 'object_type', 'read', 'url', 'user']
  944. @classmethod
  945. def setUpTestData(cls):
  946. users = (
  947. User(username='User 1'),
  948. User(username='User 2'),
  949. User(username='User 3'),
  950. User(username='User 4'),
  951. )
  952. User.objects.bulk_create(users)
  953. sites = (
  954. Site(name='Site 1', slug='site-1'),
  955. Site(name='Site 2', slug='site-2'),
  956. Site(name='Site 3', slug='site-3'),
  957. )
  958. Site.objects.bulk_create(sites)
  959. notifications = (
  960. Notification(
  961. object=sites[0],
  962. event_type=OBJECT_CREATED,
  963. user=users[0],
  964. ),
  965. Notification(
  966. object=sites[1],
  967. event_type=OBJECT_UPDATED,
  968. user=users[1],
  969. ),
  970. Notification(
  971. object=sites[2],
  972. event_type=OBJECT_DELETED,
  973. user=users[2],
  974. ),
  975. )
  976. Notification.objects.bulk_create(notifications)
  977. cls.create_data = [
  978. {
  979. 'object_type': 'dcim.site',
  980. 'object_id': sites[0].pk,
  981. 'user': users[3].pk,
  982. 'event_type': OBJECT_CREATED,
  983. },
  984. {
  985. 'object_type': 'dcim.site',
  986. 'object_id': sites[1].pk,
  987. 'user': users[3].pk,
  988. 'event_type': OBJECT_UPDATED,
  989. },
  990. {
  991. 'object_type': 'dcim.site',
  992. 'object_id': sites[2].pk,
  993. 'user': users[3].pk,
  994. 'event_type': OBJECT_DELETED,
  995. },
  996. ]