food logger context tips

This commit is contained in:
Joren de Graaf
2026-10-11 15:21:10 +02:00
parent 559c51e9bb
commit 400e8254c0
51 changed files with 1988 additions and 41 deletions
+156 -2
View File
@@ -1,6 +1,7 @@
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
@@ -8,12 +9,14 @@ 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 TestCase, override_settings
from django.test import Client, TestCase, TransactionTestCase, override_settings
from django.db import connection
from django.utils import timezone
from planner.models import UserSettings
from .api import create_token
from .models import FoodLogEntry, FoodProduct, InventoryLocation, KitchenInventoryItem, PersonalAccessToken
from .services.openfoodfacts import OpenFoodFactsError
class FoodApiTests(TestCase):
@@ -105,6 +108,118 @@ class FoodApiTests(TestCase):
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()
invalid = self.call('post', '/api/v1/kitchen/items/', {'product_id': str(product.api_id),
'quantity': 2, 'location': 'Fridge', 'opened': True, 'remaining_amount': '350'})
self.assertEqual(invalid.status_code, 400)
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_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'))
@@ -112,11 +227,24 @@ class FoodApiTests(TestCase):
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')
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',
@@ -162,8 +290,34 @@ class FoodApiTests(TestCase):
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)