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 from .api import create_token from .models import FoodLogEntry, FoodProduct, 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_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_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_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'', 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)