Files
Django_TasksApp/main/recipes/tests.py
T
2026-10-12 01:53:21 +02:00

230 lines
13 KiB
Python

import json
from decimal import Decimal
from io import BytesIO
from tempfile import TemporaryDirectory
from django.contrib.auth import get_user_model
from django.core.exceptions import ValidationError
from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import TestCase
from django.test.utils import override_settings
from django.urls import reverse
from PIL import Image
from .models import Recipe, RecipeIngredient, RecipeSubrecipe
from .templatetags.recipe_markdown import recipe_markdown
class RecipeWebTests(TestCase):
def setUp(self):
user_model = get_user_model()
self.user = user_model.objects.create_user(username='cook', password='test-password')
self.other = user_model.objects.create_user(username='other', password='test-password')
self.client.force_login(self.user)
def data(self, title='Noodles', **changes):
data = {
'title': title, 'description': 'A weeknight meal', 'category': 'Dinner',
'preparation_minutes': '10', 'cooking_minutes': '15',
'default_servings': '2', 'status': 'draft', 'tags_text': 'Asian, Quick',
'instructions_markdown': 'Cook the noodles.', 'notes_markdown': '',
'markdown_revision': '0',
'ingredients-TOTAL_FORMS': '1', 'ingredients-INITIAL_FORMS': '0',
'ingredients-MIN_NUM_FORMS': '0', 'ingredients-MAX_NUM_FORMS': '1000',
'ingredients-0-name': 'Noodles', 'ingredients-0-quantity': '250',
'ingredients-0-unit': 'g', 'ingredients-0-display_order': '0',
'subrecipes-TOTAL_FORMS': '0', 'subrecipes-INITIAL_FORMS': '0',
'subrecipes-MIN_NUM_FORMS': '0', 'subrecipes-MAX_NUM_FORMS': '1000',
}
data.update(changes)
return data
def test_create_search_filter_edit_favourite_and_delete(self):
response = self.client.post(reverse('recipes:create'), self.data())
self.assertEqual(response.status_code, 302)
recipe = Recipe.objects.get(owner=self.user)
self.assertEqual(recipe.tags, ['Asian', 'Quick'])
self.assertEqual(recipe.ingredients.get().quantity, Decimal('250'))
self.assertContains(self.client.get(reverse('recipes:list'), {'q': 'Noodles'}), 'Noodles')
self.assertContains(self.client.get(reverse('recipes:list'), {'tag': 'Asian'}), 'Noodles')
self.assertNotContains(self.client.get(reverse('recipes:list'), {'tag': 'Other'}), 'A weeknight meal')
self.client.post(reverse('recipes:favourite', args=[recipe.api_id]))
recipe.refresh_from_db()
self.assertTrue(recipe.is_favourite)
edit_data = self.data('Updated noodles', **{
'ingredients-INITIAL_FORMS': '1', 'ingredients-0-id': str(recipe.ingredients.get().pk),
'ingredients-0-quantity': '300',
})
self.assertEqual(self.client.post(reverse('recipes:edit', args=[recipe.api_id]), edit_data).status_code, 302)
recipe.refresh_from_db()
self.assertEqual(recipe.title, 'Updated noodles')
self.assertEqual(recipe.ingredients.get().quantity, Decimal('300'))
self.assertEqual(self.client.post(reverse('recipes:delete', args=[recipe.api_id])).status_code, 302)
self.assertFalse(Recipe.objects.filter(pk=recipe.pk).exists())
def test_owner_isolation(self):
recipe = Recipe.objects.create(owner=self.other, title='Private')
for name in ('detail', 'edit', 'delete', 'photo'):
self.assertEqual(self.client.get(reverse(f'recipes:{name}', args=[recipe.api_id])).status_code, 404)
self.assertEqual(self.client.post(reverse('recipes:favourite', args=[recipe.api_id])).status_code, 404)
self.assertNotContains(self.client.get(reverse('recipes:list')), 'Private')
def test_invalid_ingredient_does_not_create_recipe(self):
response = self.client.post(reverse('recipes:create'), self.data(**{'ingredients-0-quantity': '-1'}))
self.assertEqual(response.status_code, 200)
self.assertFalse(Recipe.objects.exists())
def test_subrecipe_ownership_and_cycles(self):
a = Recipe.objects.create(owner=self.user, title='A')
b = Recipe.objects.create(owner=self.user, title='B')
other = Recipe.objects.create(owner=self.other, title='Other')
RecipeSubrecipe.objects.create(recipe=a, component=b)
with self.assertRaises(ValidationError):
RecipeSubrecipe(recipe=b, component=a).full_clean()
with self.assertRaises(ValidationError):
RecipeSubrecipe(recipe=a, component=other).full_clean()
with self.assertRaises(ValidationError):
RecipeIngredient(recipe=a, name='Flour', quantity=Decimal('-1'), unit='g').full_clean()
def test_photo_upload_is_private(self):
image = BytesIO()
Image.new('RGB', (2, 2), '#217857').save(image, format='PNG')
with TemporaryDirectory() as media_root, override_settings(MEDIA_ROOT=media_root):
data = self.data()
data['photo'] = SimpleUploadedFile('noodles.png', image.getvalue(), content_type='image/png')
self.assertEqual(self.client.post(reverse('recipes:create'), data).status_code, 302)
recipe = Recipe.objects.get(owner=self.user)
photo_url = reverse('recipes:photo', args=[recipe.api_id])
self.assertEqual(self.client.get(photo_url).status_code, 200)
self.client.force_login(self.other)
self.assertEqual(self.client.get(photo_url).status_code, 404)
def test_markdown_round_trip_and_safe_rendering(self):
source = '# Dinner\n\n- [x] Prepare\n- [ ] Cook\n\n**Ready** <script>alert(1)</script> [bad](javascript:alert(1))'
recipe = Recipe.objects.create(owner=self.user, title='Dinner', instructions_markdown=source)
response = self.client.get(reverse('recipes:detail', args=[recipe.api_id]))
self.assertContains(response, '<h1>Dinner</h1>', html=True)
self.assertContains(response, '<strong>Ready</strong>', html=True)
self.assertNotContains(response, '<script>')
self.assertNotContains(response, 'href="javascript:')
self.assertEqual(Recipe.objects.get(pk=recipe.pk).instructions_markdown, source)
self.assertIn('type="checkbox"', recipe_markdown(source))
def test_autosave_rejects_stale_revision_and_other_owner(self):
recipe = Recipe.objects.create(owner=self.user, title='Dinner')
url = reverse('recipes:autosave', args=[recipe.api_id])
payload = {'revision': 0, 'title': 'Dinner',
'instructions_markdown': '# First', 'notes_markdown': 'Notes'}
response = self.client.post(url, json.dumps(payload), content_type='application/json')
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json()['revision'], 1)
stale = self.client.post(url, json.dumps({**payload, 'instructions_markdown': '# Stale'}),
content_type='application/json')
self.assertEqual(stale.status_code, 409)
recipe.refresh_from_db()
self.assertEqual(recipe.instructions_markdown, '# First')
self.client.force_login(self.other)
self.assertEqual(self.client.post(url, json.dumps(payload), content_type='application/json').status_code, 404)
def test_new_draft_autosave_is_idempotent(self):
import uuid
draft_id = str(uuid.uuid4())
payload = {'draft_id': draft_id, 'title': 'Quick lunch',
'instructions_markdown': '# Start', 'notes_markdown': ''}
url = reverse('recipes:autosave-new')
first = self.client.post(url, json.dumps(payload), content_type='application/json')
second = self.client.post(url, json.dumps(payload), content_type='application/json')
self.assertEqual(first.status_code, 200)
self.assertEqual(second.status_code, 200)
self.assertEqual(Recipe.objects.filter(owner=self.user).count(), 1)
recipe = Recipe.objects.get(owner=self.user)
self.assertEqual(recipe.markdown_revision, 1)
self.assertEqual(first.json()['edit_url'], reverse('recipes:edit', args=[recipe.api_id]))
changed = self.client.post(url, json.dumps({**payload, 'instructions_markdown': 'Stale'}),
content_type='application/json')
self.assertEqual(changed.status_code, 409)
resumed = self.data('Quick lunch finished', draft_id=draft_id)
self.assertEqual(self.client.post(reverse('recipes:create'), resumed).status_code, 302)
self.assertEqual(Recipe.objects.filter(owner=self.user).count(), 1)
recipe.refresh_from_db()
self.assertEqual(recipe.title, 'Quick lunch finished')
self.client.force_login(self.other)
self.assertEqual(self.client.post(url, json.dumps(payload), content_type='application/json').status_code, 404)
def test_manual_create_retry_uses_same_draft(self):
import uuid
data = self.data(draft_id=str(uuid.uuid4()))
url = reverse('recipes:create')
self.assertEqual(self.client.post(url, data).status_code, 302)
self.assertEqual(self.client.post(url, data).status_code, 302)
self.assertEqual(Recipe.objects.filter(owner=self.user).count(), 1)
def test_variation_copies_independent_content(self):
parent = Recipe.objects.create(owner=self.user, title='Dinner', instructions_markdown='Original')
RecipeIngredient.objects.create(recipe=parent, name='Noodles', quantity=Decimal('250'), unit='g')
component = Recipe.objects.create(owner=self.user, title='Sauce')
RecipeSubrecipe.objects.create(recipe=parent, component=component)
response = self.client.post(reverse('recipes:create-variation', args=[parent.api_id]))
self.assertEqual(response.status_code, 302)
variation = Recipe.objects.get(parent=parent)
self.assertNotEqual(variation.pk, parent.pk)
self.assertEqual(variation.ingredients.get().quantity, Decimal('250'))
self.assertEqual(variation.subrecipes.get().component, component)
edit_data = self.data('Spicy dinner', **{
'instructions_markdown': '# Spicy steps',
'ingredients-INITIAL_FORMS': '1',
'ingredients-0-id': str(variation.ingredients.get().pk),
'ingredients-0-quantity': '300',
'subrecipes-TOTAL_FORMS': '1',
'subrecipes-INITIAL_FORMS': '1',
'subrecipes-0-id': str(variation.subrecipes.get().pk),
'subrecipes-0-component': str(component.pk),
'subrecipes-0-quantity': '1',
'subrecipes-0-unit': 'servings',
'subrecipes-0-display_order': '0',
})
self.assertEqual(self.client.post(reverse('recipes:edit', args=[variation.api_id]), edit_data).status_code, 302)
variation.refresh_from_db()
self.assertEqual(variation.title, 'Spicy dinner')
self.assertEqual(variation.instructions_markdown, '# Spicy steps')
self.assertEqual(variation.ingredients.get().quantity, Decimal('300'))
self.assertEqual(parent.ingredients.get().quantity, Decimal('250'))
parent.instructions_markdown = 'Changed original'
parent.save()
variation.refresh_from_db()
self.assertEqual(variation.instructions_markdown, '# Spicy steps')
self.client.force_login(self.other)
self.assertEqual(self.client.post(reverse('recipes:create-variation', args=[parent.api_id])).status_code, 404)
def test_subrecipe_form_rejects_cycle_and_foreign_component(self):
main = Recipe.objects.create(owner=self.user, title='Main')
sauce = Recipe.objects.create(owner=self.user, title='Sauce')
foreign = Recipe.objects.create(owner=self.other, title='Foreign')
component_data = {
'subrecipes-TOTAL_FORMS': '1', 'subrecipes-0-component': str(sauce.pk),
'subrecipes-0-quantity': '2', 'subrecipes-0-unit': 'servings',
'subrecipes-0-display_order': '0',
}
url = reverse('recipes:edit', args=[main.api_id])
self.assertEqual(self.client.post(url, self.data(**component_data)).status_code, 302)
self.assertEqual(main.subrecipes.get().component, sauce)
cycle_data = {**component_data, 'subrecipes-0-component': str(main.pk)}
response = self.client.post(reverse('recipes:edit', args=[sauce.api_id]), self.data(**cycle_data))
self.assertEqual(response.status_code, 200)
self.assertFalse(sauce.subrecipes.exists())
foreign_data = {**component_data, 'subrecipes-0-component': str(foreign.pk)}
response = self.client.post(reverse('recipes:edit', args=[sauce.api_id]), self.data(**foreign_data))
self.assertEqual(response.status_code, 200)
self.assertFalse(sauce.subrecipes.exists())
def test_full_form_rejects_stale_markdown_revision(self):
recipe = Recipe.objects.create(owner=self.user, title='Original')
recipe.instructions_markdown = 'Newer Markdown'
recipe.markdown_revision = 1
recipe.save()
response = self.client.post(reverse('recipes:edit', args=[recipe.api_id]), self.data('Stale title'))
self.assertEqual(response.status_code, 200)
recipe.refresh_from_db()
self.assertEqual(recipe.title, 'Original')
self.assertEqual(recipe.instructions_markdown, 'Newer Markdown')