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')