Better API validation

This commit is contained in:
Oliver Walters 2020-04-10 00:53:04 +10:00
parent 41b3f1d39c
commit 5b2665edb1
2 changed files with 19 additions and 4 deletions

View File

@ -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,

View File

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