How to use test_recipe method in avocado

Best Python code snippet using avocado_python

test_recipe_api.py

Source:test_recipe_api.py Github

copy

Full Screen

...29 """30 Create and return a sample test ingredient31 """32 return Ingredient.objects.create(user=user, name=name)33def test_recipe(user, **params):34 """35 Create and return a sample test recipe36 """37 defaults = {38 'title': 'testing recipe',39 'duration': 10,40 'price': 5.00,41 }42 defaults.update(params)43 return Recipe.objects.create(user=user, **defaults)44class PublicRecipeApiTests(TestCase):45 """46 Test public access of recipe API47 """48 def setUp(self):49 self.client = APIClient()50 def test_required_auth(self):51 """52 Test that authentication is required53 """54 res = self.client.get(RECIPES_URL)55 self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED)56class PrivateRecipeApiTests(TestCase):57 """58 Test that access to protected API is authenticated59 """60 def setUp(self):61 self.client = APIClient()62 self.user = get_user_model().objects.create_user(63 'test@webgurus.co.ke',64 'testpass'65 )66 self.client.force_authenticate(self.user)67 def test_retrieve_recipes(self):68 """69 Test retrieving list of recipes70 """71 # sample recipes list72 test_recipe(user=self.user)73 test_recipe(user=self.user)74 res = self.client.get(RECIPES_URL)75 recipes = Recipe.objects.all().order_by('-id')76 serializer = RecipeSerializer(recipes, many=True)77 self.assertEqual(res.status_code, status.HTTP_200_OK)78 self.assertEqual(res.data, serializer.data)79 def test_recipes_limited_to_user(self):80 """81 Test retrieving recipes for specific user82 """83 user2 = get_user_model().objects.create_user(84 'other@webgurus.co.ke',85 'pass24638'86 )87 test_recipe(user=user2)88 test_recipe(user=self.user)89 res = self.client.get(RECIPES_URL)90 recipes = Recipe.objects.filter(user=self.user)91 serializer = RecipeSerializer(recipes, many=True)92 self.assertEqual(res.status_code, status.HTTP_200_OK)93 self.assertEqual(len(res.data), 1)94 self.assertEqual(res.data, serializer.data)95 def test_details_recipe_view(self):96 """97 Test viewing a recipe detail98 """99 recipe = test_recipe(user=self.user)100 recipe.tags.add(test_tag(user=self.user))101 recipe.ingredients.add(test_ingredient(user=self.user))102 url = detail_recipe_url(recipe.id)103 res = self.client.get(url)104 serializer = RecipeDetailSerializer(recipe)105 self.assertEqual(res.data, serializer.data)106 def test_create_basic_recipe(self):107 """108 Test creating a new recipe109 """110 payload = {111 'title': 'Test recipe',112 'duration': 30,113 'price': 10.00,114 }115 res = self.client.post(RECIPES_URL, payload)116 self.assertEqual(res.status_code, status.HTTP_201_CREATED)117 recipe = Recipe.objects.get(id=res.data['id'])118 for key in payload.keys():119 self.assertEqual(payload[key], getattr(recipe, key))120 def test_create_recipe_with_tags(self):121 """122 Test creating a recipe with tags123 """124 # sample tags125 tag1 = test_tag(user=self.user, name='Tag 1')126 tag2 = test_tag(user=self.user, name='Tag 2')127 payload = {128 'title': 'Test recipe with two tags',129 'tags': [tag1.id, tag2.id],130 'duration': 30,131 'price': 10.00132 }133 res = self.client.post(RECIPES_URL, payload)134 self.assertEqual(res.status_code, status.HTTP_201_CREATED)135 recipe = Recipe.objects.get(id=res.data['id'])136 tags = recipe.tags.all()137 self.assertEqual(tags.count(), 2)138 self.assertIn(tag1, tags)139 self.assertIn(tag2, tags)140 def test_create_recipe_with_ingredients(self):141 """142 Test creating recipe with ingredients143 """144 ingredient1 = test_ingredient(user=self.user, name='Ingredient 1')145 ingredient2 = test_ingredient(user=self.user, name='Ingredient 2')146 payload = {147 'title': 'Test recipe with ingredients',148 'ingredients': [ingredient1.id, ingredient2.id],149 'duration': 45,150 'price': 15.00151 }152 res = self.client.post(RECIPES_URL, payload)153 self.assertEqual(res.status_code, status.HTTP_201_CREATED)154 recipe = Recipe.objects.get(id=res.data['id'])155 ingredients = recipe.ingredients.all()156 self.assertEqual(ingredients.count(), 2)157 self.assertIn(ingredient1, ingredients)158 self.assertIn(ingredient2, ingredients)159 def test_partial_update_recipe(self):160 """161 Test updating a recipe with http patch method162 """163 recipe = test_recipe(user=self.user)164 recipe.tags.add(test_tag(user=self.user))165 new_tag = test_tag(user=self.user, name='Curry')166 payload = {167 'title': 'Chicken tikka',168 'tags': [new_tag.id]169 }170 url = detail_recipe_url(recipe.id)171 self.client.patch(url, payload)172 recipe.refresh_from_db()173 self.assertEqual(recipe.title, payload['title'])174 tags = recipe.tags.all()175 self.assertEqual(len(tags), 1)176 self.assertIn(new_tag, tags)177 def test_full_update_recipe(self):178 """179 Test updating a recipe with http put method180 """181 recipe = test_recipe(user=self.user)182 recipe.tags.add(test_tag(user=self.user))183 payload = {184 'title': 'Spaghetti carbonara',185 'duration': 25,186 'price': 5.00187 }188 url = detail_recipe_url(recipe.id)189 self.client.put(url, payload)190 recipe.refresh_from_db()191 self.assertEqual(recipe.title, payload['title'])192 self.assertEqual(recipe.duration, payload['duration'])193 self.assertEqual(recipe.price, payload['price'])194 tags = recipe.tags.all()195 self.assertEqual(len(tags), 0)196class RecipeImageUploadTests(TestCase):197 """198 Test class for recipe model image upload199 """200 def setUp(self):201 self.client = APIClient()202 self.user = get_user_model().objects.create_user('user', 'testpass')203 self.client.force_authenticate(self.user)204 self.recipe = test_recipe(user=self.user)205 def tearDown(self):206 """207 Clean up function (for removing temp files)208 """209 self.recipe.image.delete()210 def test_upload_image_to_recipe(self):211 """212 Test successful uploading of an image to recipe model213 """214 url = image_upload_url(self.recipe.id)215 # named temp file216 with tempfile.NamedTemporaryFile(suffix='.jpg') as ntf:217 img = Image.new('RGB', (10, 10))218 img.save(ntf, format='JPEG')219 ntf.seek(0)220 res = self.client.post(url, {'image': ntf}, format='multipart')221 self.recipe.refresh_from_db()222 self.assertEqual(res.status_code, status.HTTP_200_OK)223 self.assertIn('image', res.data)224 self.assertTrue(os.path.exists(self.recipe.image.path))225 def test_upload_image_bad_request(self):226 """227 Test uploading an invalid or empty image228 """229 url = image_upload_url(self.recipe.id)230 res = self.client.post(url, {'image': 'notimage'}, format='multipart')231 self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)232 def test_filter_recipes_by_tags(self):233 """234 Test filtering recipes with specific tag235 """236 recipe1 = test_recipe(user=self.user, title='Recipe test 1')237 recipe2 = test_recipe(user=self.user, title='Recipe test 2')238 recipe3 = test_recipe(user=self.user, title='Recipe test 3')239 tag1 = test_tag(user=self.user, name='Test tag 1')240 tag2 = test_tag(user=self.user, name='Test tag 2')241 recipe1.tags.add(tag1)242 recipe2.tags.add(tag2)243 res = self.client.get(244 RECIPES_URL,245 {'tags': '{},{}'.format(tag1.id, tag2.id)}246 )247 serializer1 = RecipeSerializer(recipe1)248 serializer2 = RecipeSerializer(recipe2)249 serializer3 = RecipeSerializer(recipe3)250 self.assertIn(serializer1.data, res.data)251 self.assertIn(serializer2.data, res.data)252 self.assertNotIn(serializer3.data, res.data)253 def test_filter_recipes_by_ingredients(self):254 """255 Test filtering recipes with specific ingredient256 """257 recipe1 = test_recipe(user=self.user, title='Recipe test 4')258 recipe2 = test_recipe(user=self.user, title='Recipe test 5')259 recipe3 = test_recipe(user=self.user, title='Recipe test 6')260 ingredient1 = test_ingredient(261 user=self.user, name='Test ingredient 6')262 ingredient2 = test_ingredient(263 user=self.user, name='Test ingredient 7')264 recipe1.ingredients.add(ingredient1)265 recipe2.ingredients.add(ingredient2)266 res = self.client.get(267 RECIPES_URL,268 {'ingredients': '{},{}'.format(ingredient1.id, ingredient2.id)}269 )270 serializer1 = RecipeSerializer(recipe1)271 serializer2 = RecipeSerializer(recipe2)272 serializer3 = RecipeSerializer(recipe3)273 self.assertIn(serializer1.data, res.data)...

Full Screen

Full Screen

test_models.py

Source:test_models.py Github

copy

Full Screen

1from string import capwords2from django.contrib.auth.models import User3from django.test import TestCase4from django.utils import timezone5from django.utils.text import slugify6from ingredients.models import Ingredient, Unit7from recipes.models import Recipe, Rating, RecipeIngredient, user_directory_path8class RecipeTestCase(TestCase):9 def setUp(self):10 self.user = User.objects.create(username='test')11 self.r = Recipe.objects.create(author=self.user, title='test', description='')12 self.a = Recipe.objects.create(author=self.user, title='test', description='')13 self.time = timezone.now()14 def test_description_default_upon_missing_description(self):15 test_recipe = Recipe.objects.create(author=self.user, title='test')16 self.assertTrue(test_recipe.description)17 self.assertEquals(test_recipe.description, "No description provided.")18 def test_steps_default_upon_missing_steps(self):19 test_recipe = Recipe.objects.create(author=self.user, title='test')20 self.assertTrue(test_recipe.steps)21 self.assertEquals(test_recipe.steps, "No steps provided. Time to get creative!")22 def test_steps_split_when_newlines_entered(self):23 expected = ['step1', 'step2']24 recipe = Recipe.objects.create(author=self.user, title='test', steps='step1\n\nstep2')25 self.assertEqual(recipe.step_list(), expected)26 def test_str_representation(self):27 recipe = Recipe.objects.create(author=self.user, title='another', description='')28 self.assertEqual(str(recipe), recipe.title)29 def test_str_representation_two_same_recipe_names_are_same(self):30 self.assertEqual(str(self.r), self.r.title)31 def test_date_field(self):32 """ Pretty lame test! """33 self.assertNotEquals(self.r.date, self.time)34 def test_slug_field_remains_the_same_upon_title_change(self):35 title = self.r.title36 self.r.title = 'test2'37 self.assertEqual(self.r.slug, title.lower())38 self.assertNotEquals(self.r.slug, slugify(self.r.title))39 def test_unique_slug_creation(self):40 count = len(Recipe.objects.all())41 # Need to turn chars into lower form, as title is capitalized.42 expected = f'{self.a.title.lower()}-{count}'43 self.assertEqual(self.a.slug, expected)44 def test_capitalisation(self):45 title = 'test test test'46 r = Recipe.objects.create(author=self.user, title=title)47 self.assertEqual(r.title, capwords(title))48 def test_slug_field_is_unique(self):49 self.assertNotEquals(self.a.slug, self.r.slug)50class RatingTestCase(TestCase):51 def setUp(self):52 self.user = User.objects.create(username='test')53 self.r = Recipe.objects.create(author=self.user, title='test', description='')54 self.rating = Rating.objects.create(user=self.user, recipe=self.r, stars=1)55 def test_str_representation(self):56 username = self.user.username57 stars = self.rating.stars58 expected = f'{username}\'s {self.r} rating: {stars}'59 self.assertEqual(str(self.rating), expected)60class RecipeIngredientTestCase(TestCase):61 def setUp(self):62 self.user = User.objects.create(username='test')63 self.r = Recipe.objects.create(author=self.user, title='test')64 self.i = Ingredient.objects.create(name='Meat', type='Meat')65 self.unit = Unit.objects.create(name='kilogram', abbrev='kg')66 self.ri = RecipeIngredient.objects.create(recipe=self.r, ingredient=self.i, unit=self.unit,67 quantity=1)68 def test_str_representation(self):69 expected = f'{self.i} in {self.r}'70 self.assertEqual(str(self.ri), expected)71# Function is currently not used.72class UserDirectoryPathTests(TestCase):73 def setUp(self):74 self.user = User.objects.create(username='test')75 self.r = Recipe.objects.create(author=self.user, title='test')76 self.path = user_directory_path(self.r, 'test-path')77 def test_path(self):78 """ Ensure that a constructed path is correct. """79 expected = f'user_{self.user.id}/test-path'...

Full Screen

Full Screen

test_recipe.py

Source:test_recipe.py Github

copy

Full Screen

1# -*- coding: utf-8 -*-2from __future__ import print_function3import unittest4from unittest import TestCase5from modules import recipe6class TestRecipe(TestCase):7 """8 Test if the recipe id, title, list of products and chef data are correctly stored 9 """10 def setUp(self):11 self.test_recipe = recipe.Recipe(1, [u"Мусака без домати (Бяла мусака)"],12 [u"картофи 8 бр. едри", u"кайма 350 , 400 г смес", u"лук 1 глава",13 u"олио 3, 4 суп.лъж.", u"чубрица", u"черен пипер", u"магданоз"],14 [u"name: Илияна Димова",15 u"hats: 4000.0",16 u"hearts: 4000.0",17 u"plates: 1000.0",18 u"Rating: 3000.0"])19 def test_recipe_id(self):20 self.assertEqual(1, self.test_recipe.id)21 def test_recipe_title(self):22 self.assertEqual([u"Мусака без домати (Бяла мусака)"], self.test_recipe.title)23 def test_recipe_products(self):24 self.assertEqual([u"картофи 8 бр. едри", u"кайма 350 , 400 г смес", u"лук 1 глава",25 u"олио 3, 4 суп.лъж.", u"чубрица", u"черен пипер", u"магданоз"],26 self.test_recipe.products)27 def test_recipe_chef(self):28 self.assertEqual([u"name: Илияна Димова",29 u"hats: 4000.0",30 u"hearts: 4000.0",31 u"plates: 1000.0",32 u"Rating: 3000.0"],33 self.test_recipe.chef)34 def test_recipe_rating(self):35 pass36 def test_recipe_set_times_cooked(self):37 pass38if __name__ == '__main__':...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run avocado automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful