From 5b2665edb17b069f6bf6339f72430c00ccc3dbcb Mon Sep 17 00:00:00 2001 From: Oliver Walters Date: Fri, 10 Apr 2020 00:53:04 +1000 Subject: [PATCH] Better API validation --- InvenTree/stock/api.py | 10 +++++++--- InvenTree/stock/test_api.py | 13 ++++++++++++- 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/InvenTree/stock/api.py b/InvenTree/stock/api.py index 39b660732f..4ef9fac8ef 100644 --- a/InvenTree/stock/api.py +++ b/InvenTree/stock/api.py @@ -133,8 +133,12 @@ class StockAdjust(APIView): for entry in _items: + if not type(entry) == dict: + raise ValidationError({'error': 'Improperly formatted data'}) + try: - item = StockItem.objects.get(pk=entry.get('pk', None)) + pk = entry.get('pk', None) + item = StockItem.objects.get(pk=pk) except (ValueError, StockItem.DoesNotExist): raise ValidationError({'pk': 'Each entry must contain a valid pk field'}) @@ -143,8 +147,8 @@ class StockAdjust(APIView): except (ValueError, TypeError, InvalidOperation): raise ValidationError({'quantity': 'Each entry must contain a valid quantity field'}) - if quantity <= 0: - raise ValidationError({'quantity': 'Quantity field must be greater than zero'}) + if quantity < 0: + raise ValidationError({'quantity': 'Quantity field must not be less than zero'}) self.items.append({ 'item': item, diff --git a/InvenTree/stock/test_api.py b/InvenTree/stock/test_api.py index 8c8372ebc7..4d5e29cda6 100644 --- a/InvenTree/stock/test_api.py +++ b/InvenTree/stock/test_api.py @@ -142,4 +142,15 @@ class StocktakeTest(APITestCase): }] response = self.doPost(url, data) - self.assertContains(response, 'must be greater than zero', status_code=status.HTTP_400_BAD_REQUEST) + self.assertContains(response, 'must not be less than zero', status_code=status.HTTP_400_BAD_REQUEST) + + # Test with a single item + data = { + 'item': { + 'pk': 1234, + 'quantity': '10', + } + } + + response = self.doPost(url, data) + self.assertEqual(response.status_code, status.HTTP_200_OK)