Files
Django_TasksApp/main/recipes/test_cooking.py
T
2026-10-12 10:00:02 +02:00

174 lines
10 KiB
Python

from datetime import date
from decimal import Decimal
from django.contrib.auth import get_user_model
from django.test import TestCase
from django.urls import reverse
from food.models import FoodLogEntry, FoodProduct, InventoryLocation, KitchenInventoryItem
from recipes.models import Recipe, RecipeCookingRun, RecipeIngredient, RecipeSubrecipe, RecipeUse
from recipes.services.analysis import analyze
from recipes.services.cooking import CookingError, complete, instruction_steps, make_completion
class RecipeCookingTests(TestCase):
def setUp(self):
users = get_user_model()
self.user = users.objects.create_user(username='cooking-owner')
self.other = users.objects.create_user(username='cooking-other')
self.client.force_login(self.user)
self.product = FoodProduct.objects.create(
owner=self.user, product_name='Oats', base_unit='g',
energy_kcal_100=Decimal('400'), protein_100=Decimal('10'),
carbohydrates_100=Decimal('60'), fat_100=Decimal('5'), fibre_100=Decimal('8'))
self.recipe = Recipe.objects.create(owner=self.user, title='Oat bowl',
default_servings=2,
instructions_markdown='1. Mix oats\n2. Serve warm')
RecipeIngredient.objects.create(recipe=self.recipe, name='Oats', quantity=Decimal('200'),
unit='g', inventory_product=self.product,
nutrition_product=self.product)
location = InventoryLocation.objects.create(user=self.user, name='Pantry')
self.package = KitchenInventoryItem.objects.create(
user=self.user, product=self.product, location=location,
original_amount=Decimal('300'), remaining_amount=Decimal('300'), inventory_unit='g')
self.day = date(2026, 10, 12)
def token(self):
return make_completion(analyze(self.recipe, self.user, 2))
def test_log_one_serving_without_inventory_and_keep_historical_nutrition(self):
token = self.token()
run = complete(self.user, self.recipe, token, log_food=True, deduct_stock=False,
consumed_servings='1', meal='breakfast', day=self.day)
entry = run.food_entry
self.assertEqual((entry.amount, entry.unit, entry.calories_kcal),
(Decimal('1'), 'servings', Decimal('400.000')))
self.assertEqual(entry.protein_g, Decimal('10.000'))
self.assertEqual(self.package.remaining_amount, Decimal('300'))
self.assertFalse(RecipeUse.objects.exists())
self.recipe.title = 'Changed bowl'; self.recipe.save()
self.product.energy_kcal_100 = Decimal('100'); self.product.save()
entry.refresh_from_db()
self.assertEqual((entry.product_name_snapshot, entry.calories_kcal),
('Oat bowl', Decimal('400.000')))
self.assertEqual(Decimal(run.nutrition_snapshot['calories_kcal']['per_serving']), Decimal('400'))
again = complete(self.user, self.recipe, token, log_food=True, deduct_stock=False,
consumed_servings='1', meal='breakfast', day=self.day)
self.assertEqual(again.pk, run.pk)
self.assertEqual(FoodLogEntry.objects.count(), 1)
def test_stock_only_and_both_actions_are_separate_and_idempotent(self):
stock_token = self.token()
stock = complete(self.user, self.recipe, stock_token, log_food=False, deduct_stock=True)
self.assertIsNone(stock.food_entry)
self.package.refresh_from_db()
self.assertEqual(self.package.remaining_amount, Decimal('100'))
self.assertEqual(RecipeUse.objects.count(), 1)
self.assertEqual(complete(self.user, self.recipe, stock_token, log_food=False,
deduct_stock=True).pk, stock.pk)
self.assertEqual(RecipeUse.objects.count(), 1)
self.assertEqual(FoodLogEntry.objects.count(), 0)
self.package.remaining_amount = Decimal('300'); self.package.opened = True
self.package.save()
both_token = self.token()
both = complete(self.user, self.recipe, both_token, log_food=True, deduct_stock=True,
consumed_servings='0.5', meal='dinner', day=self.day)
self.assertTrue(both.food_entry_id)
self.assertTrue(both.stock_use_id)
self.assertEqual(both.food_entry.calories_kcal, Decimal('200.000'))
self.package.refresh_from_db()
self.assertEqual(self.package.remaining_amount, Decimal('100'))
complete(self.user, self.recipe, both_token, log_food=True, deduct_stock=True,
consumed_servings='0.5', meal='dinner', day=self.day)
self.assertEqual(FoodLogEntry.objects.count(), 1)
self.assertEqual(RecipeUse.objects.count(), 2)
def test_invalid_stock_rolls_back_food_log_and_unavailable_stock_still_allows_log(self):
token = self.token()
self.package.remaining_amount = Decimal('50'); self.package.opened = True
self.package.save()
with self.assertRaises(CookingError):
complete(self.user, self.recipe, token, log_food=True, deduct_stock=True,
consumed_servings='1', meal='dinner', day=self.day)
self.assertFalse(FoodLogEntry.objects.exists())
self.assertFalse(RecipeCookingRun.objects.exists())
log_only_token = self.token()
run = complete(self.user, self.recipe, log_only_token, log_food=True,
deduct_stock=False, consumed_servings='1', meal='dinner', day=self.day)
self.assertTrue(run.food_entry_id)
self.assertIsNone(run.stock_use_id)
def test_missing_nutrients_and_nested_ingredients_are_snapshotted(self):
self.product.fibre_100 = None; self.product.save()
subrecipe = Recipe.objects.create(owner=self.user, title='Topping', default_servings=2,
instructions_markdown='Toast briefly.')
RecipeIngredient.objects.create(recipe=subrecipe, name='Oats', quantity=Decimal('100'),
unit='g', nutrition_product=self.product)
RecipeSubrecipe.objects.create(recipe=self.recipe, component=subrecipe,
quantity=Decimal('1'), unit='servings')
result = analyze(self.recipe, self.user, 2)
self.assertEqual(result['nutrition']['calories_kcal']['total'], Decimal('1000'))
self.assertFalse(result['nutrition']['fibre_g']['complete'])
run = complete(self.user, self.recipe, make_completion(result), log_food=True,
deduct_stock=False, consumed_servings='1', meal='lunch', day=self.day)
self.assertEqual(run.food_entry.calories_kcal, Decimal('500.000'))
self.assertIsNone(run.food_entry.fibre_g)
self.assertEqual(len(run.ingredient_snapshot), 2)
self.assertEqual(instruction_steps(self.recipe.instructions_markdown), ['Mix oats', 'Serve warm'])
diary = self.client.get(reverse('food:diary'), {'date': self.day.isoformat()})
self.assertContains(diary, 'Incomplete nutrition estimate')
def test_web_completion_and_owner_isolation(self):
cook_url = reverse('recipes:cook', args=[self.recipe.api_id])
finish_url = reverse('recipes:cook-finish', args=[self.recipe.api_id])
self.assertContains(self.client.get(cook_url), 'Step 1 of 2')
response = self.client.get(finish_url)
self.assertContains(response, 'Confirm selected actions')
token = response.context['confirmation']
post = {'confirmation': token, 'log_food': '1', 'consumed_servings': '1',
'meal': 'dinner', 'date': self.day.isoformat()}
self.assertEqual(self.client.post(finish_url, post).status_code, 302)
self.assertEqual(FoodLogEntry.objects.count(), 1)
self.assertEqual(self.client.post(finish_url, post).status_code, 302)
self.assertEqual(FoodLogEntry.objects.count(), 1)
stock_token = self.client.get(finish_url).context['confirmation']
stock_only = self.client.post(finish_url, {'confirmation': stock_token,
'deduct_stock': '1'})
self.assertEqual(stock_only.status_code, 302)
self.assertEqual(FoodLogEntry.objects.count(), 1)
self.package.refresh_from_db()
self.assertEqual(self.package.remaining_amount, Decimal('100'))
self.client.force_login(self.other)
self.assertEqual(self.client.get(cook_url).status_code, 404)
self.assertEqual(self.client.get(finish_url).status_code, 404)
self.assertEqual(self.client.post(finish_url, post).status_code, 404)
def test_invalid_consumed_portion_does_not_write(self):
token = self.token()
for amount in ('0', '-1', '2.001', 'nan'):
with self.assertRaises(CookingError):
complete(self.user, self.recipe, token, log_food=True, deduct_stock=False,
consumed_servings=amount, meal='dinner', day=self.day)
self.assertFalse(RecipeCookingRun.objects.exists())
def test_diary_recipe_edit_keeps_serving_unit_and_scales_snapshot(self):
run = complete(self.user, self.recipe, self.token(), log_food=True,
deduct_stock=False, consumed_servings='1', meal='breakfast', day=self.day)
url = reverse('food:edit', args=[run.food_entry.pk])
invalid = self.client.post(url, {'meal': 'breakfast', 'amount': '1',
'unit': 'g', 'portion_label_snapshot': 'Recipe serving'})
self.assertEqual(invalid.status_code, 200)
run.food_entry.refresh_from_db()
self.assertEqual(run.food_entry.unit, 'servings')
too_much = self.client.post(url, {'meal': 'breakfast', 'amount': '3',
'unit': 'servings', 'portion_label_snapshot': 'Recipe serving'})
self.assertContains(too_much, 'exceeds the prepared servings')
saved = self.client.post(url, {'meal': 'lunch', 'amount': '0.5',
'unit': 'servings', 'portion_label_snapshot': 'Recipe serving'})
self.assertEqual(saved.status_code, 302)
run.refresh_from_db(); run.food_entry.refresh_from_db()
self.assertEqual(run.consumed_servings, Decimal('0.5'))
self.assertEqual(run.food_entry.calories_kcal, Decimal('200.000'))
self.assertEqual(run.food_entry.meal, 'lunch')