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 from .models import FoodFavourite, FoodLogAttachment, FoodLogEntry, FoodPortion, FoodProduct, MealType, Unit 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_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'], 100) 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_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_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_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)