Files
Django_TasksApp/main/food/test_api.py
T
2026-10-23 14:30:58 +02:00

641 lines
46 KiB
Python

import hashlib
import io
import json
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime, timedelta, timezone as py_timezone
from decimal import Decimal
from unittest.mock import patch
from PIL import Image
from django.contrib.auth import get_user_model
from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import Client, TestCase, TransactionTestCase, override_settings
from django.db import connection
from django.utils import timezone
from planner.models import UserSettings, WaterIntakeEntry
from .api import create_token
from .models import FoodLogEntry, FoodProduct, InventoryConsumption, InventoryLocation, KitchenInventoryItem, PersonalAccessToken
from .services.openfoodfacts import OpenFoodFactsError
class FoodApiTests(TestCase):
def setUp(self):
self.a = get_user_model().objects.create_user('api-a', password='test')
self.b = get_user_model().objects.create_user('api-b', password='test')
self.product_a = FoodProduct.objects.create(owner=self.a, product_name='Pasta', energy_kcal_100=Decimal('350'))
self.product_b = FoodProduct.objects.create(owner=self.b, product_name='Private food')
self.entry_b = FoodLogEntry.objects.create(user=self.b, date=timezone.localdate(), meal='lunch',
product=self.product_b, product_name_snapshot='Private food', amount=Decimal('100'), unit='g')
self.location_b = InventoryLocation.objects.create(user=self.b, name='Cupboard')
self.item_b = KitchenInventoryItem.objects.create(user=self.b, product=self.product_b, location=self.location_b)
self.token, self.secret = create_token(self.a, 'Test',
['food:read', 'food:write', 'inventory:read', 'inventory:write'])
def call(self, method, path, data=None, token=None, **headers):
args = {'HTTP_AUTHORIZATION': f'Bearer {token or self.secret}', **headers}
if data is not None:
args['content_type'] = 'application/json'
data = json.dumps(data)
return getattr(self.client, method)(path, data=data, **args)
def test_today_reports_quantity_scaled_known_subtotals_and_missing_fields(self):
day = timezone.localdate()
FoodLogEntry.objects.create(user=self.a, date=day, meal='lunch',
product_name_snapshot='Known lunch', amount=Decimal('100'), quantity=Decimal('2'),
unit='g', calories_kcal=Decimal('120'), protein_g=Decimal('5'))
FoodLogEntry.objects.create(user=self.a, date=day, meal='dinner',
product_name_snapshot='Unknown dinner', amount=Decimal('100'), unit='g')
result = self.call('get', '/api/v1/food/today/').json()
self.assertEqual(Decimal(result['totals']['calories_kcal']), Decimal('240'))
self.assertEqual(Decimal(result['totals']['protein_g']), Decimal('10'))
self.assertTrue(result['incomplete']['calories_kcal'])
self.assertTrue(result['incomplete']['protein_g'])
self.assertIsNone(result['totals']['fat_g'])
def test_atomic_food_log_and_inventory_keeps_historical_snapshot(self):
old = FoodLogEntry.objects.create(user=self.a, product=self.product_a,
date=timezone.localdate() - timedelta(days=1), meal='dinner',
product_name_snapshot='Pasta', amount=Decimal('100'), unit='g',
calories_kcal=Decimal('432'))
location = InventoryLocation.objects.create(user=self.a, name='Pantry')
package = KitchenInventoryItem.objects.create(user=self.a, product=self.product_a,
location=location, original_amount=Decimal('700'), remaining_amount=Decimal('600'),
inventory_unit='g', opened=True)
payload = {'meal': 'lunch', 'product_id': str(self.product_a.api_id),
'amount': '90', 'unit': 'g', 'inventory_package_id': str(package.api_id)}
path = '/api/v1/food/log/'
self.assertEqual(self.call('post', path, payload).status_code, 400)
first = self.call('post', path, payload, HTTP_IDEMPOTENCY_KEY='food-stock-1')
self.assertEqual(first.status_code, 201, first.content)
self.assertIn('inventory_consumption_id', first.json())
self.assertEqual(self.call('post', path, payload, HTTP_IDEMPOTENCY_KEY='food-stock-1').status_code, 200)
package.refresh_from_db()
self.assertEqual(package.remaining_amount, Decimal('510'))
self.assertEqual(InventoryConsumption.objects.filter(user=self.a).count(), 1)
self.assertEqual(FoodLogEntry.objects.filter(user=self.a).count(), 2)
shortage = self.call('post', path, {**payload, 'amount': '600'}, HTTP_IDEMPOTENCY_KEY='food-stock-2')
self.assertEqual(shortage.status_code, 409)
self.assertEqual(FoodLogEntry.objects.filter(user=self.a).count(), 2)
old.refresh_from_db()
self.assertEqual(old.calories_kcal, Decimal('432'))
def test_bulk_inventory_update_preview_partial_atomic_and_retry(self):
location = InventoryLocation.objects.create(user=self.a, name='Pantry')
items = [KitchenInventoryItem.objects.create(user=self.a, product=self.product_a, location=location)
for _ in range(2)]
path = '/api/v1/kitchen/bulk-update/'
rows = [{'item_id': str(item.api_id), 'changes': {'location': ' Metal shelf ', 'best_before': '2026-11-01'}}
for item in items]
preview = self.call('post', path, {'items': rows, 'dry_run': True})
self.assertEqual(preview.status_code, 200, preview.content)
self.assertEqual(preview.json()['counts']['validated'], 2)
self.assertFalse(InventoryLocation.objects.filter(user=self.a, name='Metal shelf').exists())
self.assertEqual(KitchenInventoryItem.objects.filter(pk__in=[item.pk for item in items], location=location).count(), 2)
rows.append({'item_id': str(self.item_b.api_id), 'changes': {'notes': 'foreign'}})
atomic = self.call('post', path, {'items': rows, 'dry_run': False, 'atomic': True}, HTTP_IDEMPOTENCY_KEY='bulk-atomic')
self.assertEqual(atomic.json()['status'], 'rolled_back')
self.assertEqual(atomic.json()['counts']['rolled_back'], 2)
self.assertFalse(InventoryLocation.objects.filter(user=self.a, name='Metal shelf').exists())
partial_payload = {'items': rows, 'dry_run': False}
partial = self.call('post', path, partial_payload, HTTP_IDEMPOTENCY_KEY='bulk-partial')
self.assertEqual(partial.json()['counts']['changed'], 2)
self.assertEqual(partial.json()['counts']['failed'], 1)
self.assertEqual(self.call('post', path, partial_payload, HTTP_IDEMPOTENCY_KEY='bulk-partial').json(), partial.json())
self.assertEqual(self.call('post', path, {**partial_payload, 'atomic': True}, HTTP_IDEMPOTENCY_KEY='bulk-partial').status_code, 409)
self.assertEqual(KitchenInventoryItem.objects.filter(pk__in=[item.pk for item in items], location__name='Metal shelf').count(), 2)
self.assertEqual(KitchenInventoryItem.objects.get(pk=self.item_b.pk).notes, '')
def test_bulk_inventory_rejects_duplicates_limits_and_stale_timestamp(self):
location = InventoryLocation.objects.create(user=self.a, name='Pantry')
item = KitchenInventoryItem.objects.create(user=self.a, product=self.product_a, location=location)
path = '/api/v1/kitchen/bulk-update/'
row = {'item_id': str(item.api_id), 'changes': {'notes': 'new'}}
self.assertEqual(self.call('post', path, {'items': [row, row], 'dry_run': False}, HTTP_IDEMPOTENCY_KEY='dup').status_code, 400)
self.assertEqual(self.call('post', path, {'items': [row] * 51, 'dry_run': False}, HTTP_IDEMPOTENCY_KEY='large').status_code, 400)
self.assertEqual(self.call('post', path, {'items': [row], 'dry_run': False}).json()['error']['code'], 'idempotency_key_required')
result = self.call('post', path, {'items': [{**row, 'expected_updated_at': '2000-01-01T00:00:00+00:00'}],
'dry_run': False}, HTTP_IDEMPOTENCY_KEY='stale')
self.assertEqual(result.json()['items'][0]['error']['code'], 'inventory_conflict')
item.refresh_from_db()
self.assertEqual(item.notes, '')
def test_bulk_inventory_accepts_twenty_three_updates_in_one_request(self):
location = InventoryLocation.objects.create(user=self.a, name='Pantry')
items = [KitchenInventoryItem.objects.create(user=self.a, product=self.product_a, location=location)
for _ in range(23)]
payload = {'items': [{'item_id': str(item.api_id), 'changes': {'notes': 'Checked'}} for item in items],
'dry_run': False}
path = '/api/v1/kitchen/bulk-update/'
preview = self.call('post', path, {**payload, 'dry_run': True})
self.assertEqual(preview.json()['counts']['validated'], 23)
self.assertEqual(KitchenInventoryItem.objects.filter(user=self.a, notes='Checked').count(), 0)
result = self.call('post', path, payload, HTTP_IDEMPOTENCY_KEY='twenty-three-items')
self.assertEqual(result.status_code, 200, result.content)
self.assertEqual(result.json()['counts']['changed'], 23)
self.assertEqual(KitchenInventoryItem.objects.filter(user=self.a, notes='Checked').count(), 23)
self.assertEqual(self.call('post', path, payload, HTTP_IDEMPOTENCY_KEY='twenty-three-items').json(), result.json())
def test_bulk_inventory_rejects_more_than_fifty_distinct_items(self):
location = InventoryLocation.objects.create(user=self.a, name='Pantry')
items = [KitchenInventoryItem.objects.create(user=self.a, product=self.product_a, location=location)
for _ in range(51)]
payload = {'items': [{'item_id': str(item.api_id), 'changes': {'notes': 'Checked'}} for item in items],
'dry_run': False, 'atomic': True}
result = self.call('post', '/api/v1/kitchen/bulk-update/', payload, HTTP_IDEMPOTENCY_KEY='over-limit')
self.assertEqual(result.status_code, 400)
self.assertEqual(KitchenInventoryItem.objects.filter(user=self.a, notes='Checked').count(), 0)
def test_bulk_inventory_delete_preview_confirm_and_history(self):
location = InventoryLocation.objects.create(user=self.a, name='Pantry')
item = KitchenInventoryItem.objects.create(user=self.a, product=self.product_a, location=location)
path = '/api/v1/kitchen/bulk-delete/'
payload = {'item_ids': [str(item.api_id), str(self.item_b.api_id)]}
preview = self.call('post', path, payload).json()
self.assertEqual(preview['counts']['validated'], 1)
self.assertEqual(preview['counts']['failed'], 1)
self.assertEqual(preview['items'][0]['before']['product_name'], 'Pasta')
item.refresh_from_db(); self.assertIsNone(item.archived_at)
self.assertEqual(self.call('post', path, {'item_ids': [str(item.api_id)] * 2}).status_code, 400)
self.assertEqual(self.call('post', path, {'item_ids': [str(item.api_id)] * 21}).status_code, 400)
self.assertEqual(self.call('post', path, {**payload, 'dry_run': False}, HTTP_IDEMPOTENCY_KEY='delete-no-confirm').status_code, 400)
atomic = self.call('post', path, {**payload, 'dry_run': False, 'confirm': True, 'atomic': True},
HTTP_IDEMPOTENCY_KEY='bulk-delete-atomic')
self.assertEqual(atomic.json()['status'], 'rolled_back')
item.refresh_from_db(); self.assertIsNone(item.archived_at)
run_payload = {**payload, 'dry_run': False, 'confirm': True}
run = self.call('post', path, run_payload, HTTP_IDEMPOTENCY_KEY='bulk-delete')
self.assertEqual(run.json()['counts']['changed'], 1)
self.assertEqual(self.call('post', path, run_payload, HTTP_IDEMPOTENCY_KEY='bulk-delete').json(), run.json())
item.refresh_from_db(); self.assertIsNotNone(item.archived_at)
self.assertTrue(FoodProduct.objects.filter(pk=self.product_a.pk).exists())
self.assertIsNone(KitchenInventoryItem.objects.get(pk=self.item_b.pk).archived_at)
def test_bulk_inventory_update_remaining_amount_uses_consumption_and_preview_rolls_back(self):
product = FoodProduct.objects.create(owner=self.a, product_name='Flour', package_amount=Decimal('500'), package_unit='g')
location = InventoryLocation.objects.create(user=self.a, name='Pantry')
item = KitchenInventoryItem.objects.create(user=self.a, product=product, location=location,
original_amount=Decimal('500'), remaining_amount=Decimal('500'), inventory_unit='g')
payload = {'items': [{'item_id': str(item.api_id), 'changes': {'remaining_amount': '400', 'opened': True}}]}
preview = self.call('post', '/api/v1/kitchen/bulk-update/', {**payload, 'dry_run': True})
self.assertEqual(preview.json()['counts']['validated'], 1)
self.assertEqual(InventoryConsumption.objects.filter(user=self.a).count(), 0)
item.refresh_from_db(); self.assertEqual(item.remaining_amount, 500)
applied = self.call('post', '/api/v1/kitchen/bulk-update/', {**payload, 'dry_run': False},
HTTP_IDEMPOTENCY_KEY='bulk-stock-1')
self.assertEqual(applied.json()['counts']['changed'], 1)
self.assertEqual(InventoryConsumption.objects.filter(user=self.a).count(), 1)
item.refresh_from_db(); self.assertEqual(item.remaining_amount, 400)
def test_authentication_scopes_and_token_storage(self):
self.assertNotIn(self.secret, self.token.token_hash)
self.assertEqual(self.token.token_hash, hashlib.sha256(self.secret.encode()).hexdigest())
self.assertEqual(self.call('get', '/api/v1/food/today/').status_code, 200)
self.token.refresh_from_db()
self.assertIsNotNone(self.token.last_used_at)
self.assertEqual(self.call('get', '/api/v1/food/today/', token='bad').status_code, 401)
read_token, read_secret = create_token(self.a, 'Read', ['food:read'])
self.assertEqual(self.call('get', '/api/v1/food/today/', token=read_secret).status_code, 200)
self.assertEqual(self.call('post', '/api/v1/food/log/', {'meal': 'lunch'}, token=read_secret).status_code, 403)
self.assertEqual(self.call('get', '/api/v1/kitchen/items/', token=read_secret).status_code, 403)
read_token.revoked_at = timezone.now()
read_token.save()
self.assertEqual(self.call('get', '/api/v1/food/today/', token=read_secret).status_code, 401)
expired, expired_secret = create_token(self.a, 'Expired', ['food:read'], timezone.now() - timedelta(seconds=1))
self.assertEqual(self.call('get', '/api/v1/food/today/', token=expired_secret).json()['error']['code'], 'expired_token')
def test_owner_isolation_and_products(self):
self.assertEqual(self.call('get', '/api/v1/food/today/').json()['meals']['lunch'], [])
result = self.call('get', '/api/v1/food/products/?search=Private')
self.assertEqual(result.json()['results'], [])
self.assertEqual(self.call('get', f'/api/v1/food/log/{self.entry_b.api_id}/').status_code, 404)
self.assertEqual(self.call('patch', f'/api/v1/food/log/{self.entry_b.api_id}/', {'meal': 'dinner'}).status_code, 404)
self.assertEqual(self.call('delete', f'/api/v1/food/log/{self.entry_b.api_id}/').status_code, 404)
self.assertEqual(self.call('post', f'/api/v1/food/log/{self.entry_b.api_id}/attachments/').status_code, 404)
self.assertEqual(self.call('get', f'/api/v1/kitchen/items/{self.item_b.api_id}/').status_code, 404)
self.assertEqual(self.call('delete', f'/api/v1/kitchen/items/{self.item_b.api_id}/').status_code, 404)
self.assertEqual(self.call('patch', f'/api/v1/kitchen/items/{self.item_b.api_id}/', {'quantity': 2}).status_code, 404)
result = self.call('post', '/api/v1/food/log/', {'meal': 'lunch', 'amount': '100', 'unit': 'g',
'product_id': str(self.product_b.api_id)})
self.assertEqual(result.status_code, 404)
def test_food_crud_and_idempotency(self):
payload = {'meal': 'dinner', 'amount': '50', 'unit': 'g', 'product_id': str(self.product_a.api_id)}
first = self.call('post', '/api/v1/food/log/', payload, HTTP_IDEMPOTENCY_KEY='meal-1')
self.assertEqual(first.status_code, 201, first.content)
self.assertEqual(first.json()['calories_kcal'], '175.000')
second = self.call('post', '/api/v1/food/log/', payload, HTTP_IDEMPOTENCY_KEY='meal-1')
self.assertEqual(second.status_code, 200)
self.assertEqual(FoodLogEntry.objects.filter(user=self.a).count(), 1)
self.assertEqual(self.call('post', '/api/v1/food/log/', {**payload, 'amount': '60'},
HTTP_IDEMPOTENCY_KEY='meal-1').status_code, 409)
identifier = first.json()['id']
self.assertEqual(self.call('patch', f'/api/v1/food/log/{identifier}/', {'amount': '100'}).json()['calories_kcal'], '350.000')
self.assertEqual(self.call('get', f'/api/v1/food/log/{identifier}/').status_code, 200)
self.assertEqual(self.call('delete', f'/api/v1/food/log/{identifier}/').status_code, 200)
self.assertEqual(self.call('post', '/api/v1/food/log/', {**payload, 'amount': '0'}).status_code, 400)
def test_drink_contribution_follows_food_entry_and_preserves_snapshot(self):
day = timezone.localdate()
tomorrow = day + timedelta(days=1)
drink = FoodProduct.objects.create(owner=self.a, product_name='Orange juice', base_unit='ml')
payload = {'meal': 'lunch', 'amount': '250', 'unit': 'ml', 'product_id': str(drink.api_id),
'date': day.isoformat()}
first = self.call('post', '/api/v1/food/log/', payload, HTTP_IDEMPOTENCY_KEY='juice-1')
self.assertEqual(first.status_code, 201, first.content)
self.assertEqual(self.call('post', '/api/v1/food/log/', payload,
HTTP_IDEMPOTENCY_KEY='juice-1').status_code, 200)
daily = lambda date: self.call('get', f'/api/v1/hydration/daily/?date={date}').json()
self.assertEqual(daily(day.isoformat())['food_ml'], '250.000')
self.assertEqual(FoodLogEntry.objects.filter(user=self.a).count(), 1)
identifier = first.json()['id']
drink.product_name = 'Orange food'
drink.hydration_factor = Decimal('.5')
drink.save()
changed = self.call('patch', f'/api/v1/food/log/{identifier}/',
{'amount': '300', 'date': tomorrow.isoformat()})
self.assertEqual(changed.status_code, 200, changed.content)
self.assertEqual(Decimal(daily(day.isoformat())['food_ml']), 0)
self.assertEqual(daily(tomorrow.isoformat())['food_ml'], '300.000')
self.assertEqual(self.call('delete', f'/api/v1/food/log/{identifier}/').status_code, 200)
self.assertEqual(Decimal(daily(tomorrow.isoformat())['food_ml']), 0)
def test_drink_units_settings_and_manual_hydration_crud(self):
drink = FoodProduct.objects.create(owner=self.a, product_name='Milk', base_unit='ml')
grams = self.call('post', '/api/v1/food/log/', {'meal': 'breakfast', 'amount': '200',
'unit': 'g', 'product_name': 'Milk'})
self.assertEqual(grams.status_code, 201, grams.content)
self.assertEqual(Decimal(self.call('get', '/api/v1/hydration/daily/').json()['food_ml']), 0)
self.assertEqual(self.call('patch', '/api/v1/hydration/settings/',
{'auto_count_food_drinks': False}).status_code, 200)
ml = self.call('post', '/api/v1/food/log/', {'meal': 'lunch', 'amount': '200',
'unit': 'ml', 'product_id': str(drink.api_id)})
self.assertEqual(ml.status_code, 201, ml.content)
self.assertEqual(Decimal(self.call('get', '/api/v1/hydration/daily/').json()['food_ml']), 0)
self.call('patch', '/api/v1/hydration/settings/', {'auto_count_food_drinks': True})
self.assertEqual(self.call('get', '/api/v1/hydration/daily/').json()['food_ml'], '200.000')
first = self.call('post', '/api/v1/hydration/manual/', {'amount_ml': '150.5',
'beverage_type': 'water'}, HTTP_IDEMPOTENCY_KEY='manual-1')
self.assertEqual(first.status_code, 201, first.content)
again = self.call('post', '/api/v1/hydration/manual/', {'amount_ml': '150.5',
'beverage_type': 'water'}, HTTP_IDEMPOTENCY_KEY='manual-1')
self.assertEqual(again.status_code, 200)
self.assertEqual(WaterIntakeEntry.objects.filter(user=self.a).count(), 1)
self.assertEqual(self.call('get', '/api/v1/hydration/daily/').json()['total_ml'], '350.500')
identifier = first.json()['id']
self.assertEqual(self.call('patch', f'/api/v1/hydration/manual/{identifier}/',
{'amount_ml': '100'}).status_code, 200)
self.assertEqual(Decimal(self.call('get', '/api/v1/hydration/daily/').json()['manual_ml']), 100)
self.assertEqual(self.call('delete', f'/api/v1/hydration/manual/{identifier}/').status_code, 200)
self.assertEqual(Decimal(self.call('get', '/api/v1/hydration/daily/').json()['manual_ml']), 0)
def test_soup_setting_and_product_override_affect_new_entries_only(self):
soup = FoodProduct.objects.create(owner=self.a, product_name='Tomato soup', base_unit='ml')
payload = {'meal': 'lunch', 'amount': '200', 'unit': 'ml', 'product_id': str(soup.api_id)}
first = self.call('post', '/api/v1/food/log/', payload)
self.assertEqual(first.status_code, 201, first.content)
self.assertEqual(Decimal(self.call('get', '/api/v1/hydration/daily/').json()['food_ml']), 0)
self.assertEqual(self.call('patch', '/api/v1/hydration/settings/',
{'include_liquid_foods': True, 'hydration_beverage_rules': {'soup': {'factor': '0.5'}}}).status_code, 200)
second = self.call('post', '/api/v1/food/log/', payload)
self.assertEqual(second.status_code, 201, second.content)
self.assertEqual(Decimal(self.call('get', '/api/v1/hydration/daily/').json()['food_ml']), 100)
self.assertEqual(self.call('get', f'/api/v1/food/log/{first.json()["id"]}/').json()['hydration_amount_ml'], '0.000')
self.client.force_login(self.a)
override = self.client.post(f'/food/product/{soup.pk}/hydration/',
{'is_beverage': 'on', 'hydration_enabled': 'on', 'hydration_factor': '1.000'})
self.assertEqual(override.status_code, 302, override.content)
soup.refresh_from_db()
self.assertEqual(soup.hydration_source, 'manual')
def test_hydration_daily_uses_user_local_manual_date(self):
UserSettings.objects.create(user=self.a, time_zone='America/Los_Angeles')
logged = self.call('post', '/api/v1/hydration/manual/', {'amount_ml': '250',
'recorded_at': '2026-01-01T01:00:00+00:00'})
self.assertEqual(logged.status_code, 201, logged.content)
previous = self.call('get', '/api/v1/hydration/daily/?date=2025-12-31').json()
next_day = self.call('get', '/api/v1/hydration/daily/?date=2026-01-01').json()
self.assertEqual(Decimal(previous['manual_ml']), 250)
self.assertEqual(Decimal(next_day['manual_ml']), 0)
def test_manual_and_inventory_crud(self):
manual = self.call('post', '/api/v1/food/log/', {'meal': 'lunch', 'amount': '1', 'unit': 'g',
'product_name': 'Homemade satay', 'calories_kcal': '850'})
self.assertEqual(manual.status_code, 201, manual.content)
self.assertIsNone(manual.json()['product_id'])
self.assertEqual(manual.json()['created_via'], 'api')
self.assertEqual(self.call('get', '/api/v1/food/today/').json()['totals']['calories_kcal'], '850.000')
payload = {'product_id': str(self.product_a.api_id), 'quantity': 2, 'location': 'Cupboard'}
created = self.call('post', '/api/v1/kitchen/items/', payload, HTTP_IDEMPOTENCY_KEY='item-1')
self.assertEqual(created.status_code, 201, created.content)
self.assertEqual(self.call('post', '/api/v1/kitchen/items/', payload, HTTP_IDEMPOTENCY_KEY='item-1').status_code, 200)
identifier = created.json()['id']
self.assertEqual(self.call('get', '/api/v1/kitchen/items/?search=Pasta').json()['count'], 1)
self.assertEqual(self.call('patch', f'/api/v1/kitchen/items/{identifier}/', {'quantity': 3}).json()['quantity'], 3)
self.assertEqual(self.call('delete', f'/api/v1/kitchen/items/{identifier}/').status_code, 200)
def test_today_uses_user_timezone(self):
UserSettings.objects.create(user=self.a, time_zone='America/Los_Angeles')
with patch('planner.timezones.timezone.now', return_value=datetime(2026, 1, 1, 1, tzinfo=py_timezone.utc)):
self.assertEqual(self.call('get', '/api/v1/food/today/').json()['date'], '2025-12-31')
def test_product_lookup_create_and_duplicate_protection(self):
local = self.call('get', '/api/v1/food/products/lookup/?barcode=123456&include_open_food_facts=false')
self.assertEqual(local.json()['matches'], [])
payload = {'name': 'Oat milk', 'brand': 'Example', 'barcode': '123456',
'package_quantity': '1000', 'package_unit': 'ml'}
first = self.call('post', '/api/v1/food/products/create/', payload, HTTP_IDEMPOTENCY_KEY='new-oats')
self.assertEqual(first.status_code, 201, first.content)
self.assertEqual(first.json()['product']['package_amount'], '1000')
self.assertIsNone(first.json()['product']['energy_kcal_100'])
match = self.call('get', '/api/v1/food/products/lookup/?barcode=123456')
self.assertEqual(match.json()['matches'][0]['confidence'], 'exact_barcode')
self.assertEqual(match.json()['matches'][0]['product_id'], first.json()['product_id'])
by_name = self.call('get', '/api/v1/food/products/lookup/?query=Oat&brand=Example&package_quantity=1000&package_unit=ml&include_open_food_facts=false')
self.assertEqual(by_name.json()['matches'][0]['product_id'], first.json()['product_id'])
exact_name = self.call('get', '/api/v1/food/products/lookup/?query=Oat%20milk&brand=Example&package_quantity=1000&package_unit=ml&include_open_food_facts=false')
self.assertEqual(exact_name.json()['matches'][0]['confidence'], 'exact_details')
again = self.call('post', '/api/v1/food/products/create/', {**payload, 'name': 'Changed name'})
self.assertEqual(again.json()['status'], 'reused')
self.assertEqual(FoodProduct.objects.filter(owner=self.a).count(), 2)
self.assertEqual(FoodProduct.objects.get(owner=self.a, barcode='123456').product_name, 'Oat milk')
conflict = self.call('post', '/api/v1/food/products/create/', {**payload, 'brand': 'Other'},
HTTP_IDEMPOTENCY_KEY='new-oats')
self.assertEqual(conflict.status_code, 409)
self.assertEqual(self.call('post', '/api/v1/food/products/create/',
{'name': 'Bad', 'package_quantity': '-1', 'package_unit': 'g'}).status_code, 400)
self.assertEqual(self.call('post', '/api/v1/food/products/create/',
{'name': 'Bad', 'nutrition_per_100': {'calories_kcal': '-1'}}).status_code, 400)
@patch('food.services.openfoodfacts.OpenFoodFactsClient.get_product')
def test_open_food_facts_lookup_and_import(self, get_product):
sample = {'code': '87654321', 'product_name': 'Yoghurt', 'brands': 'Example',
'quantity': '500 g', 'nutriments': {'energy-kcal_100g': 60}}
get_product.return_value = sample
lookup = self.call('get', '/api/v1/food/products/lookup/?barcode=87654321').json()
self.assertEqual(lookup['matches'][0]['source'], 'open_food_facts')
self.assertEqual(FoodProduct.objects.filter(owner=self.a).count(), 1)
imported = self.call('post', '/api/v1/food/products/import/', {'barcode': '87654321'})
self.assertEqual(imported.status_code, 201, imported.content)
self.assertEqual(imported.json()['product']['package_amount'], '500.000')
self.assertIsNone(imported.json()['product']['protein_100'])
self.assertEqual(self.call('post', '/api/v1/food/products/import/', {'barcode': '87654321'}).json()['status'], 'reused')
get_product.return_value = None
self.assertEqual(self.call('post', '/api/v1/food/products/import/', {'barcode': '999999'}).status_code, 404)
get_product.side_effect = OpenFoodFactsError('Open Food Facts is temporarily unavailable.')
self.assertEqual(self.call('get', '/api/v1/food/products/lookup/?barcode=999999').json()['external_error'],
'Open Food Facts is temporarily unavailable.')
def test_batch_grocery_partial_success_and_idempotency(self):
payload = {'create_missing_products': True, 'items': [
{'name': 'Loose apples', 'quantity': 2, 'location': 'Fridge'},
{'name': 'Broken', 'quantity': -1, 'location': 'Fridge'},
]}
first = self.call('post', '/api/v1/kitchen/import-groceries/', payload, HTTP_IDEMPOTENCY_KEY='groceries-1')
self.assertEqual(first.status_code, 200, first.content)
self.assertEqual(first.json()['status'], 'partial_success')
self.assertEqual([row['status'] for row in first.json()['items']], ['added', 'skipped'])
self.assertEqual(KitchenInventoryItem.objects.filter(user=self.a).count(), 1)
self.assertEqual(FoodProduct.objects.filter(owner=self.a).count(), 2)
second = self.call('post', '/api/v1/kitchen/import-groceries/', payload, HTTP_IDEMPOTENCY_KEY='groceries-1')
self.assertEqual(second.json(), first.json())
self.assertEqual(KitchenInventoryItem.objects.filter(user=self.a).count(), 1)
self.assertEqual(self.call('post', '/api/v1/kitchen/import-groceries/',
{**payload, 'items': [{'name': 'Pears', 'location': 'Fridge'}]},
HTTP_IDEMPOTENCY_KEY='groceries-1').status_code, 409)
self.assertEqual(self.call('post', '/api/v1/kitchen/import-groceries/',
{'items': [{'product_id': str(self.product_b.api_id), 'location': 'Fridge'}]},
HTTP_IDEMPOTENCY_KEY='other-user-product').json()['items'][0]['status'], 'skipped')
def test_ambiguous_product_requires_review_and_partial_contents_require_one_package(self):
FoodProduct.objects.create(owner=self.a, product_name='Yoghurt', brand='Store A',
package_quantity='500 g', package_amount=Decimal('500'), package_unit='g')
FoodProduct.objects.create(owner=self.a, product_name='Yoghurt', brand='Store B',
package_quantity='500 g', package_amount=Decimal('500'), package_unit='g')
candidates = self.call('post', '/api/v1/food/products/create/', {'name': 'Yoghurt'})
self.assertEqual(candidates.json()['status'], 'needs_review')
self.assertEqual(len(candidates.json()['candidates']), 2)
self.assertEqual(FoodProduct.objects.filter(owner=self.a, product_name='Yoghurt').count(), 2)
product = FoodProduct.objects.filter(owner=self.a, brand='Store A').first()
created = self.call('post', '/api/v1/kitchen/items/', {'product_id': str(product.api_id),
'quantity': 2, 'location': 'Fridge', 'opened': True, 'remaining_amount': '350'})
self.assertEqual(created.status_code, 201)
self.assertEqual(KitchenInventoryItem.objects.filter(user=self.a, product=product).count(), 2)
valid = self.call('post', '/api/v1/kitchen/items/', {'product_id': str(product.api_id),
'quantity': 1, 'location': 'Fridge', 'opened': True, 'remaining_amount': '350'})
self.assertEqual(valid.status_code, 201, valid.content)
self.assertEqual(valid.json()['remaining_amount'], '350')
def test_inventory_absolute_partial_updates_and_depletion(self):
meatballs = FoodProduct.objects.create(owner=self.a, product_name='Meatballs',
package_amount=Decimal('400'), package_unit='g')
location = InventoryLocation.objects.create(user=self.a, name='Fridge')
item = KitchenInventoryItem.objects.create(user=self.a, product=meatballs, location=location,
original_amount=Decimal('400'), remaining_amount=Decimal('400'), inventory_unit='g')
path = f'/api/v1/kitchen/items/{item.api_id}/'
first = self.call('patch', path, {'opened': True, 'remaining_amount': 280,
'notes': 'Used 120 g for dinner.'})
self.assertEqual(first.status_code, 200, first.content)
self.assertEqual(Decimal(first.json()['remaining_amount']), 280)
self.assertEqual(first.json()['notes'], 'Used 120 g for dinner.')
self.assertTrue(first.json()['opened'])
self.assertEqual(self.call('patch', path, {'remaining_amount': 280}).status_code, 200)
self.assertEqual(InventoryConsumption.objects.filter(user=self.a).count(), 1)
second = self.call('patch', path, {'remaining_amount': 130})
self.assertEqual(second.status_code, 200, second.content)
self.assertEqual(Decimal(second.json()['remaining_amount']), 130)
self.assertEqual(self.call('get', f'/api/v1/kitchen/stock/?product_id={meatballs.api_id}').json()
['products'][0]['totals']['g'], '130.000')
too_much = self.call('patch', path, {'remaining_amount': 401})
self.assertEqual(too_much.status_code, 400)
self.assertEqual(too_much.json()['error']['details']['field'], 'remaining_amount')
negative = self.call('patch', path, {'remaining_amount': -1})
self.assertEqual(negative.status_code, 400)
self.assertEqual(negative.json()['error']['details']['field'], 'remaining_amount')
self.assertEqual(self.call('patch', path, {'notes': 'Still in fridge'}).json()['notes'], 'Still in fridge')
depleted = self.call('patch', path, {'opened': True, 'remaining_amount': 0,
'notes': 'Used final 130 g.'})
self.assertEqual(depleted.status_code, 200, depleted.content)
self.assertEqual(depleted.json()['status'], 'depleted')
self.assertIsNotNone(depleted.json()['archived_at'])
self.assertEqual(self.call('get', path).status_code, 404)
self.assertEqual(self.call('get', f'/api/v1/kitchen/stock/?product_id={meatballs.api_id}').json()
['products'][0]['available'], False)
def test_inventory_depletes_only_one_identical_cup(self):
yoghurt = FoodProduct.objects.create(owner=self.a, product_name='Yoghurt cup',
package_amount=Decimal('175'), package_unit='g')
location = InventoryLocation.objects.create(user=self.a, name='Fridge')
cups = [KitchenInventoryItem.objects.create(user=self.a, product=yoghurt, location=location,
original_amount=Decimal('175'), remaining_amount=Decimal('175'), inventory_unit='g')
for _ in range(2)]
result = self.call('patch', f'/api/v1/kitchen/items/{cups[0].api_id}/',
{'opened': True, 'remaining_amount': 0, 'notes': 'Consumed one cup.'})
self.assertEqual(result.status_code, 200, result.content)
cups[0].refresh_from_db()
cups[1].refresh_from_db()
self.assertIsNotNone(cups[0].archived_at)
self.assertEqual(cups[1].remaining_amount, Decimal('175'))
self.assertIsNone(cups[1].archived_at)
stock = self.call('get', f'/api/v1/kitchen/stock/?product_id={yoghurt.api_id}').json()['products'][0]
self.assertEqual(stock['totals']['g'], '175.000')
self.assertEqual(len(stock['packages']), 1)
self.assertEqual(stock['packages'][0]['id'], str(cups[1].api_id))
self.assertEqual(self.call('patch', f'/api/v1/kitchen/items/{self.item_b.api_id}/',
{'remaining_amount': 0}).status_code, 404)
def test_inventory_stock_preview_consume_idempotency_undo_and_scopes(self):
product = FoodProduct.objects.create(owner=self.a, product_name='Stock butter',
package_amount=Decimal('250'), package_unit='g')
location = InventoryLocation.objects.create(user=self.a, name='Fridge')
for _ in range(2):
KitchenInventoryItem.objects.create(user=self.a, product=product, location=location,
original_amount=Decimal('250'), remaining_amount=Decimal('250'), inventory_unit='g')
base = '/api/v1/kitchen/'
stock = self.call('get', f'{base}stock/?product_id={product.api_id}').json()
self.assertEqual(stock['products'][0]['totals'], {'g': '500.000'})
payload = {'product_id': str(product.api_id), 'amount': '300', 'unit': 'g'}
preview = self.call('post', f'{base}consumption/preview/', payload).json()
self.assertEqual([row['amount'] for row in preview['deductions']], ['250.000', '50.000'])
self.assertEqual(self.call('post', f'{base}consumption/', payload).status_code, 400)
result = self.call('post', f'{base}consumption/', payload, HTTP_IDEMPOTENCY_KEY='stock-1')
self.assertEqual(result.status_code, 200, result.content)
again = self.call('post', f'{base}consumption/', payload, HTTP_IDEMPOTENCY_KEY='stock-1')
self.assertEqual(result.json(), again.json())
self.assertEqual(self.call('get', f'{base}stock/?product_id={product.api_id}').json()['products'][0]['totals'], {'g': '200.000'})
self.assertEqual(self.call('post', f'{base}consumption/{result.json()["transaction_id"]}/undo/', {}).status_code, 200)
self.assertEqual(self.call('get', f'{base}stock/?product_id={product.api_id}').json()['products'][0]['totals'], {'g': '500.000'})
self.assertEqual(self.call('get', f'{base}stock/?product_id={self.product_b.api_id}').status_code, 404)
_, read_secret = create_token(self.a, 'Inventory read', ['inventory:read'])
self.assertEqual(self.call('post', f'{base}consumption/preview/', payload, token=read_secret).status_code, 200)
self.assertEqual(self.call('post', f'{base}consumption/', payload, token=read_secret,
HTTP_IDEMPOTENCY_KEY='read-cannot-write').status_code, 403)
def test_barcode_mismatch_does_not_reuse_similar_product(self):
FoodProduct.objects.create(owner=self.a, product_name='Milk', brand='Example', barcode='11111',
package_amount=Decimal('1000'), package_unit='ml', package_quantity='1000 ml')
create = self.call('post', '/api/v1/food/products/create/', {'name': 'Milk', 'brand': 'Example',
'barcode': '22222', 'package_quantity': '1000', 'package_unit': 'ml'})
self.assertEqual(create.json()['status'], 'needs_review')
with patch('food.services.openfoodfacts.OpenFoodFactsClient.get_product', return_value=None):
response = self.call('post', '/api/v1/kitchen/import-groceries/', {'create_missing_products': True,
'items': [{'name': 'Milk', 'brand': 'Example', 'barcode': '22222',
'package_quantity': '1000', 'package_unit': 'ml', 'location': 'Fridge'}]},
HTTP_IDEMPOTENCY_KEY='different-milk-barcode')
self.assertEqual(response.json()['items'][0]['status'], 'needs_review')
self.assertEqual(KitchenInventoryItem.objects.filter(user=self.a).count(), 0)
def test_new_tools_respect_scopes_and_owner_isolation(self):
_, food_read = create_token(self.a, 'Food read', ['food:read'])
self.assertEqual(self.call('get', '/api/v1/food/products/lookup/?query=Pasta&include_open_food_facts=false', token=food_read).status_code, 200)
self.assertEqual(self.call('post', '/api/v1/food/products/create/', {'name': 'New'},
token=food_read).status_code, 403)
_, inventory_write = create_token(self.a, 'Inventory write', ['inventory:write'])
self.assertEqual(self.call('post', '/api/v1/kitchen/import-groceries/',
{'items': [{'name': 'New', 'location': 'Fridge'}], 'create_missing_products': True},
token=inventory_write).status_code, 403)
lookup = self.call('get', '/api/v1/food/products/lookup/?query=Private&include_open_food_facts=false')
self.assertEqual(lookup.json()['matches'], [])
def test_food_diary_accepts_specific_date(self):
entry = FoodLogEntry.objects.create(user=self.a, date=datetime(2026, 1, 2).date(), meal='breakfast',
product_name_snapshot='Oats', amount=Decimal('100'), unit='g', calories_kcal=Decimal('120'))
response = self.call('get', '/api/v1/food/today/?date=2026-01-02')
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json()['date'], '2026-01-02')
self.assertEqual(response.json()['meals']['breakfast'][0]['id'], str(entry.api_id))
self.assertEqual(response.json()['totals']['calories_kcal'], '120.000')
self.assertEqual(self.call('get', '/api/v1/food/today/?date=2026-01-03').json()['meals']['breakfast'], [])
for invalid in ('', 'yesterday', '2026-02-30', '2026-1-2'):
self.assertEqual(self.call('get', f'/api/v1/food/today/?date={invalid}').status_code, 400)
def test_fibre_api_totals_preserve_unknown_values(self):
FoodLogEntry.objects.create(user=self.a, date=timezone.localdate(), meal='breakfast',
product_name_snapshot='Unknown fibre', amount=Decimal('100'), unit='g')
response = self.call('get', '/api/v1/food/today/').json()
self.assertEqual(response['goals']['fibre_goal_g'], '40.0')
self.assertIsNone(response['totals']['fibre_g'])
self.assertTrue(response['fibre_incomplete'])
FoodLogEntry.objects.create(user=self.a, date=timezone.localdate(), meal='lunch',
product_name_snapshot='Known fibre', amount=Decimal('100'), unit='g', fibre_g=Decimal('6.5'))
response = self.call('get', '/api/v1/food/today/').json()
self.assertEqual(response['totals']['fibre_g'], '6.500')
self.assertTrue(response['fibre_incomplete'])
@override_settings(MEDIA_ROOT='/tmp/tasknest-api-test-media')
def test_attachment_validation_and_isolation(self):
entry = self.call('post', '/api/v1/food/log/', {'meal': 'lunch', 'amount': '1', 'unit': 'g',
'product_name': 'Soup'}).json()
path = f"/api/v1/food/log/{entry['id']}/attachments/"
bad = SimpleUploadedFile('bad.jpg', b'<script>x</script>', content_type='image/jpeg')
response = self.client.post(path, {'image': bad}, HTTP_AUTHORIZATION=f'Bearer {self.secret}')
self.assertEqual(response.status_code, 400)
image = Image.new('RGB', (2, 2), color='red')
stream = io.BytesIO()
image.save(stream, format='PNG')
mismatch = SimpleUploadedFile('wrong.jpg', stream.getvalue(), content_type='image/jpeg')
self.assertEqual(self.client.post(path, {'image': mismatch}, HTTP_AUTHORIZATION=f'Bearer {self.secret}').status_code, 400)
good = SimpleUploadedFile('photo.png', stream.getvalue(), content_type='image/png')
response = self.client.post(path, {'image': good}, HTTP_AUTHORIZATION=f'Bearer {self.secret}')
self.assertEqual(response.status_code, 201, response.content)
for image_format, content_type, filename in [('JPEG', 'image/jpeg', 'photo.jpg'),
('WEBP', 'image/webp', 'photo.webp')]:
stream = io.BytesIO()
image.save(stream, format=image_format)
upload = SimpleUploadedFile(filename, stream.getvalue(), content_type=content_type)
self.assertEqual(self.client.post(path, {'image': upload},
HTTP_AUTHORIZATION=f'Bearer {self.secret}').status_code, 201)
huge = SimpleUploadedFile('large.png', b'X' * (5 * 1024 * 1024 + 1), content_type='image/png')
self.assertEqual(self.client.post(path, {'image': huge},
HTTP_AUTHORIZATION=f'Bearer {self.secret}').status_code, 413)
identifier = response.json()['id']
_, other_secret = create_token(self.b, 'Other', ['food:read', 'food:write'])
self.assertEqual(self.call('get', f'/api/v1/food/attachments/{identifier}/file/', token=other_secret).status_code, 404)
self.assertEqual(self.call('delete', f'/api/v1/food/attachments/{identifier}/', token=other_secret).status_code, 404)
self.assertEqual(self.call('get', f'/api/v1/food/attachments/{identifier}/file/').status_code, 200)
def test_token_management_screen_shows_secret_once(self):
self.client.force_login(self.a)
self.assertEqual(self.client.get('/food/settings/tokens/').status_code, 200)
response = self.client.post('/food/settings/tokens/', {
'name': 'Phone', 'scopes': ['food:read', 'inventory:read']})
self.assertEqual(response.status_code, 200, response.content[:300])
self.assertContains(response, 'Copy this token now')
created = PersonalAccessToken.objects.get(user=self.a, name='Phone')
self.assertNotIn(created.token_hash, response.content.decode())
self.assertNotContains(self.client.get('/food/settings/tokens/'), 'Copy this token now')
self.assertEqual(self.client.post(f'/food/settings/tokens/{created.pk}/revoke/').status_code, 302)
created.refresh_from_db()
self.assertIsNotNone(created.revoked_at)
self.assertNotContains(self.client.get('/food/settings/tokens/'), 'Revoke Phone')
self.assertTrue(PersonalAccessToken.objects.filter(pk=created.pk).exists())
create_token(self.a, 'Expired token', ['food:read'], timezone.now() - timedelta(days=1))
self.assertNotContains(self.client.get('/food/settings/tokens/'), 'Expired token')
def test_api_fallback_errors_are_json(self):
response = self.call('get', '/api/v1/does-not-exist/')
self.assertEqual(response.status_code, 404)
self.assertEqual(response['Content-Type'], 'application/json')
class ConcurrentProductCreationTests(TransactionTestCase):
def test_concurrent_manual_creation_reuses_one_product(self):
if connection.vendor == 'sqlite':
self.skipTest('SQLite does not support select_for_update row locking.')
user = get_user_model().objects.create_user('concurrent-products', password='test')
_, secret = create_token(user, 'Product create', ['food:write'])
payload = json.dumps({'name': 'Milk', 'brand': 'Example',
'package_quantity': '1000', 'package_unit': 'ml'})
def create(_):
client = Client()
response = client.post('/api/v1/food/products/create/', data=payload,
content_type='application/json', HTTP_AUTHORIZATION=f'Bearer {secret}')
return response.status_code, response.json()
with ThreadPoolExecutor(max_workers=2) as pool:
results = list(pool.map(create, range(2)))
self.assertEqual(sorted(status for status, _ in results), [200, 201])
self.assertEqual(results[0][1]['product_id'], results[1][1]['product_id'])
self.assertEqual(FoodProduct.objects.filter(owner=user).count(), 1)