text: from django.contrib.auth import get_user_model
  from django.test import TestCase
  from django.urls import reverse
  
  from rest_framework import status
  from rest_framework.test import APIClient
  
  from core.models import Recipe, Tag, Ingredient
  
  from recipe.serializers import RecipeSerializer, RecipeDetailSerializer
  
  
  RECIPES_URL = reverse("recipe:recipe_list_create")
  
  
  def image_upload_url(pk):
      return reverse("recipe:recipe_detail", args=[pk, 'upload-image'])
  
  
  def sample_tag(user, name="Test Tag"):
      return Tag.objects.create(user=user, name=name)
  
  
  def sample_ingredient(user, name="Sugar"):
      return Ingredient.objects.create(user=user, name=name)
  
  
  def recipe_detail_url(pk):
      return reverse("recipe:recipe_detail", args=[pk])
  
  
  def sample_recipe(user, **params):
      """Create and return a sample recipe"""
      defaults = {
          "title": "Sample recipe",
          "time_minutes": 10,
          "price": 5.00,
      }
      defaults.update(params)
  
      return Recipe.objects.create(user=user, **defaults)
  
  
  class PublicRecipeApiTests(TestCase):
      """Test unauthenticated recipe API access"""
  
      def setUp(self):
          self.client = APIClient()
  
      def test_required_auth(self):
          """Test the authenticaiton is required"""
          res = self.client.get(RECIPES_URL)
  
          self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED)
  
  
  class PrivateRecipeApiTests(TestCase):
      """Test authenticated recipe API access"""
  
      def setUp(self):
          self.client = APIClient()
          self.user = get_user_model().objects.create_user(
              "test@londonappdev.com", "testpass"
          )
          self.client.force_authenticate(self.user)
  
      def test_retrieve_recipes(self):
          """Test retrieving list of recipes"""
          sample_recipe(user=self.user)
          sample_recipe(user=self.user)
  
          res = self.client.get(RECIPES_URL)
  
          recipes = Recipe.objects.all().order_by("-id")
          serializer = RecipeSerializer(recipes, many=True)
          self.assertEqual(res.status_code, status.HTTP_200_OK)
          self.assertEqual(res.data, serializer.data)
  
      def test_recipes_limited_to_user(self):
          """Test retrieving recipes for user"""
          user2 = get_user_model().objects.create_user(
              "other@londonappdev.com", "pass"
          )
          sample_recipe(user=user2)
          sample_recipe(user=self.user)
  
          res = self.client.get(RECIPES_URL)
  
          recipes = Recipe.objects.filter(user=self.user)
          serializer = RecipeSerializer(recipes, many=True)
          self.assertEqual(res.status_code, status.HTTP_200_OK)
          self.assertEqual(len(res.data), 1)
          self.assertEqual(res.data, serializer.data)
  
      def test_update_recipe(self):
          recipe = sample_recipe(user=self.user)
          payload = {"title": "yumy burger"}
  
          res = self.client.patch(recipe_detail_url(recipe.pk), payload)
          self.assertEqual(res.data["title"], "yumy burger")
  
      def test_view_recipe_datail(self):
          recipe = sample_recipe(user=self.user)
          recipe.tags.add(sample_tag(user=self.user))
          recipe.ingredients.add(sample_ingredient(user=self.user))
  
          url = recipe_detail_url(recipe.pk)
          res = self.client.get(url)
  
          serializer = RecipeDetailSerializer(recipe)
  
          self.assertEqual(res.data, serializer.data)
  
      def test_create_basic_recipe(self):
          payload = {"title": "Chocolate cake", "time_minutes": 30, "price": 22}
          res = self.client.post(RECIPES_URL, payload)
          self.assertEqual(res.status_code, status.HTTP_201_CREATED)
  
          recipe = Recipe.objects.get(id=res.data["id"])
          for key in payload.keys():
              self.assertEqual(payload[key], getattr(recipe, key))
  
      def test_create_recipe_with_tags(self):
          tag1 = sample_tag(user=self.user, name="Vegan")
          tag2 = sample_tag(user=self.user, name="Fatty")
  
          payload = {
              "title": "Some fatty stuff",
              "tags": [tag1.id, tag2.id],
              "time_minutes": 60,
              "price": 45,
          }
          res = self.client.post(RECIPES_URL, payload)
  
          self.assertEqual(res.status_code, status.HTTP_201_CREATED)
  
          recipe = Recipe.objects.get(id=res.data["id"])
          tags = recipe.tags.all()
  
          self.assertEqual(tags.count(), 2)
          self.assertIn(tag1, tags)
          self.assertIn(tag2, tags)
  
      def test_create_recipe_with_ingredients(self):
          ingredient1 = sample_ingredient(user=self.user, name="Sugar")
          ingredient2 = sample_ingredient(user=self.user, name="Milk")
          payload = {
              "title": "Cake",
              "ingredients": [ingredient1.id, ingredient2.id],
              "time_minutes": 5,
              "price": 99,
          }
          res = self.client.post(RECIPES_URL, payload)
          self.assertEqual(res.status_code, status.HTTP_201_CREATED)
          recipe = Recipe.objects.get(id=res.data["id"])
          ingredients = recipe.ingredients.all()
          self.assertEqual(ingredients.count(), 2)
          self.assertIn(ingredient1, ingredients)
          self.assertIn(ingredient2, ingredients)
  
      def test_filter_recipes_by_tags(self):
          recipe1 = sample_recipe(user=self.user, title='Yummy')
          recipe2 = sample_recipe(user=self.user, title='mmmm')
          tag1 = sample_tag(user=self.user, name='Fatty')
          tag2 = sample_tag(user=self.user, name='Vegan')
          recipe1.tags.add(tag1)
          recipe2.tags.add(tag2)
          recipe3 = sample_recipe(user=self.user, title='Coca cake')
  
          res = self.client.get(
              RECIPES_URL,
              {'tags': f'{tag1.id},{tag2.id}'}
          )
          serializer1 = RecipeSerializer(recipe1)
          serializer2 = RecipeSerializer(recipe2)
          serializer3 = RecipeSerializer(recipe3)
  
          self.assertIn(serializer1.data, res.data)
          self.assertIn(serializer2.data, res.data)
          self.assertNotIn(serializer3, res.data)
  
      def test_filte_recipes_by_ingredients(self):
          recipe1 = sample_recipe(user=self.user, title="Ymmm")
          recipe2 = sample_recipe(user=self.user, title="Burger")
          ingredient1 = sample_ingredient(user=self.user, name='sugar')
          ingredient2 = sample_ingredient(user=self.user, name='salt')
          recipe1.ingredients.add(ingredient1)
          recipe2.ingredients.add(ingredient2)
          recipe3 = sample_recipe(user=self.user, title='Pizza')
  
          res = self.client.get(
              RECIPES_URL,
              {'ingredients': f'{ingredient1.id},{ingredient2.id}'}
          )
  
          serializer1 = RecipeSerializer(recipe1)
          serializer2 = RecipeSerializer(recipe2)
          serializer3 = RecipeSerializer(recipe3)
  
          self.assertIn(serializer1.data, res.data)
          self.assertIn(serializer2.data, res.data)
          self.assertNotIn(serializer3.data, res.data)
  