def test_count_all(self): with self.app_context(): recipe1 = RecipeModel("Title1", "Url1", "Ingredients1, test1") recipe2 = RecipeModel("Title2", "Url2", "Ingredients1, test2") recipe3 = RecipeModel("Title3", "Url3", "Ingredients1, test3") recipe1.save_to_db() recipe2.save_to_db() recipe3.save_to_db() no_of_recipes = RecipeModel.count_all()[0] self.assertEqual( no_of_recipes, 3, "RecipeModel.count_all() failed to count a proper number of recipes" )
def post(self): recipe = RecipeModel(**request.get_json()) if RecipeModel.findby_name(recipe.name): return { 'message': "Recipe with this name '{}' already exists".format(recipe.name) }, 400 recipe.saveto_db() return {'recipe': recipe_schema.dump(recipe)}, 201
def setUp(self) -> None: super(TestUsersFavouriteRecipes, self).setUp() with self.app_context(): self.user = UserModel("TestUsername", "TestPwd1!") self.user.save_to_db() recipe = RecipeModel("Title1", "Url1", "Ingredients1, test1") recipe.save_to_db() self.current_time = datetime.utcnow() self.f_recipe = FavouriteRecipesModel(self.user.user_id, recipe.recipe_id, self.current_time, "Meat", "The most delicious ever!")
def put(self, name): data = Recipe.parser.parse_args() recipe = RecipeModel.find_by_name(name) if recipe: recipe.instructions = data['instructions'] else: recipe = RecipeModel(name, data['instructions']) recipe.save_to_db() return recipe.json()
def setUp(self) -> None: super(TestDeleteAccount, self).setUp() with self.app_context(): with self.app() as client: self.current_time = datetime.utcnow() UserModel("TestUsername", "TestPwd1!").save_to_db() self.recipe_id1, _ = RecipeModel( "Title1", "Url1", "Ingredients1, test1").save_to_db() recipe_id2, _ = RecipeModel( "Title2", "Url2", "Ingredients2, test2").save_to_db() recipe_id3, _ = RecipeModel( "Title3", "Url3", "Ingredients3, test3").save_to_db() FavouriteRecipesModel( 1, self.recipe_id1, self.current_time, "Test category - salad", "Test comment - for Friday's dinner").save_to_db() FavouriteRecipesModel( 1, recipe_id2, self.current_time, "Test category - salad", "Test comment - for Friday's dinner").save_to_db() FavouriteRecipesModel( 1, recipe_id3, self.current_time, "Test category - salad", "Test comment - for Friday's dinner").save_to_db()
def test_show_all(self): with self.app_context(): self.f_recipe.save_to_db() recipe2 = RecipeModel("Title2", "Url2", "Ingredients2, test2") recipe2.save_to_db() f_recipe2 = FavouriteRecipesModel(self.user.user_id, recipe2.recipe_id, self.current_time) f_recipe2.save_to_db() all_recipes = FavouriteRecipesModel.show_all() self.assertEqual( len(all_recipes), 2, "FavouriteRecipesModel.show_all() does not query the db appropriately." )
def test_show_mine(self): with self.app_context(): self.f_recipe.save_to_db() recipe2 = RecipeModel("Title2", "Url2", "Ingredients2, test2") recipe2.save_to_db() f_recipe2 = FavouriteRecipesModel(self.user.user_id, recipe2.recipe_id, self.current_time) f_recipe2.save_to_db() my_recipes = [ x.json() for x in FavouriteRecipesModel.show_mine(self.user.user_id) ] expected = [{ "recipe_id": 1, "save_date": datetime.strftime(self.current_time, "%Y-%m-%d %H:%M"), "category": "Meat", "comment": "The most delicious ever!", "recipe_title": "Title1", "recipe_link": "Url1", "ingredients": "Ingredients1, test1" }, { "recipe_id": 2, "save_date": datetime.strftime(self.current_time, "%Y-%m-%d %H:%M"), "category": None, "comment": None, "recipe_title": "Title2", "recipe_link": "Url2", "ingredients": "Ingredients2, test2" }] self.assertListEqual( my_recipes, expected, "FavouriteRecipesModel.show_mine() query does not return proper values." )
def test_put_success(self): with self.app_context(): with self.app() as client: recipe_id, _ = RecipeModel("Title1", "Url1", "Ingredients1, test1").save_to_db() FavouriteRecipesModel(1, recipe_id, self.current_time, "Meat", "The most delicious ever!").save_to_db() response = client.put(f"{URL}/favourite_recipe/1", data=json.dumps({ "category": "Awful", "comment": "Don't ever try again!!" }), headers={ "Content-Type": "application/json", "Authorization": f"Bearer {self.access_token}" }) expected = { "Recipe updated!": { "recipe_id": 1, "save_date": datetime.strftime(self.current_time, "%Y-%m-%d %H:%M"), "category": "Awful", "comment": "Don't ever try again!!", "recipe_title": "Title1", "recipe_link": "Url1", "ingredients": "Ingredients1, test1" } } self.assertDictEqual( json.loads(response.data), expected, "Message returned while trying to successfully update a favourite recipe" " is incorrect.") self.assertEqual( response.status_code, 201, "Status code returned while trying to successfully update a favourite recipe" " is incorrect.")
def test_show_my_recipe_ids(self): with self.app_context(): self.f_recipe.save_to_db() recipe2 = RecipeModel("Title2", "Url2", "Ingredients2, test2") recipe2.save_to_db() f_recipe2 = FavouriteRecipesModel(self.user.user_id, recipe2.recipe_id, self.current_time) f_recipe2.save_to_db() my_recipes_ids = FavouriteRecipesModel.show_my_recipe_ids( self.user.user_id) self.assertListEqual( my_recipes_ids, [(1, ), (2, )], "FavouriteRecipesModel.show_my_recipe_ids() returns wrong values." )
def post(self): data = self.parser.parse_args() if RecipeModel.find_by_name(data['name']): return { 'message': "A recipe with name '{}' already exists.".format(data['name']) }, 400 recipe = RecipeModel(**data) try: recipe.save_to_db() except: return {"message": "An error occurred creating the recipe."}, 500 return recipe.json(), 201
def test_post_as_favourite_recipe_already_existing_in_db(self): with self.app_context(): with self.app() as client: RecipeModel("Test title", "Test url", "Test, ingredients").save_to_db() response = client.post(f"{URL}/favourite_recipe", data=json.dumps({ "title": "Test title", "href": "Test url", "ingredients": "Test, ingredients", "category": "Meat", "comment": "The most delicious ever!" }), headers={ "Content-Type": "application/json", "Authorization": f"Bearer {self.access_token}" }) expected = { 'message': "Successfully saved", "saved_recipe": { "recipe_id": 1, "save_date": datetime.strftime(self.current_time, "%Y-%m-%d %H:%M"), "category": "Meat", "comment": "The most delicious ever!", "recipe_title": "Test title", "recipe_link": "Test url", "ingredients": "Test, ingredients" } } self.assertDictEqual( json.loads(response.data), expected, "Message returned when successfully saving a favourite recipe " "(which was already existing in the recipes table) is incorrect.") self.assertEqual( response.status_code, 201, "Status code returned when successfully saving a favourite recipe " "(which was already existing in the recipes table) is incorrect.")
def post(self, name): if RecipeModel.find_by_name(name): return { 'message': "A recipe with name '{}' already exists.".format(name) }, 400 data = Recipe.parser.parse_args() recipe = RecipeModel(name, data['instructions'], data['category_id']) try: recipe.save_to_db() except: return {"message": "An error occurred inserting the recipe."}, 500 return recipe.json(), 201
def test_delete_success(self): with self.app_context(): with self.app() as client: recipe_id, _ = RecipeModel("Title1", "Url1", "Ingredients1, test1").save_to_db() FavouriteRecipesModel(1, recipe_id, self.current_time, "Meat", "The most delicious ever!").save_to_db() self.assertIsNotNone( RecipeModel.find_by_recipe_id(1), "While running TestFavouriteRecipeResource.test_delete_success()," "the recipe was not saved successfully to db.") self.assertIsNotNone( FavouriteRecipesModel.find_by_recipe_id(1), "While running TestFavouriteRecipeResource.test_delete_success()," "the favourite recipe was not saved successfully to db.") response = client.delete( f"{URL}/favourite_recipe/1", headers={"Authorization": f"Bearer {self.access_token}"}) expected = { "message": f"Recipe with the id 1 removed successfully from your favourites!" } self.assertDictEqual( json.loads(response.data), expected, "Incorrect message returned while trying to successfully delete " "a favourite recipe.") self.assertEqual( response.status_code, 200, "Incorrect status code returned while trying to successfully delete " "a favourite recipe.") self.assertIsNone( RecipeModel.find_by_recipe_id(1), "While running TestFavouriteRecipeResource.test_delete_success()," "the recipe was not deleted successfully from db.") self.assertListEqual( FavouriteRecipesModel.find_by_recipe_id(1), [], "While running TestFavouriteRecipeResource.test_delete_success()," "the favourite recipe was not deleted successfully from db." )
def post(self): data_parser = reqparse.RequestParser() data_parser.add_argument("title", required=True, type=str, help="Please add recipe's title") data_parser.add_argument("href", required=True, type=str, help="Please add recipe's url") data_parser.add_argument("ingredients", required=True, type=str, help="Please add recipe's ingredients") data_parser.add_argument("category", required=False, type=str, help="You can categorize this recipe") data_parser.add_argument("comment", required=False, type=str, help="You can add a comment to this recipe") data = data_parser.parse_args() user_id = get_raw_jwt()['identity'] current_time = datetime.utcnow() recipe_obj = RecipeModel.find_by_href(data['href']) if recipe_obj: recipe_id = recipe_obj.recipe_id else: recipe_id, recipe_obj = RecipeModel(data['title'], data['href'], data['ingredients']).save_to_db() if FavouriteRecipesModel.find_by_recipe_id_user_id(recipe_id, user_id): return {"message": "You have already this recipe saved in your favourites. " "If you want to update it, use the update endpoint."}, 400 favourite = FavouriteRecipesModel(user_id, recipe_id, current_time, data['category'], data['comment']) favourite.save_to_db() just_saved_recipe_display = favourite.json() return {'message': "Successfully saved", "saved_recipe": just_saved_recipe_display}, 201
def post(self, value): recipe_data = Recipe.recipe_parser.parse_args() portion_sum = 0 if RecipeModel.find_by_value(value): return {'message': "Recipe '{}' already exist".format(value)}, 400 recipe = RecipeModel(value, recipe_data['name']) for mixing in iter(recipe_data['ingredients_list']): portion_sum = portion_sum + mixing['portion'] if portion_sum > 200: return {"meessage": "portion over limit"} try: recipe_id = recipe.save_to_db() for mixing in iter(recipe_data['ingredients_list']): mixing_model = MixingModel(mixing['ingredient_id'], recipe_id, mixing['portion']) mixing_model.save_to_db() except: return {'message': 'An error occured during saving to DB'}, 500 return recipe.json(), 201
def test_get_success(self): with self.app_context(): with self.app() as client: recipe_id, _ = RecipeModel("Title1", "Url1", "Ingredients1, test1").save_to_db() FavouriteRecipesModel(1, recipe_id, self.current_time, "Meat", "The most delicious ever!").save_to_db() response = client.get( f"{URL}/favourite_recipe/1", headers={"Authorization": f"Bearer {self.access_token}"}) expected = { "Recipe": { "recipe_id": 1, "save_date": datetime.strftime(self.current_time, "%Y-%m-%d %H:%M"), "category": "Meat", "comment": "The most delicious ever!", "recipe_title": "Title1", "recipe_link": "Url1", "ingredients": "Ingredients1, test1" } } self.assertDictEqual( json.loads(response.data), expected, "Favourite recipe returned to a client is not what expected." ) self.assertEqual( response.status_code, 200, "Status code of an attempt to return a favourite recipe " "to a client is not what expected.")
def test_show_stats(self): with self.app_context(): self.f_recipe.save_to_db() recipe2 = RecipeModel("Title2", "Url2", "Ingredients2, test2") recipe2.save_to_db() f_recipe2 = FavouriteRecipesModel(self.user.user_id, recipe2.recipe_id, self.current_time) f_recipe2.save_to_db() user2 = UserModel("TestUsername2", "TestPwd1!") user2.save_to_db() f_rec_user2 = FavouriteRecipesModel(user2.user_id, recipe2.recipe_id, self.current_time) f_rec_user2.save_to_db() stats = [(rm.recipe_id, stat) for (rm, stat) in FavouriteRecipesModel.show_stats()] expected = [(1, 1), (2, 2)] self.assertListEqual( stats, expected, "FavouriteRecipesModel.show_stats() produces improper stats.")
def put(self, recipe_id): data = NewRecipe.parser.parse_args() recipe = RecipeModel.find_by_id(recipe_id) if recipe: if recipe.chef_id == data['chef_id']: recipe.name = data['name'] recipe.recipe_type = data['recipe_type'] recipe.description = data['description'] recipe.steps = data['steps'] recipe.servings = data['servings'] recipe.prep_min = data['prep_min'] recipe.cook_min = data['cook_min'] else: return { 'message': 'You can not change this recipe as you are not the chef.' }, 401 else: recipe = RecipeModel(**data) recipe.save_to_db() return recipe.json(), 201
def test_crud(self): with self.app_context(): recipe = RecipeModel("Title1", "Url1", "Ingredients1, test1") self.assertIsNone( RecipeModel.find_by_href("Url1"), f"Recipe object with a href {recipe.href} should not exist in the table." ) recipe.save_to_db() self.assertIsNotNone( RecipeModel.find_by_href("Url1"), f"Recipe object with a link {recipe.href} failed to save to db" ) self.assertIsNotNone( RecipeModel.find_by_recipe_id(1), f"Recipe did not find by its (manually created) id.") self.assertEqual( RecipeModel.find_by_href("Url1").recipe_title, "Title1", f"Recipe title does not equal the desired one {recipe.recipe_title}" ) recipe.delete_from_db(1) self.assertIsNone( RecipeModel.find_by_href("Url1"), "Recipe object found in db, while it should already be deleted." )
def test_get_users_stats_admin(self): with self.app_context(): with self.app() as client: UserModel("TestAdmin", "TestPwd1!", admin=1).save_to_db() UserModel("TestUsername", "TestPwd1!").save_to_db() UserModel("TestUsername2", "TestPwd1!").save_to_db() UserModel("TestUsername3", "TestPwd1!").save_to_db() UserModel("TestUsername4", "TestPwd1!").save_to_db() current_time = datetime.utcnow() recipe_id1, _ = RecipeModel( "Title1", "Url1", "Ingredients1, test1").save_to_db() recipe_id2, _ = RecipeModel( "Title2", "Url2", "Ingredients2, test2").save_to_db() recipe_id3, _ = RecipeModel( "Title3", "Url3", "Ingredients3, test3").save_to_db() FavouriteRecipesModel(2, recipe_id1, current_time, "Meat", "The most delicious ever!").save_to_db() FavouriteRecipesModel(2, recipe_id2, current_time, "Meat", "The most delicious ever!").save_to_db() FavouriteRecipesModel(2, recipe_id3, current_time, "Meat", "The most delicious ever!").save_to_db() FavouriteRecipesModel(3, recipe_id1, current_time).save_to_db() FavouriteRecipesModel(3, recipe_id2, current_time).save_to_db() FavouriteRecipesModel(3, recipe_id3, current_time).save_to_db() FavouriteRecipesModel(4, recipe_id1, current_time).save_to_db() FavouriteRecipesModel(4, recipe_id2, current_time).save_to_db() response = client.post( f"{URL}/login", data=json.dumps({ "username": "******", "password": "******" }), headers={"Content-Type": "application/json"}) access_token = json.loads(response.data)['access_token'] response = client.get(f"{URL}/users_stats", headers={ "Content-Type": "application/json", "Authorization": f"Bearer {access_token}" }) expected = { "number_of_users_in_db": 5, "users_details": [{ "admin": 1, "user_id": 1, "username": "******", "number_of_favourite_recipes_saved": 0, "ids_of_favourite_recipes": [] }, { "admin": 0, "user_id": 2, "username": "******", "number_of_favourite_recipes_saved": 3, "ids_of_favourite_recipes": [1, 2, 3] }, { "admin": 0, "user_id": 3, "username": "******", "number_of_favourite_recipes_saved": 3, "ids_of_favourite_recipes": [1, 2, 3] }, { "admin": 0, "user_id": 4, "username": "******", "number_of_favourite_recipes_saved": 2, "ids_of_favourite_recipes": [1, 2] }, { "admin": 0, "user_id": 5, "username": "******", "number_of_favourite_recipes_saved": 0, "ids_of_favourite_recipes": [] }] } self.maxDiff = None self.assertDictEqual( json.loads(response.data), expected, "The /users_stats GET returns wrong response.")
def setUp(self) -> None: self.new_recipe = RecipeModel("Title1", "Url1", "Ingredients1, test1") self.new_recipe.recipe_id = 1
def test_delete_when_admin(self): with self.app_context(): with self.app() as client: UserModel("TestAdmin", "TestPwd1!", admin=1).save_to_db() UserModel("TestUsernameToBeDeleted", "TestPwd1!").save_to_db() self.current_time = datetime.utcnow() self.recipe_id1, _ = RecipeModel( "Title1", "Url1", "Ingredients1, test1").save_to_db() recipe_id2, _ = RecipeModel( "Title2", "Url2", "Ingredients2, test2").save_to_db() recipe_id3, _ = RecipeModel( "Title3", "Url3", "Ingredients3, test3").save_to_db() FavouriteRecipesModel( 2, self.recipe_id1, self.current_time, "Test category - salad", "Test comment - for Friday's dinner").save_to_db() FavouriteRecipesModel( 2, recipe_id2, self.current_time, "Test category - salad", "Test comment - for Friday's dinner").save_to_db() FavouriteRecipesModel( 2, recipe_id3, self.current_time, "Test category - salad", "Test comment - for Friday's dinner").save_to_db() FavouriteRecipesModel(1, self.recipe_id1, self.current_time, "Category of the second user", "User2's comment").save_to_db() self.assertEqual( RecipeModel.count_all()[0], 3, "The number of recipes saved to db is not correct.") self.assertEqual( len(FavouriteRecipesModel.show_mine(2)), 3, "The number of favourite recipes saved to db is not correct." ) self.assertEqual( len(FavouriteRecipesModel.show_mine(1)), 1, "The number of favourite recipes saved to db is not correct." ) response = client.post( f"{URL}/login", data=json.dumps({ "username": "******", "password": "******" }), headers={"Content-Type": "application/json"}) access_token = json.loads(response.data)['access_token'] response = client.delete( f"{URL}/admin_delete_account/2", headers={"Authorization": f"Bearer {access_token}"}) expected = { "message": f"User's account (user_id: 2) deleted successfully!" } self.assertEqual(response.status_code, 200) self.assertDictEqual(json.loads(response.data), expected) self.assertEqual( RecipeModel.count_all()[0], 1, "The number of recipes saved to db is not correct.") self.assertEqual( len(FavouriteRecipesModel.show_mine(2)), 0, "The number of favourite recipes saved to db is not correct." ) self.assertEqual( len(FavouriteRecipesModel.show_mine(1)), 1, "The number of favourite recipes saved to db is not correct." )
def test_get(self): with self.app_context(): with self.app() as client: UserModel("TestUsername", "TestPwd1!").save_to_db() current_time = datetime.utcnow() recipe_id1, _ = RecipeModel("Title1", "Url1", "Ingredients1, test1").save_to_db() recipe_id2, _ = RecipeModel("Title2", "Url2", "Ingredients2, test2").save_to_db() recipe_id3, _ = RecipeModel("Title3", "Url3", "Ingredients3, test3").save_to_db() FavouriteRecipesModel(1, recipe_id1, current_time, "Meat", "The most delicious ever!").save_to_db() FavouriteRecipesModel(1, recipe_id2, current_time, "Meat", "The most delicious ever!").save_to_db() FavouriteRecipesModel(1, recipe_id3, current_time ).save_to_db() response = client.post(f"{URL}/login", data=json.dumps({ "username": "******", "password": "******" }), headers={ "Content-Type": "application/json" } ) access_token = json.loads(response.data)['access_token'] response = client.get(f"{URL}/favourite_recipes", headers={ "Content-Type": "application/json", "Authorization": f"Bearer {access_token}" }) expected = {"Your favourite recipes: ": [ {"recipe_id": 1, "save_date": datetime.strftime(current_time, "%Y-%m-%d %H:%M"), "category": "Meat", "comment": "The most delicious ever!", "recipe_title": "Title1", "recipe_link": "Url1", "ingredients": "Ingredients1, test1"}, {"recipe_id": 2, "save_date": datetime.strftime(current_time, "%Y-%m-%d %H:%M"), "category": "Meat", "comment": "The most delicious ever!", "recipe_title": "Title2", "recipe_link": "Url2", "ingredients": "Ingredients2, test2"}, {"recipe_id": 3, "save_date": datetime.strftime(current_time, "%Y-%m-%d %H:%M"), "category": None, "comment": None, "recipe_title": "Title3", "recipe_link": "Url3", "ingredients": "Ingredients3, test3"} ] } self.maxDiff = None self.assertDictEqual(json.loads(response.data), expected, "Wrong response returned when getting user favourites recipes " "- which should be a list of 3 favourites.") self.assertEqual(response.status_code, 200, "Wrong status code returned when getting user favourites recipes " "- which should be a list of 3 favourites.")
def test_get_admin(self): with self.app_context(): with self.app() as client: UserModel("TestUsername1", "Pwd1!").save_to_db() UserModel("TestUsername2", "Pwd1!").save_to_db() UserModel("TestUsername3", "Pwd1!").save_to_db() UserModel("TestUsername4", "Pwd1!").save_to_db() current_time = datetime.utcnow() recipe_id1, _ = RecipeModel("Title1", "Url1", "Ingredients1, test1").save_to_db() recipe_id2, _ = RecipeModel("Title2", "Url2", "Ingredients2, test2").save_to_db() recipe_id3, _ = RecipeModel("Title3", "Url3", "Ingredients3, test3").save_to_db() FavouriteRecipesModel(2, recipe_id1, current_time, "Meat", "The most delicious ever!").save_to_db() FavouriteRecipesModel(2, recipe_id2, current_time, "Meat", "The most delicious ever!").save_to_db() FavouriteRecipesModel(2, recipe_id3, current_time, "Meat", "The most delicious ever!").save_to_db() FavouriteRecipesModel(3, recipe_id1, current_time).save_to_db() FavouriteRecipesModel(3, recipe_id2, current_time).save_to_db() FavouriteRecipesModel(3, recipe_id3, current_time).save_to_db() FavouriteRecipesModel(4, recipe_id1, current_time).save_to_db() FavouriteRecipesModel(4, recipe_id2, current_time).save_to_db() UserModel("TestUsername", "TestPwd1!", admin=1).save_to_db() response = client.post(f"{URL}/login", data=json.dumps({ "username": "******", "password": "******" }), headers={ "Content-Type": "application/json" } ) access_token = json.loads(response.data)['access_token'] response = client.get(f"{URL}/recipes_stats", headers={ "Content-Type": "application/json", "Authorization": f"Bearer {access_token}" } ) expected = {"a number of recipes saved into the table 'recipes'": 3, 'details of the recipes and a number of people who saved each of them as their favourites': [ {'recipe': { 'recipe_id': 1, 'recipe_title': 'Title1', 'recipe_link': 'Url1', 'recipe_ingredients': 'Ingredients1, test1' }, 'number_of_users_who_have_it_saved_to_favourites': 3, 'ids_of_users_who_saved_it_to_favourites': [2, 3, 4] }, {'recipe': { 'recipe_id': 2, 'recipe_title': 'Title2', 'recipe_link': 'Url2', 'recipe_ingredients': 'Ingredients2, test2' }, 'number_of_users_who_have_it_saved_to_favourites': 3, 'ids_of_users_who_saved_it_to_favourites': [2, 3, 4] }, {'recipe': { 'recipe_id': 3, 'recipe_title': 'Title3', 'recipe_link': 'Url3', 'recipe_ingredients': 'Ingredients3, test3' }, 'number_of_users_who_have_it_saved_to_favourites': 2, 'ids_of_users_who_saved_it_to_favourites': [2, 3] } ] } self.assertDictEqual(json.loads(response.data), expected) self.assertEqual(response.status_code, 200)