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, RecipeLink, 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_linked_recipe_and_composition_web_flows(self): main = Recipe.objects.create(owner=self.user, title='Main') side = Recipe.objects.create(owner=self.user, title='Side') other = Recipe.objects.create(owner=self.other, title='Private') response = self.client.post(reverse('recipes:link', args=[main.api_id]), { 'recipe_id': str(side.api_id), 'relationship': 'goes_well_with', 'note': 'Serve together', 'reciprocal': '1'}) self.assertRedirects(response, reverse('recipes:detail', args=[main.api_id])) link = RecipeLink.objects.get() edit_url = reverse('recipes:link-edit', args=[main.api_id, link.id]) self.assertContains(self.client.get(edit_url), 'Edit linked recipe') self.assertEqual(self.client.post(edit_url, { 'relationship': 'alternative_to', 'note': 'Different texture', 'reciprocal': ''}).status_code, 302) link.refresh_from_db() self.assertEqual((link.relationship, link.note, link.reciprocal), ('alternative_to', 'Different texture', False)) self.assertContains(self.client.get(reverse('recipes:detail', args=[side.api_id])), 'Main') response = self.client.post(reverse('recipes:link', args=[main.api_id]), { 'recipe_id': str(other.api_id), 'relationship': 'goes_well_with'}) self.assertEqual(response.status_code, 404) preview = self.client.post(reverse('recipes:compose'), { 'component': [str(main.api_id), str(side.api_id)], f'servings_{main.api_id}': '2', f'servings_{side.api_id}': '1', 'action': 'preview'}) self.assertEqual(preview.status_code, 200) self.assertContains(preview, 'Component preview') created = self.client.post(reverse('recipes:compose'), { 'title': 'Combined', 'default_servings': '2', 'component': [str(main.api_id), str(side.api_id)], f'servings_{main.api_id}': '2', f'servings_{side.api_id}': '1', 'action': 'create'}) self.assertEqual(created.status_code, 302) combined = Recipe.objects.get(title='Combined') self.assertEqual(set(combined.subrecipes.values_list('component_id', flat=True)), {main.pk, side.pk}) 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_detail_photo_drop_zone_upload_validates_and_scopes(self): recipe = Recipe.objects.create(owner=self.user, title='Photo target') image = BytesIO() Image.new('RGB', (2, 2), '#217857').save(image, format='PNG') url = reverse('recipes:photo-upload', args=[recipe.api_id]) with TemporaryDirectory() as media_root, override_settings(MEDIA_ROOT=media_root): self.assertContains(self.client.get(reverse('recipes:detail', args=[recipe.api_id])), 'Add a recipe photo') self.assertEqual(self.client.get(url).status_code, 405) self.assertEqual(self.client.post(url, {'photo': SimpleUploadedFile( 'bad.png', b'not an image', content_type='image/png')}).status_code, 302) recipe.refresh_from_db() self.assertFalse(recipe.photo) response = self.client.post(url, {'photo': SimpleUploadedFile( 'good.png', image.getvalue(), content_type='image/png')}) self.assertEqual(response.status_code, 302) recipe.refresh_from_db() self.assertTrue(recipe.photo) self.assertContains(self.client.get(reverse('recipes:detail', args=[recipe.api_id])), 'Photo of Photo target') self.client.force_login(self.other) self.assertEqual(self.client.post(url, {'photo': SimpleUploadedFile( 'other.png', image.getvalue(), content_type='image/png')}).status_code, 404) def test_markdown_round_trip_and_safe_rendering(self): source = '# Dinner\n\n- [x] Prepare\n- [ ] Cook\n\n**Ready** [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, '

Dinner

', html=True) self.assertContains(response, 'Ready', html=True) self.assertNotContains(response, '