185 lines
12 KiB
Python
185 lines
12 KiB
Python
import json
|
|
from decimal import Decimal
|
|
|
|
from django.contrib.auth import get_user_model
|
|
from django.test import TestCase
|
|
|
|
from food.api import create_token
|
|
from food.models import FoodLogEntry, FoodProduct, InventoryLocation, KitchenInventoryItem
|
|
from recipes.models import (Recipe, RecipeIngredient, RecipeIngredientSubstitution,
|
|
RecipeSubrecipe, RecipeUse)
|
|
|
|
|
|
class RecipeApiTests(TestCase):
|
|
def setUp(self):
|
|
users = get_user_model()
|
|
self.user = users.objects.create_user('recipe-api-owner')
|
|
self.other = users.objects.create_user('recipe-api-other')
|
|
_, self.secret = create_token(self.user, 'Recipe API',
|
|
['food:read', 'food:write', 'inventory:read', 'inventory:write'])
|
|
_, self.food_read = create_token(self.user, 'Recipe read', ['food:read'])
|
|
_, self.stock_read = create_token(self.user, 'Stock read', ['inventory:read'])
|
|
self.product = FoodProduct.objects.create(owner=self.user, product_name='Oats',
|
|
energy_kcal_100=Decimal('400'), protein_100=Decimal('10'),
|
|
carbohydrates_100=Decimal('60'), fat_100=Decimal('5'), fibre_100=Decimal('8'))
|
|
self.other_product = FoodProduct.objects.create(owner=self.other, product_name='Private oats')
|
|
self.other_recipe = Recipe.objects.create(owner=self.other, title='Private recipe')
|
|
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')
|
|
|
|
def call(self, method, path, data=None, token=None, key=None):
|
|
headers = {'HTTP_AUTHORIZATION': f'Bearer {token or self.secret}'}
|
|
if key:
|
|
headers['HTTP_IDEMPOTENCY_KEY'] = key
|
|
if data is not None:
|
|
headers['content_type'] = 'application/json'
|
|
data = json.dumps(data)
|
|
return getattr(self.client, method)(f'/api/v1/{path}', data=data, **headers)
|
|
|
|
def create(self):
|
|
response = self.call('post', 'recipes/create/',
|
|
{'title': 'Oat bowl', 'default_servings': '2',
|
|
'instructions_markdown': 'Mix oats.'}, key='create-oat-bowl')
|
|
self.assertEqual(response.status_code, 201, response.content)
|
|
return response.json()['id']
|
|
|
|
def test_cook_later_api_is_idempotent_scoped_and_paged(self):
|
|
recipe_id = self.create()
|
|
path = 'recipes/cook-later/'
|
|
self.assertFalse(self.call('get', f'recipes/{recipe_id}/').json()['is_cook_later'])
|
|
self.assertEqual(self.call('post', path, {'recipe_id': recipe_id}, token=self.food_read).status_code, 403)
|
|
self.assertEqual(self.call('post', path, {'recipe_id': str(self.other_recipe.api_id)}).status_code, 404)
|
|
self.assertTrue(self.call('post', path, {'recipe_id': recipe_id}).json()['created'])
|
|
self.assertFalse(self.call('post', path, {'recipe_id': recipe_id}).json()['created'])
|
|
self.assertTrue(self.call('get', f'recipes/{recipe_id}/').json()['is_cook_later'])
|
|
self.assertTrue(self.call('get', 'recipes/?query=Oat').json()['recipes'][0]['is_cook_later'])
|
|
self.assertEqual(self.call('get', path).json()['count'], 1)
|
|
self.assertEqual(self.call('get', f'{path}?offset=1').json()['recipes'], [])
|
|
self.assertEqual(self.call('get', f'{path}?limit=0').status_code, 400)
|
|
self.assertTrue(self.call('delete', f'{path}{recipe_id}/').json()['removed'])
|
|
self.assertFalse(self.call('delete', f'{path}{recipe_id}/').json()['removed'])
|
|
|
|
def test_recipe_crud_variation_and_scopes(self):
|
|
recipe_id = self.create()
|
|
repeat = self.call('post', 'recipes/create/',
|
|
{'title': 'Oat bowl', 'default_servings': '2',
|
|
'instructions_markdown': 'Mix oats.'}, key='create-oat-bowl')
|
|
self.assertEqual(repeat.status_code, 200)
|
|
self.assertEqual(repeat.json()['id'], recipe_id)
|
|
self.assertEqual(self.call('post', 'recipes/create/',
|
|
{'title': 'Other'}, key='create-oat-bowl').status_code, 409)
|
|
self.assertEqual(self.call('get', 'recipes/?query=Oat').json()['count'], 1)
|
|
self.assertEqual(self.call('get', f'recipes/{recipe_id}/').json()['title'], 'Oat bowl')
|
|
self.assertEqual(self.call('patch', f'recipes/{recipe_id}/',
|
|
{'title': 'Updated bowl', 'instructions_markdown': 'Toast oats.'}).json()['title'], 'Updated bowl')
|
|
self.assertEqual(self.call('patch', f'recipes/{recipe_id}/',
|
|
{'title': 'No write'}, token=self.food_read).status_code, 403)
|
|
self.assertEqual(self.call('get', f'recipes/{recipe_id}/', token=self.stock_read).status_code, 403)
|
|
self.assertEqual(self.call('get', f'recipes/{self.other_recipe.api_id}/').status_code, 404)
|
|
self.assertEqual(self.call('patch', f'recipes/{self.other_recipe.api_id}/',
|
|
{'title': 'Stolen'}).status_code, 404)
|
|
variation = self.call('post', f'recipes/{recipe_id}/variations/',
|
|
{'title': 'Spicy bowl'}, key='variation-1')
|
|
self.assertEqual(variation.status_code, 201, variation.content)
|
|
variation_id = variation.json()['id']
|
|
self.assertEqual(variation.json()['parent_id'], recipe_id)
|
|
self.assertEqual(self.call('get', f'recipes/{recipe_id}/').json()['variations'][0]['id'], variation_id)
|
|
self.assertEqual(self.call('delete', f'recipes/{recipe_id}/').status_code, 200)
|
|
self.assertEqual(self.call('get', f'recipes/{variation_id}/').json()['parent_id'], None)
|
|
|
|
def test_ingredients_subrecipes_ownership_cycle_and_independent_variation(self):
|
|
recipe_id = self.create()
|
|
ingredient = {'name': 'Oats', 'quantity': '200', 'unit': 'g',
|
|
'inventory_product_id': str(self.product.api_id),
|
|
'nutrition_product_id': str(self.product.api_id)}
|
|
created = self.call('post', f'recipes/{recipe_id}/ingredients/', ingredient, key='oats-ingredient')
|
|
self.assertEqual(created.status_code, 201, created.content)
|
|
item_id = created.json()['id']
|
|
self.assertEqual(self.call('post', f'recipes/{recipe_id}/ingredients/', ingredient,
|
|
key='oats-ingredient').json()['id'], item_id)
|
|
self.assertEqual(self.call('post', f'recipes/{recipe_id}/ingredients/',
|
|
{**ingredient, 'inventory_product_id': str(self.other_product.api_id)}).status_code, 400)
|
|
self.assertEqual(self.call('patch', f'recipes/{recipe_id}/ingredients/{item_id}/',
|
|
{'quantity': '150'}).json()['quantity'], '150')
|
|
RecipeIngredientSubstitution.objects.create(
|
|
ingredient=RecipeIngredient.objects.get(pk=item_id), name='Buckwheat',
|
|
quantity=Decimal('150'), unit='g', product=self.product)
|
|
variation = self.call('post', f'recipes/{recipe_id}/variations/', {}, key='var-with-oats').json()
|
|
variation_id = variation['id']
|
|
self.assertEqual(variation['ingredients'][0]['quantity'], '150.000')
|
|
self.assertEqual(variation['ingredients'][0]['substitutions'][0]['name'], 'Buckwheat')
|
|
self.call('patch', f'recipes/{recipe_id}/ingredients/{item_id}/', {'quantity': '100'})
|
|
self.assertEqual(self.call('get', f'recipes/{variation_id}/').json()['ingredients'][0]['quantity'], '150.000')
|
|
component = self.call('post', 'recipes/create/', {'title': 'Topping'}, key='topping').json()['id']
|
|
link = self.call('post', f'recipes/{recipe_id}/subrecipes/',
|
|
{'component_id': component, 'quantity': '1', 'unit': 'servings'}, key='link-topping')
|
|
self.assertEqual(link.status_code, 201, link.content)
|
|
self.assertEqual(self.call('post', f'recipes/{component}/subrecipes/',
|
|
{'component_id': recipe_id}).status_code, 400)
|
|
self.assertEqual(self.call('post', f'recipes/{recipe_id}/subrecipes/',
|
|
{'component_id': str(self.other_recipe.api_id)}).status_code, 404)
|
|
self.assertEqual(self.call('delete', f'recipes/{component}/').status_code, 409)
|
|
self.assertEqual(self.call('delete', f'recipes/{recipe_id}/subrecipes/{link.json()["id"]}/').status_code, 200)
|
|
self.assertEqual(self.call('delete', f'recipes/{component}/').status_code, 200)
|
|
self.assertEqual(self.call('delete', f'recipes/{recipe_id}/ingredients/{item_id}/').status_code, 200)
|
|
|
|
def test_inventory_preview_confirm_replay_undo_and_recipe_log_snapshot(self):
|
|
recipe_id = self.create()
|
|
ingredient = {'name': 'Oats', 'quantity': '200', 'unit': 'g',
|
|
'inventory_product_id': str(self.product.api_id),
|
|
'nutrition_product_id': str(self.product.api_id)}
|
|
self.assertEqual(self.call('post', f'recipes/{recipe_id}/ingredients/', ingredient).status_code, 201)
|
|
preview = self.call('post', f'recipes/{recipe_id}/stock/preview/',
|
|
{'servings': '2'}, token=self.stock_read)
|
|
self.assertEqual(preview.status_code, 200, preview.content)
|
|
self.assertTrue(preview.json()['stock_ready'])
|
|
self.assertEqual(preview.json()['products'][0]['deductions'][0]['amount'], '200.000')
|
|
self.assertEqual(self.call('post', f'recipes/{recipe_id}/stock/confirm/',
|
|
{'confirmation': preview.json()['confirmation']}, token=self.stock_read).status_code, 403)
|
|
confirmation = {'confirmation': preview.json()['confirmation']}
|
|
confirmed = self.call('post', f'recipes/{recipe_id}/stock/confirm/', confirmation)
|
|
self.assertEqual(confirmed.status_code, 200, confirmed.content)
|
|
self.assertTrue(confirmed.json()['created'])
|
|
self.assertFalse(self.call('post', f'recipes/{recipe_id}/stock/confirm/',
|
|
confirmation).json()['created'])
|
|
self.package.refresh_from_db()
|
|
self.assertEqual(self.package.remaining_amount, Decimal('100'))
|
|
self.assertEqual(RecipeUse.objects.count(), 1)
|
|
logged = self.call('post', f'recipes/{recipe_id}/log/',
|
|
{'servings': '2', 'consumed_servings': '0.5', 'meal': 'dinner',
|
|
'date': '2026-10-12'}, key='recipe-meal-1')
|
|
self.assertEqual(logged.status_code, 201, logged.content)
|
|
self.assertEqual(logged.json()['nutrition']['calories_kcal'], '200.000')
|
|
self.assertFalse(logged.json()['stock_deducted'])
|
|
self.assertEqual(self.call('post', f'recipes/{recipe_id}/log/',
|
|
{'servings': '2', 'consumed_servings': '0.5', 'meal': 'dinner',
|
|
'date': '2026-10-12'}, key='recipe-meal-1').status_code, 200)
|
|
self.assertEqual(FoodLogEntry.objects.count(), 1)
|
|
self.call('patch', f'recipes/{recipe_id}/', {'title': 'Edited bowl'})
|
|
entry = FoodLogEntry.objects.get()
|
|
self.assertEqual((entry.product_name_snapshot, entry.calories_kcal),
|
|
('Oat bowl', Decimal('200')))
|
|
self.assertEqual(self.call('post', f'recipes/stock-use/{confirmed.json()["stock_use_id"]}/undo/',
|
|
{}).status_code, 200)
|
|
self.package.refresh_from_db()
|
|
self.assertEqual(self.package.remaining_amount, Decimal('300'))
|
|
self.assertEqual(FoodLogEntry.objects.count(), 1)
|
|
self.assertEqual(self.call('post', f'recipes/{recipe_id}/stock/confirm/',
|
|
{'confirmation': 'invalid'}).status_code, 400)
|
|
|
|
def test_missing_stock_blocks_confirmation_but_not_meal(self):
|
|
recipe_id = self.create()
|
|
self.call('post', f'recipes/{recipe_id}/ingredients/',
|
|
{'name': 'Oats', 'quantity': '400', 'unit': 'g',
|
|
'nutrition_product_id': str(self.product.api_id),
|
|
'inventory_product_id': str(self.product.api_id)})
|
|
preview = self.call('post', f'recipes/{recipe_id}/stock/preview/', {}).json()
|
|
self.assertFalse(preview['stock_ready'])
|
|
self.assertIsNone(preview['confirmation'])
|
|
self.assertEqual(self.call('post', f'recipes/{recipe_id}/log/',
|
|
{'consumed_servings': '1', 'meal': 'lunch'}, key='meal-with-shortage').status_code, 201)
|
|
self.package.refresh_from_db()
|
|
self.assertEqual(self.package.remaining_amount, Decimal('300'))
|