From c3f6b75b302cedf99694acaf5dc3e7489b35e180 Mon Sep 17 00:00:00 2001 From: Oliver Date: Thu, 20 Oct 2022 22:43:14 +1100 Subject: [PATCH] Attachment bug fix (#3818) * Prevent name check on null attachment file (cherry picked from commit c4ed1e23a01f278d696c2853337bdde0a682c6c5) * Unit testing for uploading attachments via API (cherry picked from commit 592548065f7b69f58b8aaaaea506e3ec653a63df) --- InvenTree/InvenTree/models.py | 2 +- InvenTree/part/test_api.py | 80 +++++++++++++++++++++++++++++++++++ 2 files changed, 81 insertions(+), 1 deletion(-) diff --git a/InvenTree/InvenTree/models.py b/InvenTree/InvenTree/models.py index 04b9c14bed..cd15800e55 100644 --- a/InvenTree/InvenTree/models.py +++ b/InvenTree/InvenTree/models.py @@ -385,7 +385,7 @@ class InvenTreeAttachment(models.Model): 'link': _('Missing external link'), }) - if self.attachment.name.lower().endswith('.svg'): + if self.attachment and self.attachment.name.lower().endswith('.svg'): self.attachment.file.file = self.clean_svg(self.attachment) super().save(*args, **kwargs) diff --git a/InvenTree/part/test_api.py b/InvenTree/part/test_api.py index 35179485d0..9555ed5092 100644 --- a/InvenTree/part/test_api.py +++ b/InvenTree/part/test_api.py @@ -2350,3 +2350,83 @@ class PartParameterTest(InvenTreeAPITestCase): data = response.data self.assertEqual(data['data'], '15') + + +class PartAttachmentTest(InvenTreeAPITestCase): + """Unit tests for the PartAttachment API endpoint""" + + fixtures = [ + 'category', + 'part', + 'location', + ] + + def test_add_attachment(self): + """Test that we can create a new PartAttachment via the API""" + + url = reverse('api-part-attachment-list') + + # Upload without permission + response = self.post( + url, + {}, + expected_code=403, + ) + + # Add required permission + self.assignRole('part.add') + + # Upload without specifying part (will fail) + response = self.post( + url, + { + 'comment': 'Hello world', + }, + expected_code=400 + ) + + self.assertIn('This field is required', str(response.data['part'])) + + # Upload without file OR link (will fail) + response = self.post( + url, + { + 'part': 1, + 'comment': 'Hello world', + }, + expected_code=400 + ) + + self.assertIn('Missing file', str(response.data['attachment'])) + self.assertIn('Missing external link', str(response.data['link'])) + + # Upload an invalid link (will fail) + response = self.post( + url, + { + 'part': 1, + 'link': 'not-a-link.py', + }, + expected_code=400 + ) + + self.assertIn('Enter a valid URL', str(response.data['link'])) + + link = 'https://www.google.com/test' + + # Upload a valid link (will pass) + response = self.post( + url, + { + 'part': 1, + 'link': link, + 'comment': 'Hello world', + }, + expected_code=201 + ) + + data = response.data + + self.assertEqual(data['part'], 1) + self.assertEqual(data['link'], link) + self.assertEqual(data['comment'], 'Hello world')