from datetime import date
from decimal import Decimal
from tempfile import TemporaryDirectory
from django.contrib.auth import get_user_model
from django.core.exceptions import ValidationError
from django.core.files.uploadedfile import SimpleUploadedFile
from django.db import IntegrityError, transaction
from django.test import TestCase
from django.urls import reverse
from planner.models import UserSettings
from .services.diary import diary_context, ring_progress
from .models import (FoodFavourite, FoodLogAttachment, FoodLogEntry, FoodPortion, FoodProduct, MealType, Unit,
InventoryLocation, KitchenInventoryItem, InventoryConsumption, InventoryScanRun,
InventoryScanBatch, InventoryScanItem)
class FoodFoundationTests(TestCase):
def setUp(self):
self.user = get_user_model().objects.create_user(username='food-one', password='test-password')
self.other = get_user_model().objects.create_user(username='food-two', password='test-password')
self.product = FoodProduct.objects.create(owner=self.user, product_name='Yoghurt', barcode='123', base_unit=Unit.GRAM)
def test_inventory_staging_counts_refresh_and_are_user_scoped(self):
location = InventoryLocation.objects.create(user=self.user, name='Fridge')
run = InventoryScanRun.objects.create(user=self.user)
batch = InventoryScanBatch.objects.create(run=run, location=location, sequence=1)
InventoryScanItem.objects.create(batch=batch, location=location, barcode='111',
status=InventoryScanItem.Status.QUEUED)
InventoryScanItem.objects.create(batch=batch, location=location, barcode='222',
status=InventoryScanItem.Status.FAILED)
other_location = InventoryLocation.objects.create(user=self.other, name='Other fridge')
other_run = InventoryScanRun.objects.create(user=self.other)
other_batch = InventoryScanBatch.objects.create(run=other_run, location=other_location, sequence=1)
InventoryScanItem.objects.create(batch=other_batch, location=other_location, barcode='333',
status=InventoryScanItem.Status.PROCESSING)
self.client.force_login(self.user)
url = reverse('food:inventory-staging-counts')
response = self.client.get(url, secure=True)
self.assertEqual(response.status_code, 200)
self.assertContains(response, '1', html=True)
self.assertContains(response, '1', html=True)
self.assertContains(response, 'hx-trigger="load, every 5s"')
InventoryScanItem.objects.filter(batch=batch, barcode='111').update(status=InventoryScanItem.Status.COMPLETE)
response = self.client.get(url, secure=True)
self.assertContains(response, '0', html=True)
self.assertContains(response, '1', html=True)
def test_meals_are_fixed(self):
self.assertEqual(list(MealType.values), ['breakfast', 'lunch', 'dinner', 'snacks'])
def test_missing_nutrients_remain_null(self):
self.product.refresh_from_db()
self.assertIsNone(self.product.energy_kcal_100)
self.assertIsNone(self.product.protein_100)
self.assertIsNone(self.product.fibre_100)
def test_default_and_custom_fibre_goal(self):
from planner.forms import FoodGoalForm
self.client.force_login(self.user)
profile = UserSettings.objects.create(user=self.user)
self.assertEqual(profile.fibre_goal_g, Decimal('40'))
response = self.client.get(reverse('planner:user-settings'))
self.assertContains(response, 'Daily fibre goal (g)')
response = self.client.post(reverse('planner:user-settings'), {'section': 'food',
'daily_calorie_goal': '2000', 'carbohydrate_goal_g': '250', 'protein_goal_g': '100',
'fat_goal_g': '70', 'fibre_goal_g': '35.5'})
self.assertEqual(response.status_code, 302)
profile.refresh_from_db()
self.assertEqual(profile.fibre_goal_g, Decimal('35.5'))
self.assertEqual(profile.protein_goal_g, Decimal('100'))
self.assertContains(self.client.get(reverse('planner:user-settings')), 'value="35.5"')
self.assertFalse(FoodGoalForm(data={'fibre_goal_g': '-1'}).is_valid())
def test_fibre_snapshots_scale_and_unknown_is_not_zero(self):
from .services.logging import apply_product_snapshot
self.product.fibre_100 = Decimal('3.2')
self.product.save(update_fields=['fibre_100'])
entry = FoodLogEntry(user=self.user, date=date(2026, 10, 3), meal=MealType.BREAKFAST,
amount=Decimal('250'), unit=Unit.GRAM)
apply_product_snapshot(entry, self.product)
self.assertEqual(entry.fibre_g, Decimal('8.000'))
entry.full_clean()
entry.save()
self.product.fibre_100 = None
self.product.save(update_fields=['fibre_100'])
old = FoodLogEntry.objects.create(user=self.user, date=date(2026, 10, 3), meal=MealType.LUNCH,
product_name_snapshot='Legacy food', amount=Decimal('100'), unit=Unit.GRAM)
context = diary_context(self.user, date(2026, 10, 3))
self.assertIsNone(old.fibre_g)
self.assertEqual(context['totals']['fibre_g'], Decimal('8.000'))
fibre = context['macros'][3]
self.assertTrue(fibre['incomplete'])
self.assertEqual(fibre['percent'], 20)
self.assertIsNone(fibre['remaining'])
self.assertEqual(FoodLogEntry.objects.get(pk=entry.pk).fibre_g, Decimal('8.000'))
def test_fibre_totals_and_over_goal(self):
UserSettings.objects.create(user=self.user, fibre_goal_g=Decimal('40'))
for value in ('25', '20'):
FoodLogEntry.objects.create(user=self.user, date=date(2026, 10, 3), meal=MealType.SNACKS,
product_name_snapshot='Known fibre', amount=Decimal('100'), unit=Unit.GRAM,
fibre_g=Decimal(value))
context = diary_context(self.user, date(2026, 10, 3))
self.assertEqual(context['totals']['fibre_g'], Decimal('45'))
fibre = context['macros'][3]
self.assertEqual(fibre['percent'], 113)
self.assertEqual(fibre['remaining'], Decimal('-5'))
self.assertFalse(fibre['incomplete'])
self.client.force_login(self.user)
self.assertContains(self.client.get(reverse('food:diary'), {'date': '2026-10-03'}), '5.0 g over target')
def test_ring_laps_and_over_target_accessible_text(self):
for amount, percent, base, extra, laps in (
('0', 0, '0.00', '0.00', 0),
('36', 75, '75.00', '0.00', 0),
('48', 100, '100.00', '0.00', 1),
('60', 125, '100.00', '25.00', 1),
('80.4', 168, '100.00', '67.50', 1),
('96', 200, '100.00', '100.00', 2),
('108', 225, '100.00', '25.00', 2),
):
with self.subTest(amount=amount):
ring = ring_progress(Decimal(amount), Decimal('48'))
self.assertEqual((ring['percent'], ring['base_lap'], ring['extra_lap'], ring['full_laps']),
(percent, base, extra, laps))
UserSettings.objects.create(user=self.user, fat_goal_g=Decimal('48'))
FoodLogEntry.objects.create(user=self.user, date=date(2026, 10, 3), meal=MealType.SNACKS,
product_name_snapshot='Known fat', amount=Decimal('100'), unit=Unit.GRAM,
fat_g=Decimal('80.4'))
self.client.force_login(self.user)
response = self.client.get(reverse('food:diary'), {'date': '2026-10-03'})
self.assertContains(response, '168%')
self.assertContains(response, '32.4 g over target')
self.assertContains(response, 'stroke-dasharray="67.50 100"')
def test_favourite_and_portion_uniqueness(self):
FoodFavourite.objects.create(user=self.user, product=self.product)
FoodPortion.objects.create(user=self.user, product=self.product, label='My bowl', amount=Decimal('300'), unit=Unit.GRAM)
with self.assertRaises(IntegrityError), transaction.atomic():
FoodFavourite.objects.create(user=self.user, product=self.product)
with self.assertRaises(IntegrityError), transaction.atomic():
FoodPortion.objects.create(user=self.user, product=self.product, label='My bowl', amount=Decimal('200'), unit=Unit.GRAM)
def test_log_snapshot_survives_product_edit(self):
entry = FoodLogEntry.objects.create(user=self.user, date=date(2026, 10, 3), meal=MealType.BREAKFAST,
product=self.product, product_name_snapshot='Yoghurt', amount=Decimal('300'), unit=Unit.GRAM,
calories_kcal=Decimal('174'))
self.product.product_name = 'Renamed yoghurt'
self.product.energy_kcal_100 = Decimal('100')
self.product.save()
entry.refresh_from_db()
self.assertEqual(entry.product_name_snapshot, 'Yoghurt')
self.assertEqual(entry.calories_kcal, Decimal('174'))
def test_cross_user_product_reference_rejected(self):
for item in (
FoodFavourite(user=self.other, product=self.product),
FoodPortion(user=self.other, product=self.product, label='Bowl', amount=Decimal('100'), unit=Unit.GRAM),
FoodLogEntry(user=self.other, product=self.product, date=date(2026, 10, 3), meal=MealType.LUNCH,
product_name_snapshot='Yoghurt', amount=Decimal('100'), unit=Unit.GRAM),
):
with self.assertRaises(ValidationError):
item.full_clean()
def test_food_route_requires_login(self):
self.assertEqual(self.client.get(reverse('food:diary')).status_code, 302)
self.client.force_login(self.user)
self.assertEqual(self.client.get(reverse('food:diary')).status_code, 200)
def test_diary_shows_private_attachment_to_owner(self):
entry = FoodLogEntry.objects.create(user=self.user, date=date(2026, 10, 3), meal=MealType.DINNER,
product_name_snapshot='Dinner', amount=Decimal('250'), unit=Unit.GRAM)
image_bytes = b'example-image-bytes'
with TemporaryDirectory() as media_root, self.settings(MEDIA_ROOT=media_root):
attachment = FoodLogAttachment.objects.create(log_entry=entry,
image=SimpleUploadedFile('dinner.png', image_bytes, content_type='image/png'),
original_filename='dinner.png', content_type='image/png', file_size=len(image_bytes))
image_url = reverse('food:attachment-file', args=[attachment.api_id])
self.client.force_login(self.user)
diary = self.client.get(reverse('food:diary'), {'date': '2026-10-03'})
self.assertContains(diary, image_url, count=2)
image = self.client.get(image_url)
self.assertEqual(image.status_code, 200)
self.assertEqual(image['Content-Type'], 'image/png')
self.assertEqual(b''.join(image.streaming_content), image_bytes)
image.close()
self.client.force_login(self.other)
self.assertEqual(self.client.get(image_url).status_code, 404)
self.client.logout()
self.assertEqual(self.client.get(image_url).status_code, 302)
def test_food_goals_reject_negative_values(self):
from planner.forms import FoodGoalForm
form = FoodGoalForm(data={'daily_calorie_goal': '-1', 'carbohydrate_goal_g': '-1',
'protein_goal_g': '10', 'fat_goal_g': '0'})
self.assertFalse(form.is_valid())
def test_diary_totals_and_over_goal(self):
goals = UserSettings.objects.create(user=self.user, daily_calorie_goal=100, protein_goal_g=Decimal('10'))
FoodLogEntry.objects.create(user=self.user, date=date(2026, 10, 3), meal=MealType.BREAKFAST,
product=self.product, product_name_snapshot='Yoghurt', amount=Decimal('100'), unit=Unit.GRAM,
calories_kcal=Decimal('80'), protein_g=Decimal('4'))
FoodLogEntry.objects.create(user=self.user, date=date(2026, 10, 3), meal=MealType.DINNER,
product_name_snapshot='Soup', amount=Decimal('100'), unit=Unit.GRAM,
calories_kcal=Decimal('55'), protein_g=Decimal('3'))
context = diary_context(self.user, date(2026, 10, 3))
self.assertEqual(context['totals']['calories_kcal'], Decimal('135'))
self.assertEqual(context['totals']['protein_g'], Decimal('7'))
self.assertEqual(context['calorie_remaining'], Decimal('-35'))
self.assertEqual(context['meals'][0]['calories'], Decimal('80'))
self.assertEqual(context['meals'][2]['calories'], Decimal('55'))
self.assertEqual(context['macros'][1]['percent'], None)
self.client.force_login(self.user)
response = self.client.get(reverse('food:diary'), {'date': '2026-10-03'})
self.assertContains(response, '35 kcal over goal')
self.assertContains(response, 'No target')
self.assertContains(response, 'date=2026-10-02')
self.assertContains(response, 'date=2026-10-04')
def test_goals_and_partial_nutrition_across_recent_dates(self):
UserSettings.objects.create(user=self.user, daily_calorie_goal=2050,
protein_goal_g=Decimal('132'), carbohydrate_goal_g=Decimal('250'),
fat_goal_g=Decimal('48'), fibre_goal_g=Decimal('40'))
complete = {'calories_kcal': Decimal('300'), 'protein_g': Decimal('20'),
'carbohydrates_g': Decimal('30'), 'fat_g': Decimal('10'),
'fibre_g': Decimal('5'), 'sugars_g': Decimal('4'), 'salt_g': Decimal('1')}
for day in (15, 16, 17):
FoodLogEntry.objects.create(user=self.user, date=date(2026, 10, day),
meal=MealType.LUNCH, product_name_snapshot='Known lunch',
amount=Decimal('100'), unit='g', **complete)
unknown = FoodLogEntry.objects.create(user=self.user, date=date(2026, 10, 16),
meal=MealType.DINNER, product_name_snapshot='Unknown meatballs',
amount=Decimal('160'), unit='g')
FoodLogEntry.objects.create(user=self.user, date=date(2026, 10, 17),
meal=MealType.DINNER, product_name_snapshot='Partial dinner',
amount=Decimal('100'), unit='g', protein_g=Decimal('8'), fibre_g=Decimal('2'))
before = list(FoodLogEntry.objects.filter(user=self.user).values_list('pk', 'calories_kcal'))
self.client.force_login(self.user)
for day in (15, 16, 17):
selected = date(2026, 10, day)
context = diary_context(self.user, selected)
self.assertEqual(context['calorie_goal'], 2050)
self.assertEqual(context['totals']['calories_kcal'], Decimal('300'))
self.assertEqual(context['totals']['protein_g'], Decimal('20') if day != 17 else Decimal('28'))
self.assertEqual(context['nutrition_incomplete']['calories_kcal'], day != 15)
self.assertEqual(context['calorie_remaining'], Decimal('1750') if day == 15 else None)
response = self.client.get(reverse('food:diary'), {'date': selected.isoformat()})
self.assertContains(response, 'Goal: 2050 kcal')
self.assertNotContains(response, 'No calorie goal')
self.assertContains(response, '132.0 g goal')
self.assertContains(response, '250.0 g goal')
self.assertContains(response, '48.0 g goal')
if day == 15:
self.assertContains(response, '1750 kcal remaining')
self.assertNotContains(response, 'Nutrition incomplete')
else:
self.assertContains(response, 'At least 300 kcal eaten')
self.assertContains(response, 'Nutrition incomplete')
self.assertContains(response, 'food entry to review')
self.assertContains(self.client.get(reverse('food:diary'), {'date': '2026-10-16'}),
f'href="#food-entry-{unknown.pk}"')
self.assertEqual(before, list(FoodLogEntry.objects.filter(user=self.user).values_list('pk', 'calories_kcal')))
def test_bad_date_and_user_isolation(self):
FoodLogEntry.objects.create(user=self.other, date=date(2026, 10, 3), meal=MealType.LUNCH,
product_name_snapshot='Private food', amount=Decimal('100'), unit=Unit.GRAM,
calories_kcal=Decimal('999'))
self.client.force_login(self.user)
self.assertEqual(self.client.get(reverse('food:diary'), {'date': 'not-a-date'}).status_code, 400)
response = self.client.get(reverse('food:diary'), {'date': '2026-10-03'})
self.assertNotContains(response, 'Private food')
self.assertEqual(diary_context(self.user, date(2026, 10, 3))['totals']['calories_kcal'], 0)
def test_add_edit_delete_and_htmx_fragment(self):
self.product.energy_kcal_100 = Decimal('60')
self.product.protein_100 = Decimal('4')
self.product.save()
self.client.force_login(self.user)
add_url = reverse('food:add')
response = self.client.post(add_url, {'date': '2026-10-03', 'product': self.product.pk,
'meal': MealType.BREAKFAST, 'amount': '200', 'unit': 'g'}, HTTP_HX_REQUEST='true')
self.assertEqual(response.status_code, 200)
self.assertContains(response, 'id="food-workspace"')
self.assertContains(response, '120 kcal eaten')
entry = FoodLogEntry.objects.get(user=self.user)
self.assertEqual(entry.protein_g, Decimal('8'))
response = self.client.post(reverse('food:edit', args=[entry.pk]), {'meal': MealType.DINNER,
'amount': '100', 'unit': 'g'}, HTTP_HX_REQUEST='true')
self.assertContains(response, '60 kcal eaten')
entry.refresh_from_db()
self.assertEqual(entry.meal, MealType.DINNER)
self.assertEqual(entry.protein_g, Decimal('4'))
response = self.client.post(reverse('food:delete', args=[entry.pk]), HTTP_HX_REQUEST='true')
self.assertContains(response, '0 kcal eaten')
self.assertFalse(FoodLogEntry.objects.filter(pk=entry.pk).exists())
def test_inventory_portion_preserves_old_diary_and_retries(self):
import uuid
self.product.energy_kcal_100 = Decimal('100')
self.product.save(update_fields=['energy_kcal_100'])
historical = FoodLogEntry.objects.create(user=self.user, product=self.product,
date=date(2026, 10, 3), meal=MealType.BREAKFAST,
product_name_snapshot='Yoghurt', amount=Decimal('100'), unit='g',
calories_kcal=Decimal('275'))
location = InventoryLocation.objects.create(user=self.user, name='Fridge')
package = KitchenInventoryItem.objects.create(user=self.user, product=self.product,
location=location, original_amount=Decimal('360'), remaining_amount=Decimal('270'),
inventory_unit='g', opened=True)
portion = FoodPortion.objects.create(user=self.user, product=self.product,
label='cup', amount=Decimal('90'), unit='g')
self.client.force_login(self.user)
payload = {'date': '2026-10-04', 'product': self.product.pk, 'meal': MealType.LUNCH,
'portion': f'portion:{portion.pk}', 'unit': 'g', 'inventory_package': str(package.api_id),
'submission_id': str(uuid.uuid4())}
response = self.client.post(reverse('food:add'), payload)
self.assertEqual(response.status_code, 302)
package.refresh_from_db()
self.assertEqual(package.remaining_amount, Decimal('180'))
self.assertEqual(InventoryConsumption.objects.filter(user=self.user).count(), 1)
self.client.post(reverse('food:add'), payload)
self.assertEqual(FoodLogEntry.objects.filter(user=self.user).count(), 2)
package.refresh_from_db()
self.assertEqual(package.remaining_amount, Decimal('180'))
self.assertEqual(diary_context(self.user, date(2026, 10, 3))['totals']['calories_kcal'], Decimal('275'))
historical.refresh_from_db()
self.assertEqual(historical.calories_kcal, Decimal('275'))
def test_inventory_shortage_does_not_log_food(self):
import uuid
location = InventoryLocation.objects.create(user=self.user, name='Fridge')
package = KitchenInventoryItem.objects.create(user=self.user, product=self.product,
location=location, original_amount=Decimal('700'), remaining_amount=Decimal('60'),
inventory_unit='g', opened=True)
self.client.force_login(self.user)
response = self.client.post(reverse('food:add'), {'date': '2026-10-04',
'product': self.product.pk, 'meal': MealType.LUNCH, 'portion': 'custom',
'amount': '100', 'unit': 'g', 'inventory_package': str(package.api_id),
'submission_id': str(uuid.uuid4())})
self.assertContains(response, 'Insufficient stock')
self.assertFalse(FoodLogEntry.objects.filter(user=self.user).exists())
package.refresh_from_db()
self.assertEqual(package.remaining_amount, Decimal('60'))
def test_multiple_configured_pieces_use_exact_saved_weight(self):
import uuid
self.product.energy_kcal_100 = Decimal('200')
self.product.save(update_fields=['energy_kcal_100'])
piece = FoodPortion.objects.create(user=self.user, product=self.product,
label='meatball', amount=Decimal('25'), unit='g')
location = InventoryLocation.objects.create(user=self.user, name='Freezer')
package = KitchenInventoryItem.objects.create(user=self.user, product=self.product,
location=location, original_amount=Decimal('250'), remaining_amount=Decimal('125'),
inventory_unit='g', opened=True)
self.client.force_login(self.user)
response = self.client.post(reverse('food:add'), {'date': '2026-10-04',
'product': self.product.pk, 'meal': MealType.DINNER,
'portion': f'portion:{piece.pk}', 'portion_count': '3', 'unit': 'g',
'inventory_package': str(package.api_id), 'submission_id': str(uuid.uuid4())})
self.assertEqual(response.status_code, 302)
entry = FoodLogEntry.objects.get(user=self.user)
self.assertEqual(entry.amount, Decimal('75'))
self.assertEqual(entry.calories_kcal, Decimal('150'))
self.assertEqual(entry.portion_label_snapshot, '3 × meatball')
package.refresh_from_db()
self.assertEqual(package.remaining_amount, Decimal('50'))
def test_cannot_edit_or_delete_another_users_entry(self):
entry = FoodLogEntry.objects.create(user=self.other, date=date(2026, 10, 3), meal=MealType.LUNCH,
product_name_snapshot='Private food', amount=Decimal('100'), unit=Unit.GRAM)
self.client.force_login(self.user)
self.assertEqual(self.client.get(reverse('food:edit', args=[entry.pk])).status_code, 404)
self.assertEqual(self.client.post(reverse('food:delete', args=[entry.pk])).status_code, 404)