From 48e050d3171c16f16d92feae7ff63d08b960818e Mon Sep 17 00:00:00 2001 From: Oliver Walters Date: Mon, 5 Oct 2020 00:49:00 +1100 Subject: [PATCH] Add some more unit tests and validation code for the StockItem model - Ensure that the build part matches the stockitem part! --- InvenTree/stock/models.py | 14 ++++++++++++++ InvenTree/stock/tests.py | 9 ++++++++- 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/InvenTree/stock/models.py b/InvenTree/stock/models.py index fbdc1654f3..1535ded420 100644 --- a/InvenTree/stock/models.py +++ b/InvenTree/stock/models.py @@ -275,11 +275,25 @@ class StockItem(MPTTModel): # TODO - Find a test than can be perfomed... pass + # Ensure that the item cannot be assigned to itself if self.belongs_to and self.belongs_to.pk == self.pk: raise ValidationError({ 'belongs_to': _('Item cannot belong to itself') }) + # If the item is marked as "is_building", it must point to a build! + if self.is_building and not self.build: + raise ValidationError({ + 'build': _("Item must have a build reference if is_building=True") + }) + + # If the item points to a build, check that the Part references match + if self.build: + if not self.part == self.build.part: + raise ValidationError({ + 'build': _("Build reference does not point to the same part object") + }) + def get_absolute_url(self): return reverse('stock-item-detail', kwargs={'pk': self.id}) diff --git a/InvenTree/stock/tests.py b/InvenTree/stock/tests.py index 44b901e7b6..34fe8877f8 100644 --- a/InvenTree/stock/tests.py +++ b/InvenTree/stock/tests.py @@ -7,7 +7,9 @@ import datetime from .models import StockLocation, StockItem, StockItemTracking from .models import StockItemTestResult + from part.models import Part +from build.models import Build class StockTest(TestCase): @@ -62,9 +64,14 @@ class StockTest(TestCase): # And there should be *no* items being build self.assertEqual(part.quantity_being_built, 0) + build = Build.objects.create(part=part, title='A test build', quantity=1) + # Add some stock items which are "building" for i in range(10): - StockItem.objects.create(part=part, quantity=10, is_building=True) + StockItem.objects.create( + part=part, build=build, + quantity=10, is_building=True + ) # The "is_building" quantity should not be counted here self.assertEqual(part.total_stock, n + 5)