2
0

test_customfields.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  1. from datetime import date
  2. from django.contrib.contenttypes.models import ContentType
  3. from django.test import Client, TestCase
  4. from django.urls import reverse
  5. from rest_framework import status
  6. from dcim.models import Site
  7. from extras.choices import *
  8. from extras.models import CustomField, CustomFieldValue, CustomFieldChoice
  9. from utilities.testing import APITestCase, create_test_user
  10. from virtualization.models import VirtualMachine
  11. class CustomFieldTest(TestCase):
  12. def setUp(self):
  13. Site.objects.bulk_create([
  14. Site(name='Site A', slug='site-a'),
  15. Site(name='Site B', slug='site-b'),
  16. Site(name='Site C', slug='site-c'),
  17. ])
  18. def test_simple_fields(self):
  19. DATA = (
  20. {'field_type': CustomFieldTypeChoices.TYPE_TEXT, 'field_value': 'Foobar!', 'empty_value': ''},
  21. {'field_type': CustomFieldTypeChoices.TYPE_INTEGER, 'field_value': 0, 'empty_value': None},
  22. {'field_type': CustomFieldTypeChoices.TYPE_INTEGER, 'field_value': 42, 'empty_value': None},
  23. {'field_type': CustomFieldTypeChoices.TYPE_BOOLEAN, 'field_value': True, 'empty_value': None},
  24. {'field_type': CustomFieldTypeChoices.TYPE_BOOLEAN, 'field_value': False, 'empty_value': None},
  25. {'field_type': CustomFieldTypeChoices.TYPE_DATE, 'field_value': date(2016, 6, 23), 'empty_value': None},
  26. {'field_type': CustomFieldTypeChoices.TYPE_URL, 'field_value': 'http://example.com/', 'empty_value': ''},
  27. )
  28. obj_type = ContentType.objects.get_for_model(Site)
  29. for data in DATA:
  30. # Create a custom field
  31. cf = CustomField(type=data['field_type'], name='my_field', required=False)
  32. cf.save()
  33. cf.obj_type.set([obj_type])
  34. cf.save()
  35. # Assign a value to the first Site
  36. site = Site.objects.first()
  37. cfv = CustomFieldValue(field=cf, obj_type=obj_type, obj_id=site.id)
  38. cfv.value = data['field_value']
  39. cfv.save()
  40. # Retrieve the stored value
  41. cfv = CustomFieldValue.objects.filter(obj_type=obj_type, obj_id=site.pk).first()
  42. self.assertEqual(cfv.value, data['field_value'])
  43. # Delete the stored value
  44. cfv.value = data['empty_value']
  45. cfv.save()
  46. self.assertEqual(CustomFieldValue.objects.filter(obj_type=obj_type, obj_id=site.pk).count(), 0)
  47. # Delete the custom field
  48. cf.delete()
  49. def test_select_field(self):
  50. obj_type = ContentType.objects.get_for_model(Site)
  51. # Create a custom field
  52. cf = CustomField(type=CustomFieldTypeChoices.TYPE_SELECT, name='my_field', required=False)
  53. cf.save()
  54. cf.obj_type.set([obj_type])
  55. cf.save()
  56. # Create some choices for the field
  57. CustomFieldChoice.objects.bulk_create([
  58. CustomFieldChoice(field=cf, value='Option A'),
  59. CustomFieldChoice(field=cf, value='Option B'),
  60. CustomFieldChoice(field=cf, value='Option C'),
  61. ])
  62. # Assign a value to the first Site
  63. site = Site.objects.first()
  64. cfv = CustomFieldValue(field=cf, obj_type=obj_type, obj_id=site.id)
  65. cfv.value = cf.choices.first()
  66. cfv.save()
  67. # Retrieve the stored value
  68. cfv = CustomFieldValue.objects.filter(obj_type=obj_type, obj_id=site.pk).first()
  69. self.assertEqual(str(cfv.value), 'Option A')
  70. # Delete the stored value
  71. cfv.value = None
  72. cfv.save()
  73. self.assertEqual(CustomFieldValue.objects.filter(obj_type=obj_type, obj_id=site.pk).count(), 0)
  74. # Delete the custom field
  75. cf.delete()
  76. class CustomFieldAPITest(APITestCase):
  77. def setUp(self):
  78. super().setUp()
  79. content_type = ContentType.objects.get_for_model(Site)
  80. # Text custom field
  81. self.cf_text = CustomField(type=CustomFieldTypeChoices.TYPE_TEXT, name='magic_word')
  82. self.cf_text.save()
  83. self.cf_text.obj_type.set([content_type])
  84. self.cf_text.save()
  85. # Integer custom field
  86. self.cf_integer = CustomField(type=CustomFieldTypeChoices.TYPE_INTEGER, name='magic_number')
  87. self.cf_integer.save()
  88. self.cf_integer.obj_type.set([content_type])
  89. self.cf_integer.save()
  90. # Boolean custom field
  91. self.cf_boolean = CustomField(type=CustomFieldTypeChoices.TYPE_BOOLEAN, name='is_magic')
  92. self.cf_boolean.save()
  93. self.cf_boolean.obj_type.set([content_type])
  94. self.cf_boolean.save()
  95. # Date custom field
  96. self.cf_date = CustomField(type=CustomFieldTypeChoices.TYPE_DATE, name='magic_date')
  97. self.cf_date.save()
  98. self.cf_date.obj_type.set([content_type])
  99. self.cf_date.save()
  100. # URL custom field
  101. self.cf_url = CustomField(type=CustomFieldTypeChoices.TYPE_URL, name='magic_url')
  102. self.cf_url.save()
  103. self.cf_url.obj_type.set([content_type])
  104. self.cf_url.save()
  105. # Select custom field
  106. self.cf_select = CustomField(type=CustomFieldTypeChoices.TYPE_SELECT, name='magic_choice')
  107. self.cf_select.save()
  108. self.cf_select.obj_type.set([content_type])
  109. self.cf_select.save()
  110. self.cf_select_choice1 = CustomFieldChoice(field=self.cf_select, value='Foo')
  111. self.cf_select_choice1.save()
  112. self.cf_select_choice2 = CustomFieldChoice(field=self.cf_select, value='Bar')
  113. self.cf_select_choice2.save()
  114. self.cf_select_choice3 = CustomFieldChoice(field=self.cf_select, value='Baz')
  115. self.cf_select_choice3.save()
  116. self.site = Site.objects.create(name='Test Site 1', slug='test-site-1')
  117. def test_get_obj_without_custom_fields(self):
  118. url = reverse('dcim-api:site-detail', kwargs={'pk': self.site.pk})
  119. response = self.client.get(url, **self.header)
  120. self.assertEqual(response.data['name'], self.site.name)
  121. self.assertEqual(response.data['custom_fields'], {
  122. 'magic_word': None,
  123. 'magic_number': None,
  124. 'is_magic': None,
  125. 'magic_date': None,
  126. 'magic_url': None,
  127. 'magic_choice': None,
  128. })
  129. def test_get_obj_with_custom_fields(self):
  130. CUSTOM_FIELD_VALUES = [
  131. (self.cf_text, 'Test string'),
  132. (self.cf_integer, 1234),
  133. (self.cf_boolean, True),
  134. (self.cf_date, date(2016, 6, 23)),
  135. (self.cf_url, 'http://example.com/'),
  136. (self.cf_select, self.cf_select_choice1.pk),
  137. ]
  138. for field, value in CUSTOM_FIELD_VALUES:
  139. cfv = CustomFieldValue(field=field, obj=self.site)
  140. cfv.value = value
  141. cfv.save()
  142. url = reverse('dcim-api:site-detail', kwargs={'pk': self.site.pk})
  143. response = self.client.get(url, **self.header)
  144. self.assertEqual(response.data['name'], self.site.name)
  145. self.assertEqual(response.data['custom_fields'].get('magic_word'), CUSTOM_FIELD_VALUES[0][1])
  146. self.assertEqual(response.data['custom_fields'].get('magic_number'), CUSTOM_FIELD_VALUES[1][1])
  147. self.assertEqual(response.data['custom_fields'].get('is_magic'), CUSTOM_FIELD_VALUES[2][1])
  148. self.assertEqual(response.data['custom_fields'].get('magic_date'), CUSTOM_FIELD_VALUES[3][1])
  149. self.assertEqual(response.data['custom_fields'].get('magic_url'), CUSTOM_FIELD_VALUES[4][1])
  150. self.assertEqual(response.data['custom_fields'].get('magic_choice'), {
  151. 'value': self.cf_select_choice1.pk, 'label': 'Foo'
  152. })
  153. def test_set_custom_field_text(self):
  154. data = {
  155. 'name': 'Test Site 1',
  156. 'slug': 'test-site-1',
  157. 'custom_fields': {
  158. 'magic_word': 'Foo bar baz',
  159. }
  160. }
  161. url = reverse('dcim-api:site-detail', kwargs={'pk': self.site.pk})
  162. response = self.client.put(url, data, format='json', **self.header)
  163. self.assertHttpStatus(response, status.HTTP_200_OK)
  164. self.assertEqual(response.data['custom_fields'].get('magic_word'), data['custom_fields']['magic_word'])
  165. cfv = self.site.custom_field_values.get(field=self.cf_text)
  166. self.assertEqual(cfv.value, data['custom_fields']['magic_word'])
  167. def test_set_custom_field_integer(self):
  168. data = {
  169. 'name': 'Test Site 1',
  170. 'slug': 'test-site-1',
  171. 'custom_fields': {
  172. 'magic_number': 42,
  173. }
  174. }
  175. url = reverse('dcim-api:site-detail', kwargs={'pk': self.site.pk})
  176. response = self.client.put(url, data, format='json', **self.header)
  177. self.assertHttpStatus(response, status.HTTP_200_OK)
  178. self.assertEqual(response.data['custom_fields'].get('magic_number'), data['custom_fields']['magic_number'])
  179. cfv = self.site.custom_field_values.get(field=self.cf_integer)
  180. self.assertEqual(cfv.value, data['custom_fields']['magic_number'])
  181. def test_set_custom_field_boolean(self):
  182. data = {
  183. 'name': 'Test Site 1',
  184. 'slug': 'test-site-1',
  185. 'custom_fields': {
  186. 'is_magic': 0,
  187. }
  188. }
  189. url = reverse('dcim-api:site-detail', kwargs={'pk': self.site.pk})
  190. response = self.client.put(url, data, format='json', **self.header)
  191. self.assertHttpStatus(response, status.HTTP_200_OK)
  192. self.assertEqual(response.data['custom_fields'].get('is_magic'), data['custom_fields']['is_magic'])
  193. cfv = self.site.custom_field_values.get(field=self.cf_boolean)
  194. self.assertEqual(cfv.value, data['custom_fields']['is_magic'])
  195. def test_set_custom_field_date(self):
  196. data = {
  197. 'name': 'Test Site 1',
  198. 'slug': 'test-site-1',
  199. 'custom_fields': {
  200. 'magic_date': '2017-04-25',
  201. }
  202. }
  203. url = reverse('dcim-api:site-detail', kwargs={'pk': self.site.pk})
  204. response = self.client.put(url, data, format='json', **self.header)
  205. self.assertHttpStatus(response, status.HTTP_200_OK)
  206. self.assertEqual(response.data['custom_fields'].get('magic_date'), data['custom_fields']['magic_date'])
  207. cfv = self.site.custom_field_values.get(field=self.cf_date)
  208. self.assertEqual(cfv.value.isoformat(), data['custom_fields']['magic_date'])
  209. def test_set_custom_field_url(self):
  210. data = {
  211. 'name': 'Test Site 1',
  212. 'slug': 'test-site-1',
  213. 'custom_fields': {
  214. 'magic_url': 'http://example.com/2/',
  215. }
  216. }
  217. url = reverse('dcim-api:site-detail', kwargs={'pk': self.site.pk})
  218. response = self.client.put(url, data, format='json', **self.header)
  219. self.assertHttpStatus(response, status.HTTP_200_OK)
  220. self.assertEqual(response.data['custom_fields'].get('magic_url'), data['custom_fields']['magic_url'])
  221. cfv = self.site.custom_field_values.get(field=self.cf_url)
  222. self.assertEqual(cfv.value, data['custom_fields']['magic_url'])
  223. def test_set_custom_field_select(self):
  224. data = {
  225. 'name': 'Test Site 1',
  226. 'slug': 'test-site-1',
  227. 'custom_fields': {
  228. 'magic_choice': self.cf_select_choice2.pk,
  229. }
  230. }
  231. url = reverse('dcim-api:site-detail', kwargs={'pk': self.site.pk})
  232. response = self.client.put(url, data, format='json', **self.header)
  233. self.assertHttpStatus(response, status.HTTP_200_OK)
  234. self.assertEqual(response.data['custom_fields'].get('magic_choice'), data['custom_fields']['magic_choice'])
  235. cfv = self.site.custom_field_values.get(field=self.cf_select)
  236. self.assertEqual(cfv.value.pk, data['custom_fields']['magic_choice'])
  237. def test_set_custom_field_defaults(self):
  238. """
  239. Create a new object with no custom field data. Custom field values should be created using the custom fields'
  240. default values.
  241. """
  242. CUSTOM_FIELD_DEFAULTS = {
  243. 'magic_word': 'foobar',
  244. 'magic_number': '123',
  245. 'is_magic': 'true',
  246. 'magic_date': '2019-12-13',
  247. 'magic_url': 'http://example.com/',
  248. 'magic_choice': self.cf_select_choice1.value,
  249. }
  250. # Update CustomFields to set default values
  251. for field_name, default_value in CUSTOM_FIELD_DEFAULTS.items():
  252. CustomField.objects.filter(name=field_name).update(default=default_value)
  253. data = {
  254. 'name': 'Test Site X',
  255. 'slug': 'test-site-x',
  256. }
  257. url = reverse('dcim-api:site-list')
  258. response = self.client.post(url, data, format='json', **self.header)
  259. self.assertHttpStatus(response, status.HTTP_201_CREATED)
  260. self.assertEqual(response.data['custom_fields']['magic_word'], CUSTOM_FIELD_DEFAULTS['magic_word'])
  261. self.assertEqual(response.data['custom_fields']['magic_number'], str(CUSTOM_FIELD_DEFAULTS['magic_number']))
  262. self.assertEqual(response.data['custom_fields']['is_magic'], bool(CUSTOM_FIELD_DEFAULTS['is_magic']))
  263. self.assertEqual(response.data['custom_fields']['magic_date'], CUSTOM_FIELD_DEFAULTS['magic_date'])
  264. self.assertEqual(response.data['custom_fields']['magic_url'], CUSTOM_FIELD_DEFAULTS['magic_url'])
  265. self.assertEqual(response.data['custom_fields']['magic_choice'], self.cf_select_choice1.pk)
  266. class CustomFieldChoiceAPITest(APITestCase):
  267. def setUp(self):
  268. super().setUp()
  269. vm_content_type = ContentType.objects.get_for_model(VirtualMachine)
  270. self.cf_1 = CustomField.objects.create(name="cf_1", type=CustomFieldTypeChoices.TYPE_SELECT)
  271. self.cf_2 = CustomField.objects.create(name="cf_2", type=CustomFieldTypeChoices.TYPE_SELECT)
  272. self.cf_choice_1 = CustomFieldChoice.objects.create(field=self.cf_1, value="cf_field_1", weight=100)
  273. self.cf_choice_2 = CustomFieldChoice.objects.create(field=self.cf_1, value="cf_field_2", weight=50)
  274. self.cf_choice_3 = CustomFieldChoice.objects.create(field=self.cf_2, value="cf_field_3", weight=10)
  275. def test_list_cfc(self):
  276. url = reverse('extras-api:custom-field-choice-list')
  277. response = self.client.get(url, **self.header)
  278. self.assertEqual(len(response.data), 2)
  279. self.assertEqual(len(response.data[self.cf_1.name]), 2)
  280. self.assertEqual(len(response.data[self.cf_2.name]), 1)
  281. self.assertTrue(self.cf_choice_1.value in response.data[self.cf_1.name])
  282. self.assertTrue(self.cf_choice_2.value in response.data[self.cf_1.name])
  283. self.assertTrue(self.cf_choice_3.value in response.data[self.cf_2.name])
  284. self.assertEqual(self.cf_choice_1.pk, response.data[self.cf_1.name][self.cf_choice_1.value])
  285. self.assertEqual(self.cf_choice_2.pk, response.data[self.cf_1.name][self.cf_choice_2.value])
  286. self.assertEqual(self.cf_choice_3.pk, response.data[self.cf_2.name][self.cf_choice_3.value])
  287. class CustomFieldCSV(TestCase):
  288. def setUp(self):
  289. super().setUp()
  290. user = create_test_user(
  291. permissions=[
  292. 'dcim.view_site',
  293. 'dcim.add_site',
  294. ]
  295. )
  296. self.client = Client()
  297. self.client.force_login(user)
  298. obj_type = ContentType.objects.get_for_model(Site)
  299. self.cf_text = CustomField.objects.create(name="text", type=CustomFieldTypeChoices.TYPE_TEXT)
  300. self.cf_text.obj_type.set([obj_type])
  301. self.cf_text.save()
  302. self.cf_choice = CustomField.objects.create(name="choice", type=CustomFieldTypeChoices.TYPE_SELECT)
  303. self.cf_choice.obj_type.set([obj_type])
  304. self.cf_choice.save()
  305. self.cf_choice_1 = CustomFieldChoice.objects.create(field=self.cf_choice, value="cf_field_1")
  306. self.cf_choice_2 = CustomFieldChoice.objects.create(field=self.cf_choice, value="cf_field_2")
  307. self.cf_choice_3 = CustomFieldChoice.objects.create(field=self.cf_choice, value="cf_field_3")
  308. def test_import(self):
  309. """
  310. Import a site with custom fields
  311. """
  312. csv_data = (
  313. "name,slug,cf_text,cf_choice",
  314. "Site 1,site-1,something,cf_field_1",
  315. )
  316. response = self.client.post(reverse('dcim:site_import'), {'csv': '\n'.join(csv_data)})
  317. self.assertEqual(response.status_code, 200)
  318. site1_custom_fields = Site.objects.get(name='Site 1').get_custom_fields()
  319. self.assertEqual(len(site1_custom_fields), 2)
  320. self.assertEqual(site1_custom_fields[self.cf_text], 'something')
  321. self.assertEqual(site1_custom_fields[self.cf_choice], self.cf_choice_1)
  322. def test_import_invalid_choice(self):
  323. """
  324. Import a site with an invalid choice
  325. """
  326. csv_data = (
  327. "name,slug,cf_choice",
  328. "Site 2,site-2,cf_field_4",
  329. )
  330. response = self.client.post(reverse('dcim:site_import'), {'csv': '\n'.join(csv_data)})
  331. self.assertEqual(response.status_code, 200)
  332. self.assertFalse(len(Site.objects.filter(name="Site 2")), 0)