Add some more unit tests and validation code for the StockItem model

- Ensure that the build part matches the stockitem part!
This commit is contained in:
Oliver Walters 2020-10-05 00:49:00 +11:00
parent 3ee7be1d58
commit 48e050d317
2 changed files with 22 additions and 1 deletions

View File

@ -275,11 +275,25 @@ class StockItem(MPTTModel):
# TODO - Find a test than can be perfomed... # TODO - Find a test than can be perfomed...
pass pass
# Ensure that the item cannot be assigned to itself
if self.belongs_to and self.belongs_to.pk == self.pk: if self.belongs_to and self.belongs_to.pk == self.pk:
raise ValidationError({ raise ValidationError({
'belongs_to': _('Item cannot belong to itself') '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): def get_absolute_url(self):
return reverse('stock-item-detail', kwargs={'pk': self.id}) return reverse('stock-item-detail', kwargs={'pk': self.id})

View File

@ -7,7 +7,9 @@ import datetime
from .models import StockLocation, StockItem, StockItemTracking from .models import StockLocation, StockItem, StockItemTracking
from .models import StockItemTestResult from .models import StockItemTestResult
from part.models import Part from part.models import Part
from build.models import Build
class StockTest(TestCase): class StockTest(TestCase):
@ -62,9 +64,14 @@ class StockTest(TestCase):
# And there should be *no* items being build # And there should be *no* items being build
self.assertEqual(part.quantity_being_built, 0) 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" # Add some stock items which are "building"
for i in range(10): 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 # The "is_building" quantity should not be counted here
self.assertEqual(part.total_stock, n + 5) self.assertEqual(part.total_stock, n + 5)