Files
Django_TasksApp/main/food/tests.py
T
2026-10-09 14:43:46 +02:00

156 lines
8.8 KiB
Python

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)
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'][0]['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)