From 9db3efa0858fb1a9a95ab10fc4726350276a062e Mon Sep 17 00:00:00 2001 From: Lavissa Date: Thu, 11 Jan 2024 02:03:12 +0100 Subject: [PATCH] Enable existing_image on PATCH requests (#6126) * Enable existing_image on PATCH requests * Fix CI problems * Solution * Change check to whitelist and add unit tests --- InvenTree/part/serializers.py | 5 ++- InvenTree/part/test_api.py | 58 +++++++++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+), 1 deletion(-) diff --git a/InvenTree/part/serializers.py b/InvenTree/part/serializers.py index 4e978e086f..ea23eb8e72 100644 --- a/InvenTree/part/serializers.py +++ b/InvenTree/part/serializers.py @@ -617,7 +617,10 @@ class PartSerializer( if not create: # These fields are only used for the LIST API endpoint - for f in self.skip_create_fields()[1:]: + for f in self.skip_create_fields(): + # Fields required for certain operations, but are not part of the model + if f in ["remote_image", "existing_image"]: + continue self.fields.pop(f) if not pricing: diff --git a/InvenTree/part/test_api.py b/InvenTree/part/test_api.py index 1b32f5f914..d80bc7b0ff 100644 --- a/InvenTree/part/test_api.py +++ b/InvenTree/part/test_api.py @@ -1575,6 +1575,64 @@ class PartDetailTests(PartAPITestBase): self.assertEqual(response.data['image'], image_name) + def test_update_existing_image(self): + """Test that we can update the image of an existing part with an already existing image""" + # First, upload an image for an existing part + p = Part.objects.first() + + fn = 'part_image_123abc.png' + + img = PIL.Image.new('RGB', (128, 128), color='blue') + img.save(fn) + + # Upload the image to a part + with open(fn, 'rb') as img_file: + response = self.upload_client.patch( + reverse('api-part-detail', kwargs={'pk': p.pk}), + { + 'image': img_file, + }, + ) + + self.assertEqual(response.status_code, 200) + image_name = response.data['image'] + self.assertTrue(image_name.startswith('/media/part_images/part_image')) + + # Create a new part without an image + response = self.post( + reverse('api-part-list'), + { + 'name': 'Some New Part', + 'description': 'Description of the part', + 'category': 1 + }, + expected_code=201 + ) + + self.assertEqual(response.data['image'], None) + part_pk = response.data['pk'] + + # Add image from the first part to the new part + response = self.patch( + reverse('api-part-detail', kwargs={'pk': part_pk}), + { + 'existing_image': image_name + }, + expected_code=200 + ) + + self.assertEqual(response.data['image'], image_name) + + # Attempt to add a non-existent image to an existing part + last_p = Part.objects.last() + response = self.patch( + reverse('api-part-detail', kwargs={'pk': last_p.pk}), + { + 'existing_image': 'bogus_image.jpg' + }, + expected_code=400 + ) + def test_details(self): """Test that the required details are available.""" p = Part.objects.get(pk=1)