From 48168de4ff9e2153c1d8818947300538717083a9 Mon Sep 17 00:00:00 2001 From: Julio Oliveira at Encora <149191228+Julio-Oliveira-Encora@users.noreply.github.com> Date: Fri, 19 Jan 2024 17:24:08 -0300 Subject: [PATCH] =?UTF-8?q?Fixes=20#14755:=20ValueError=20in=20web=20UI=20?= =?UTF-8?q?after=20REST=20API=20accepts=20invalid=20cus=E2=80=A6=20(#14804?= =?UTF-8?q?)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Fixes #14755: ValueError in web UI after REST API accepts invalid custom-field choice-set data * PR Comments Addressed * Set max_length=2 on extra_choices items; remove custom validation logic * Move test for invalid choices to CustomFieldChoiceSetTest * Omit unused imports --------- Co-authored-by: julio.oliveira Co-authored-by: Jeremy Stretch --- netbox/extras/api/serializers.py | 7 +++++++ netbox/extras/tests/test_api.py | 18 +++++++++++++++++- 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/netbox/extras/api/serializers.py b/netbox/extras/api/serializers.py index f5e99b4434..714c925488 100644 --- a/netbox/extras/api/serializers.py +++ b/netbox/extras/api/serializers.py @@ -3,6 +3,7 @@ from drf_spectacular.types import OpenApiTypes from drf_spectacular.utils import extend_schema_field from rest_framework import serializers +from rest_framework.fields import ListField from core.api.nested_serializers import NestedDataSourceSerializer, NestedDataFileSerializer, NestedJobSerializer from core.api.serializers import JobSerializer @@ -175,6 +176,12 @@ class CustomFieldChoiceSetSerializer(ValidatedModelSerializer): choices=CustomFieldChoiceSetBaseChoices, required=False ) + extra_choices = serializers.ListField( + child=serializers.ListField( + min_length=2, + max_length=2 + ) + ) class Meta: model = CustomFieldChoiceSet diff --git a/netbox/extras/tests/test_api.py b/netbox/extras/tests/test_api.py index 93be2d2c4b..f40372a8f7 100644 --- a/netbox/extras/tests/test_api.py +++ b/netbox/extras/tests/test_api.py @@ -14,7 +14,6 @@ from extras.scripts import BooleanVar, IntegerVar, Script, StringVar from utilities.testing import APITestCase, APIViewTestCases - User = get_user_model() @@ -251,6 +250,23 @@ def setUpTestData(cls): ) CustomFieldChoiceSet.objects.bulk_create(choice_sets) + def test_invalid_choice_items(self): + """ + Attempting to define each choice as a single-item list should return a 400 error. + """ + self.add_permissions('extras.add_customfieldchoiceset') + data = { + "name": "test", + "extra_choices": [ + ["choice1"], + ["choice2"], + ["choice3"], + ] + } + + response = self.client.post(self._get_list_url(), data, format='json', **self.header) + self.assertEqual(response.status_code, 400) + class CustomLinkTest(APIViewTestCases.APIViewTestCase): model = CustomLink