public IActionResult Modify(int id)
        {
            var recipe       = RecipesService.GetById(id);
            var recipeModify = ModelConverter.ConvertToRecipeModify(recipe);

            return(View(recipeModify));
        }
        public IActionResult Details(int id)
        {
            var recipe      = RecipesService.GetRecipeDetails(id);
            var sidebarData = RecipesService.GetSidebarData();

            var recipeDetails = ModelConverter.ConvertToRecipeDetailsModel(recipe);

            recipeDetails.SidebarData = sidebarData;

            if (User.Identity.IsAuthenticated)
            {
                var userId      = Convert.ToInt32(User.FindFirst("Id").Value);
                var currentLike = recipeDetails.RecipeLikes.FirstOrDefault(x => x.UserId == userId);

                if (currentLike != null)
                {
                    if (currentLike.Status)
                    {
                        recipeDetails.LikeStatus = RecipeLikeStatus.Liked;
                    }
                    else
                    {
                        recipeDetails.LikeStatus = RecipeLikeStatus.Disliked;
                    }
                }
            }

            return(View(recipeDetails));
        }
        public async Task AddRecipeWithEmptyCategoryShouldThrowException()
        {
            var db = this.GetDatabase();

            var recipesService = new RecipesService(db);

            db.Courses
            .Add(new Course
            {
                Name = "testCourse"
            });

            db.Users
            .Add(new User
            {
                UserName     = "******",
                Email        = "test",
                PasswordHash = "test",
                Id           = "testUserId"
            });

            db.SaveChanges();

            var model = new RecipeAddModel
            {
                Name        = "testRecipe",
                Course      = "testCourse",
                Ingredients = new List <AddIngredient>()
            };

            await Assert.ThrowsAsync <ArgumentNullException>(async() => await recipesService.AddRecipe(model, "test"));
        }
        public async Task AddRecipeShouldAddIngredientsToRecipe()
        {
            var db = this.GetDatabase();

            var recipesService = new RecipesService(db);

            db.Courses
            .Add(new Course
            {
                Name = "testCourse"
            });

            db.Categories
            .Add(new Category
            {
                Name = "testCategory"
            });

            db.Ingredients
            .Add(new Ingredient
            {
                Name = "testIngredient"
            });

            db.Users
            .Add(new User
            {
                UserName     = "******",
                Email        = "test",
                PasswordHash = "test",
                Id           = "testUserId"
            });

            db.SaveChanges();

            var model = new RecipeAddModel
            {
                Name        = "testRecipe",
                Course      = "testCourse",
                Category    = "testCategory",
                Ingredients = new List <AddIngredient>
                {
                    new AddIngredient
                    {
                        Name = "testIngredient"
                    }
                }
            };

            await recipesService.AddRecipe(model, "test");

            var recipe = db.Recipes
                         .FirstOrDefault(r => r.Name == "testRecipe");

            var ingr = recipe
                       .Ingredients
                       .FirstOrDefault(i => i.Ingredient.Name == "testIngredient");

            ingr.Should().NotBeNull();
        }
Ejemplo n.º 5
0
 public FrmRecipes(int id, bool valid)
 {
     InitializeComponent();
     _serv    = new RecipesService();
     _id      = id;
     _isValid = valid;
 }
Ejemplo n.º 6
0
        public async Task RecipeUpdate_ClearingAllIngredients_AreDeleted()
        {
            // each test creates new Connection / Options / DbSchema
            var connection = new SqliteConnection("DataSource=:memory:");

            connection.Open();

            try
            {
                var options = new DbContextOptionsBuilder <RecipesContext>()
                              .UseSqlite(connection)
                              .Options;

                SetupBasicContext(options);

                using (var context = new RecipesContext(options))
                {
                    var service        = new RecipesService(context, this._loggerMock.Object, this._mediaHelper.Object, this._mapper);
                    var recipeToUpdate = await service.GetOne(4);

                    // Remove all ingredients
                    recipeToUpdate.Ingredients = new List <IngredientBase>();
                    await service.UpdateOne(recipeToUpdate);

                    var dbrecipe = await service.GetOne(4);

                    //Assert.IsFalse(dbrecipe.Ingredients.Any());
                    Assert.AreEqual(0, dbrecipe.Ingredients.Count());
                }
            }
            finally
            {
                connection.Close();
            }
        }
        public void ReturnRecipesOfPassedDishTypeAsParameter()
        {
            //Arrange
            var            dataMock = new Mock <IHomeMadeFoodData>();
            var            ingredientsServiceMock = new Mock <IIngredientsService>();
            RecipesService recipesService         = new RecipesService(dataMock.Object, ingredientsServiceMock.Object);
            var            dishType = DishType.Pasta;
            Recipe         recipe   = new Recipe()
            {
                Id       = Guid.NewGuid(),
                Title    = "Recipe's title",
                DishType = DishType.Pasta
            };

            var expectedResultCollection = new List <Recipe>()
            {
                recipe
            };

            dataMock.Setup(x => x.Recipes.All).Returns(expectedResultCollection.AsQueryable());
            //Act
            var recipesOfDishTypePasta = recipesService.GetAllOfDishType(dishType).ToList();
            var actualResult           = recipesOfDishTypePasta[0].DishType;

            //Assert
            Assert.AreEqual(dishType, actualResult);
        }
Ejemplo n.º 8
0
        public void Throw_WhenThePassedRecipeIsNull()
        {
            //Arrange
            var                  dataMock = new Mock <IHomeMadeFoodData>();
            var                  ingredientsServiceMock = new Mock <IIngredientsService>();
            RecipesService       recipesService         = new RecipesService(dataMock.Object, ingredientsServiceMock.Object);
            Recipe               recipe          = null;
            IEnumerable <string> ingredientNames = new List <string>()
            {
                "Tomato"
            };
            IEnumerable <double> ingredientQuantities = new List <double>()
            {
                1.200
            };
            IEnumerable <decimal> ingredientPrices = new List <decimal>()
            {
                4.80m
            };
            IEnumerable <Guid> foodCategories = new List <Guid>()
            {
                Guid.NewGuid()
            };

            //Act & Assert
            Assert.Throws <ArgumentNullException>(
                () => recipesService.AddRecipe(
                    recipe,
                    ingredientNames,
                    ingredientQuantities,
                    ingredientPrices,
                    foodCategories));
        }
Ejemplo n.º 9
0
        public async Task GetAllRecipes_WithInitialData_ShouldReturnCorrectResult()
        {
            string errorMessagePrefix = "RecipesService Method GetAllRecipes() does not work properly.";

            var context = MyLifeStyleInmemoryFactory.InitializeContext();

            await SeedData(context);

            this.recipsService = new RecipesService(context);

            IEnumerable <AllRecipesViewModel> actualResultsEnumerable = await this.recipsService.GetAllRecipes <AllRecipesViewModel>();

            List <AllRecipesViewModel> actualResults = actualResultsEnumerable.ToList();

            List <AllRecipesViewModel> expectedResults = context.Recipes.OrderByDescending(x => x.Publication.CreatedOn).To <AllRecipesViewModel>().ToList();

            for (int i = 0; i < expectedResults.Count; i++)
            {
                var expectedEntry = expectedResults[i];
                var actualEntry   = actualResults[i];

                Assert.True(expectedEntry.PublicationTitle == actualEntry.PublicationTitle, errorMessagePrefix + " " + "Title is not returned properly");
                Assert.True(expectedEntry.DishType == actualEntry.DishType, errorMessagePrefix + " " + "DishType is not returned properly");
                Assert.True(expectedEntry.DietType == actualEntry.DietType, errorMessagePrefix + " " + "DietType is not returned properly");
                Assert.True(expectedEntry.Summary == actualEntry.Summary, errorMessagePrefix + " " + "Summary is not returned properly");
            }
        }
Ejemplo n.º 10
0
        public async Task RecipeUpdate_UpdatingExistingImageBytes_UpdatesProperly()
        {
            // each test creates new Connection / Options / DbSchema
            var connection = new SqliteConnection("DataSource=:memory:");

            connection.Open();

            try
            {
                var options = new DbContextOptionsBuilder <RecipesContext>()
                              .UseSqlite(connection)
                              .Options;

                var recipeId = 3;
                // Setup context with one recipe, and medias. Specifying separate media path since modifying image physically (to avoid conflict with other tests)
                SetupBasicContext(options, false, recipeId, "RecipeUpdate_UpdatingExistingImageBytes");

                using (var context = new RecipesContext(options))
                {
                    var service = new RecipesService(context, this._loggerMock.Object, this._mediaHelper, this._mapper);
                    // get recipe with ID 4
                    var recipeToUpdate = await service.GetOne(recipeId);

                    // Update media with ID: 1
                    var media = recipeToUpdate.Medias.Where(m => m.Id == 3).First();
                    // overriding ingredient to remove linked/tracked objects, and modifying some properties
                    // TODO: verify why object is being tracked? When we have asNoTracking set
                    recipeToUpdate.Medias.Remove(media);

                    // Load images json and select image 1 (foodMarket.jpg) that we know isn't in Media with ID 1 (foodColor.jpeg)
                    var TestImages = LoadRecipeMediaDtoFromJson(recipeId);
                    // Update properties AND mediabytes
                    recipeToUpdate.Medias.Add(new MediaDto {
                        Id = media.Id, Recipe_Id = media.Recipe_Id, Title = "FoodMarket", Tag = media.Tag, MediaDataUrl = TestImages.First().MediaDataUrl
                    });
                    await service.UpdateOne(recipeToUpdate);
                }
                using (var context = new RecipesContext(options))
                {
                    // VERIFY
                    var service       = new RecipesService(context, this._loggerMock.Object, this._mediaHelper, this._mapper);
                    var recipeUpdated = await service.GetOne(recipeId);

                    var image = recipeUpdated.Medias.Where(m => m.Id == 3).First();
                    Assert.AreEqual("FoodMarket", image.Title);

                    // Verify logger wrote INFO specifying that Media with Id 1 had its image overriden
                    this._loggerMock.Verify(l =>
                                            l.Log(LogLevel.Information, 0, It.Is <It.IsAnyType>((v, t) => v.ToString().Contains("New image provided")), It.IsAny <Exception>(), (Func <It.IsAnyType, Exception, string>)It.IsAny <object>())
                                            , Times.Once);
                    //l.Log(LogLevel.Information, 0, It.IsAny<It.IsAnyType>(), It.IsAny<Exception>(), (Func<It.IsAnyType, Exception, string>)It.IsAny<object>()), Times.Once);
                }
            }
            finally
            {
                connection.Close();
            }
        }
Ejemplo n.º 11
0
        public async Task RecipeUpdate_DeletingOneImage_DeletesProperly()
        {
            // each test creates new Connection / Options / DbSchema
            var connection = new SqliteConnection("DataSource=:memory:");

            connection.Open();

            try
            {
                var options = new DbContextOptionsBuilder <RecipesContext>()
                              .UseSqlite(connection)
                              .Options;

                var recipeId = 4; // choose recipe ID not used by other test to prevent conflicts on result checks
                // Setup context with one recipe, and medias. Specifying separate media path since modifying image physically (to avoid conflict with other tests)
                // TODO: Each test should have their own data to work with
                SetupBasicContext(options, false, recipeId, "RecipeUpdate_DeletingOneImage");

                using (var context = new RecipesContext(options))
                {
                    var service = new RecipesService(context, this._loggerMock.Object, this._mediaHelper, this._mapper);
                    // get recipe with ID defined at class level
                    // TODO: we're doing all of this wrong... You need a moqed environment for all test to work properly... The mediaLogicHelperTest already handles testing physical loading

                    var recipeToUpdate = await service.GetOne(recipeId);

                    // Remove media with ID: 3
                    var image = recipeToUpdate.Medias.Where(m => m.Id == 3).First();
                    recipeToUpdate.Medias.Remove(image);


                    await service.UpdateOne(recipeToUpdate);
                }
                using (var context = new RecipesContext(options))
                {
                    // VERIFY
                    var service       = new RecipesService(context, this._loggerMock.Object, this._mediaHelper, this._mapper);
                    var recipeUpdated = await service.GetOne(recipeId);

                    var image = recipeUpdated.Medias.Where(m => m.Id == 3).FirstOrDefault();
                    Assert.IsNull(image);
                    Assert.AreEqual(2, recipeUpdated.Medias.Count, "Medias count should be 2");
                    // Verify logger wrote INFO specifying that Image 3 was deleted
                    this._loggerMock.Verify(l =>
                                            l.Log(LogLevel.Information, 0, It.Is <It.IsAnyType>((v, t) => v.ToString().Contains("DELETED") && v.ToString().Contains("ID:3")), It.IsAny <Exception>(), (Func <It.IsAnyType, Exception, string>)It.IsAny <object>())
                                            , Times.Once);
                    // verify file no longer exist
                    // File path was defined in SetupBasicContext, it's not following regular path standards (from recipe service)
                    var imgToDeletePath = this._contextMedia.Where(m => m.Id == 3).First().MediaPath;
                    Assert.IsFalse(File.Exists(imgToDeletePath));
                }
            }
            finally
            {
                connection.Close();
            }
        }
        public IActionResult ModifyOverview()
        {
            var recipes = RecipesService.GetAll();
            var modifyOverviewModels = recipes
                                       .Select(x => ModelConverter.ConverToModifyOverviewModel(x))
                                       .ToList();

            return(View(modifyOverviewModels));
        }
Ejemplo n.º 13
0
        public async Task RecipeUpdate_AddingNewImagesToRecipeWithNoImages_WorksAndPathCreatedProperly()
        {
            // each test creates new Connection / Options / DbSchema
            var connection = new SqliteConnection("DataSource=:memory:");

            connection.Open();

            try
            {
                var options = new DbContextOptionsBuilder <RecipesContext>()
                              .UseSqlite(connection)
                              .Options;

                var recipeId = 1; // TODO: why is this text conflicting with DeleteMultipleImages ? Not same path nor Recipe ID and diff contexts
                // Setup context with one recipe, no medias
                SetupBasicContext(options, true, recipeId);

                using (var context = new RecipesContext(options))
                {
                    var service = new RecipesService(context, this._loggerMock.Object, this._mediaHelper, this._mapper);
                    // get recipe with ID setup for this test suite
                    var recipeToUpdate = await service.GetOne(recipeId);

                    // loading 3 mediaDtos from json
                    var mediaDtos = LoadRecipeMediaDtoFromJson(recipeId);
                    // insert into recipe that we want to update, to act like incoming media bytes
                    recipeToUpdate.Medias = mediaDtos;

                    await service.UpdateOne(recipeToUpdate);
                }
                using (var context = new RecipesContext(options))
                {
                    // VERIFY
                    var service = new RecipesService(context, this._loggerMock.Object, this._mediaHelper, this._mapper);

                    // Get recipe again from DB with new medias
                    var recipeToUpdate = await service.GetOne(recipeId);

                    Assert.AreEqual(3, recipeToUpdate.Medias.Count());
                    string userRecipePath; // not needed so we override
                    foreach (var i in recipeToUpdate.Medias)
                    {
                        var savedImgPath = MediaLogicHelper.GenerateSingleMediaPath(this._mediaHelper.UserMediasPath, recipeToUpdate.Id, i.Id, out userRecipePath);
                        // check file exists
                        Assert.IsTrue(File.Exists(savedImgPath));

                        long savedImageSize = new FileInfo(savedImgPath).Length;
                        // verify size is under 800kb
                        Assert.Less(savedImageSize, this.MAX_IMAGESIZE);
                    }
                }
            }
            finally
            {
                connection.Close();
            }
        }
Ejemplo n.º 14
0
 public void Setup()
 {
     recipeService = new RecipesService();
     recipeTest    = new Recipe("Flourless Chocolate Almond Butter Cookies",
                                new Uri("https://www.edamam.com/web-img/18a/18a14f2fc10f3805f6b67a23009b32f1.jpg"),
                                new Uri("http://www.thekitchenofdanielle.com/flourless-chocolate-almond-butter-cookies-vgf/"),
                                10,
                                2418.673499998057);
     recipes = new ObservableCollection <Recipe>();
 }
Ejemplo n.º 15
0
        public void ShouldThrow_WhenGuidIdParameterIsEmpty()
        {
            //Arrange
            var            dataMock = new Mock <IHomeMadeFoodData>();
            var            ingredientsServiceMock = new Mock <IIngredientsService>();
            RecipesService recipesService         = new RecipesService(dataMock.Object, ingredientsServiceMock.Object);

            //Act&Assert
            Assert.Throws <ArgumentException>(() => recipesService.GetRecipeById(Guid.Empty));
        }
        public async Task AddRecipeWithExistingIngredientShouldNotAddItToDatabase()
        {
            var db = this.GetDatabase();

            var recipesService = new RecipesService(db);

            db.Courses
            .Add(new Course
            {
                Name = "testCourse"
            });

            db.Categories
            .Add(new Category
            {
                Name = "testCategory"
            });

            db.Ingredients
            .Add(new Ingredient
            {
                Name = "testIngredient"
            });

            db.Users
            .Add(new User
            {
                UserName     = "******",
                Email        = "test",
                PasswordHash = "test",
                Id           = "testUserId"
            });

            db.SaveChanges();

            var model = new RecipeAddModel
            {
                Name        = "testRecipe",
                Course      = "testCourse",
                Category    = "testCategory",
                Ingredients = new List <AddIngredient>
                {
                    new AddIngredient
                    {
                        Name = "testIngredient"
                    }
                }
            };

            await recipesService.AddRecipe(model, "test");

            var ingr = db.Ingredients.Where(r => r.Name == "testIngredient");

            ingr.Count().Should().Be(1);
        }
        public void Throw_WhenThePassedRecipeIsNull()
        {
            //Arrange
            var            dataMock = new Mock <IHomeMadeFoodData>();
            var            ingredientsServiceMock = new Mock <IIngredientsService>();
            RecipesService recipesService         = new RecipesService(dataMock.Object, ingredientsServiceMock.Object);
            Recipe         recipe = null;

            //Act & Assert
            Assert.Throws <ArgumentNullException>(() => recipesService.EditRecipe(recipe));
        }
Ejemplo n.º 18
0
 public RecipesController(
     IMapper mapper,
     IOptions <AppSettings> appSettings,
     DataContext context,
     RecipesService recipeService)
 {
     _mapper       = mapper;
     _appSettings  = appSettings.Value;
     _context      = context;
     RecipeService = recipeService;
 }
        public IActionResult Modify(RecipeModifyModel modifyRecipe)
        {
            if (ModelState.IsValid)
            {
                var recipe = ModelConverter.ConvertFromRecipeModify(modifyRecipe);
                RecipesService.UpdateRecipe(recipe);
                return(RedirectToAction("ModifyOverview"));
            }

            return(View(modifyRecipe));
        }
Ejemplo n.º 20
0
        public async Task RecipeUpdate_AddingOneImageToRecipeWithImages_IsAddedProperlyAndPathCreated()
        {
            // each test creates new Connection / Options / DbSchema
            var connection = new SqliteConnection("DataSource=:memory:");

            connection.Open();

            try
            {
                var options = new DbContextOptionsBuilder <RecipesContext>()
                              .UseSqlite(connection)
                              .Options;

                var recipeId = 6;
                // Setup context with one recipe, and medias
                SetupBasicContext(options, false, recipeId);

                using (var context = new RecipesContext(options))
                {
                    var service = new RecipesService(context, this._loggerMock.Object, this._mediaHelper, this._mapper);
                    // get recipe with ID defined at class level
                    var recipeToUpdate = await service.GetOne(recipeId);

                    // loading mediaDtos from json (to have media with image bytes)
                    var mediaDtos  = LoadRecipeMediaDtoFromJson(recipeId);
                    var mediaToAdd = mediaDtos.First();
                    recipeToUpdate.Medias.Add(mediaToAdd);

                    await service.UpdateOne(recipeToUpdate);
                }
                using (var context = new RecipesContext(options))
                {
                    // VERIFY
                    var service       = new RecipesService(context, this._loggerMock.Object, this._mediaHelper, this._mapper);
                    var recipeUpdated = await service.GetOne(recipeId);

                    Assert.AreEqual(4, recipeUpdated.Medias.Count);

                    string userRecipePath;
                    // We can't access image path but we can recreate it from method used by service when saving it
                    var savedImgPath = MediaLogicHelper.GenerateSingleMediaPath(this._mediaHelper.UserMediasPath, recipeUpdated.Id, 4, out userRecipePath);
                    // check file exists
                    Assert.IsTrue(File.Exists(savedImgPath));
                    long savedImageSize = new FileInfo(savedImgPath).Length;
                    // verify size is under 800kb
                    Assert.Less(savedImageSize, this.MAX_IMAGESIZE);
                }
            }
            finally
            {
                connection.Close();
            }
        }
Ejemplo n.º 21
0
        private static void CrawlToDatabase()
        {
            var db             = new RecipesContext();
            var recipesService = new RecipesService(db);

            ICrawler crawler = new AllRecipesCrawler {
                Logger = Log
            };

            // crawler.ProcessRecipes(RecipeIdProvider.Range(6800, 6810), recipesService.Add);
            crawler.ProcessRecipes(RecipeIdProvider.Random(6800, 300000, 20), recipesService.Add);
        }
Ejemplo n.º 22
0
        public void Throw_WhenThePassedRecipeIsNull()
        {
            //Arrange
            var            dataMock = new Mock <IHomeMadeFoodData>();
            var            ingredientsServiceMock = new Mock <IIngredientsService>();
            RecipesService recipesService         = new RecipesService(dataMock.Object, ingredientsServiceMock.Object);

            dataMock.Setup(x => x.Recipes.Delete(It.IsAny <Recipe>()));

            //Act & Assert
            Assert.Throws <ArgumentNullException>(() => recipesService.DeleteRecipe(null));
        }
Ejemplo n.º 23
0
        public void InvokeDataCommitOnce_WhenThePassedArgumentsAreValid()
        {
            //Arrange
            var            dataMock = new Mock <IHomeMadeFoodData>();
            var            ingredientsServiceMock = new Mock <IIngredientsService>();
            RecipesService recipesService         = new RecipesService(dataMock.Object, ingredientsServiceMock.Object);
            List <string>  ingredientNames        = new List <string>()
            {
                "Tomato"
            };
            List <double> ingredientQuantities = new List <double>()
            {
                1.200
            };
            List <decimal> ingredientPrices = new List <decimal>()
            {
                4.80m
            };
            List <Guid> foodCategories = new List <Guid>()
            {
                Guid.NewGuid()
            };

            Guid   recipeId = Guid.NewGuid();
            Recipe recipe   = new Recipe()
            {
                Id          = recipeId,
                Title       = "Title Of A New Recipe",
                Describtion = "This is a decsribtion",
                Instruction = "Instructions of the recipe",
                DishType    = DishType.MainDish,
                Ingredients = new List <Ingredient>()
                {
                    new Ingredient()
                    {
                        Id                      = Guid.NewGuid(),
                        Name                    = ingredientNames[0],
                        FoodCategoryId          = foodCategories[0],
                        RecipeId                = recipeId,
                        QuantityInMeasuringUnit = ingredientQuantities[0],
                        PricePerMeasuringUnit   = ingredientPrices[0]
                    }
                }
            };

            dataMock.Setup(x => x.Recipes.Delete(It.IsAny <Recipe>()));

            //Act
            recipesService.DeleteRecipe(recipe);

            //Assert
            dataMock.Verify(x => x.SaveChanges(), Times.Once);
        }
Ejemplo n.º 24
0
        // Test adding recipe with instructions/ingredients/all props and 1 media
        public async Task RecipeAdd_WithAllProperties_Works()
        {
            // each test creates new Connection / Options / DbSchema
            var connection = new SqliteConnection("DataSource=:memory:");

            connection.Open();

            try
            {
                var options = new DbContextOptionsBuilder <RecipesContext>()
                              .UseSqlite(connection)
                              .Options;

                SetupBasicContext(options); // TODO: move into setup?
                int createdRecipeId = -1;
                using (var context = new RecipesContext(options))
                {
                    var service   = new RecipesService(context, this._loggerMock.Object, this._mediaHelper.Object, this._mapper);
                    var newRecipe = new RecipeDto
                    {
                        Description  = "Something",
                        LastModifier = "xx",
                        TitleShort   = "NewRecipe",
                        TitleLong    = "Gorgeous wedding cake",
                        OriginalLink = "https://www.foodnetwork.com/recipes/geoffrey-zakarian/classic-gin-gimlet-2341489",
                        Id           = 5 // should reset to 0 and be assigned by DB
                    };

                    var response = await service.AddOne(newRecipe);

                    Assert.IsTrue(response.Success);
                    var rgx   = new Regex(@"^.*Id:(?<id>[0-9])$");
                    var match = rgx.Match(response.Message);
                    createdRecipeId = Convert.ToInt32(match.Groups["id"].Value);
                }
                using (var context = new RecipesContext(options))
                {
                    var service = new RecipesService(context, this._loggerMock.Object, this._mediaHelper.Object, this._mapper);
                    var recipe  = await service.GetOne(createdRecipeId);

                    Assert.AreEqual("Something", recipe.Description);
                    Assert.AreEqual("xx", recipe.LastModifier);
                    Assert.AreEqual("NewRecipe", recipe.TitleShort);
                    Assert.AreEqual("Gorgeous wedding cake", recipe.TitleLong);
                    Assert.AreEqual("https://www.foodnetwork.com/recipes/geoffrey-zakarian/classic-gin-gimlet-2341489", recipe.OriginalLink);
                }
            }
            finally
            {
                connection.Close();
            }
        }
 public IActionResult Create(RecipeCreateModel createRecipe)
 {
     if (ModelState.IsValid)
     {
         var recipe = ModelConverter.ConvertFromCreateModel(createRecipe);
         RecipesService.CreateRecipe(recipe);
         return(RedirectToAction("ModifyOverview"));
     }
     else
     {
         return(View(createRecipe));
     }
 }
Ejemplo n.º 26
0
        public async Task RecipeUpdate_UpdatingRecipeAndIngredient_IsUpdated()
        {
            // each test creates new Connection / Options / DbSchema
            var connection = new SqliteConnection("DataSource=:memory:");

            connection.Open();

            try
            {
                var options = new DbContextOptionsBuilder <RecipesContext>()
                              .UseSqlite(connection)
                              .Options;

                SetupBasicContext(options);

                using (var context = new RecipesContext(options))
                {
                    var service        = new RecipesService(context, this._loggerMock.Object, this._mediaHelper.Object, this._mapper);
                    var recipeToUpdate = await service.GetOne(4);

                    // modifying recipe properties
                    recipeToUpdate.OriginalLink = "https://www.something.com";
                    recipeToUpdate.TitleShort   = "Banana pancakes";

                    // modifying ingredient with id 1
                    var ingredient = recipeToUpdate.Ingredients.FirstOrDefault(i => i.Id == 1);
                    // overriding ingredient to remove linked/tracked objects, and modifying some properties
                    recipeToUpdate.Ingredients.Remove(ingredient);
                    recipeToUpdate.Ingredients.Add(new IngredientBase {
                        Id = ingredient.Id, Name = "Strawberry", Quantity = 1, Unit_Id = 3, Recipe_Id = ingredient.Recipe_Id
                    });

                    await service.UpdateOne(recipeToUpdate);

                    // get recipe again
                    var newRecipe = await service.GetOne(4);

                    Assert.AreEqual("Banana pancakes", newRecipe.TitleShort);
                    Assert.AreEqual("https://www.something.com", newRecipe.OriginalLink);

                    ingredient = recipeToUpdate.Ingredients.FirstOrDefault(i => i.Id == 1);
                    Assert.AreEqual("Strawberry", ingredient.Name);
                    Assert.AreEqual(1, ingredient.Quantity);
                    Assert.AreEqual(3, ingredient.Unit_Id);
                }
            }
            finally
            {
                connection.Close();
            }
        }
Ejemplo n.º 27
0
        public async Task AddReviewShouldCreateANewReviewToRecipe()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString()).Options;

            AutoMapperConfig.RegisterMappings(Assembly.Load("CookingBook.Web.ViewModels"));
            var dbContext = new ApplicationDbContext(options);

            var recipeRepo            = new EfDeletableEntityRepository <Recipe>(dbContext);
            var nutritionRepo         = new EfDeletableEntityRepository <NutritionValue>(dbContext);
            var productRepo           = new EfDeletableEntityRepository <Product>(dbContext);
            var userRepo              = new EfDeletableEntityRepository <ApplicationUser>(dbContext);
            var service               = new RecipesService(recipeRepo, nutritionRepo, productRepo, userRepo);
            var category              = new Category();
            var nutrValue             = new NutritionValue();
            var user                  = new ApplicationUser();
            var prod                  = new Collection <RecipeByIdProductsViewModel>();
            var recipeCreateViewModel = new RecipeCreateViewModel
            {
                CategoryId     = 1,
                CookProcedure  = "cookProc",
                Photo          = "photo",
                Serving        = 1,
                Title          = "addNew",
                CookTime       = 2,
                NutritionValue = new RecipeCreateNutritionValuesViewModel
                {
                    Calories = 1, Carbohydrates = 1, Fats = 1, Fiber = 1, Protein = 1, Salt = 1, Sugar = 1,
                },
                Products = new List <RecipeCreateProductsViewModel>(),
            };
            string       userId       = "trayan";
            StringValues sv           = new StringValues("one");
            StringValues sk           = new StringValues("1");
            var          recipeResult = await service.CreateAsync(recipeCreateViewModel, userId, sv, sk);

            var model = new ReviewForRecipeViewModel
            {
                Comment   = "commentOne",
                RecipeId  = recipeResult,
                Score     = 5,
                UserId    = "trayan",
                CreatedOn = DateTime.Now,
            };
            var reviewResult = await service.AddReview(model);

            Assert.IsType <string>(reviewResult);
            Assert.NotEmpty(reviewResult);
            Assert.NotNull(reviewResult);
            Assert.True(dbContext.Reviews.Any());
        }
Ejemplo n.º 28
0
        public async Task EditByAdminShouldChangeRecipe()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString()).Options;

            AutoMapperConfig.RegisterMappings(Assembly.Load("CookingBook.Web.ViewModels"));
            var dbContext             = new ApplicationDbContext(options);
            var recipeRepo            = new EfDeletableEntityRepository <Recipe>(dbContext);
            var nutritionRepo         = new EfDeletableEntityRepository <NutritionValue>(dbContext);
            var productRepo           = new EfDeletableEntityRepository <Product>(dbContext);
            var userRepo              = new EfDeletableEntityRepository <ApplicationUser>(dbContext);
            var service               = new RecipesService(recipeRepo, nutritionRepo, productRepo, userRepo);
            var category              = new Category();
            var nutrValue             = new NutritionValue();
            var user                  = new ApplicationUser();
            var prod                  = new Collection <RecipeByIdProductsViewModel>();
            var recipeCreateViewModel = new RecipeCreateViewModel
            {
                CategoryId     = 1,
                CookProcedure  = "cookProc",
                Photo          = "photo",
                Serving        = 1,
                Title          = "addNew",
                CookTime       = 2,
                NutritionValue = new RecipeCreateNutritionValuesViewModel
                {
                    Calories = 1, Carbohydrates = 1, Fats = 1, Fiber = 1, Protein = 1, Salt = 1, Sugar = 1
                },
                Products = new List <RecipeCreateProductsViewModel>(),
            };
            string       userId       = "trayan";
            StringValues sv           = new StringValues("one");
            StringValues sk           = new StringValues("1");
            var          recipeResult = await service.CreateAsync(recipeCreateViewModel, userId, sv, sk);

            var model = new AdminRecipeViewModel
            {
                Id            = recipeResult,
                CategoryId    = 5,
                CookProcedure = "five",
                CookTime      = 5,
                Photo         = "fifthPhoto",
                Serving       = 5,
                Title         = "fifthEdit",
            };

            await service.EditByAdmin(model);

            Assert.Equal(5, dbContext.Recipes.FirstOrDefault(x => x.Id == recipeResult).CategoryId);
        }
Ejemplo n.º 29
0
        // TODO: bad practice. If doing integration test that use physical disk, setup different folder with pics for each test
        public async Task RecipeUpdate_DeletingMultipleImages_DeletesProperly()
        {
            // each test creates new Connection / Options / DbSchema
            var connection = new SqliteConnection("DataSource=:memory:");

            connection.Open();

            try
            {
                var options = new DbContextOptionsBuilder <RecipesContext>()
                              .UseSqlite(connection)
                              .Options;

                var recipeId = 5;
                // Setup context with one recipe, and medias. Specifying separate media path since modifying image physically (to avoid conflict with other tests)
                SetupBasicContext(options, false, recipeId, "RecipeUpdate_DeletingMultipleImages");
                using (var context = new RecipesContext(options))
                {
                    var service = new RecipesService(context, this._loggerMock.Object, this._mediaHelper, this._mapper);
                    // get recipe with ID defined at class level
                    var recipeToUpdate = await service.GetOne(recipeId);

                    // Remove all medias
                    recipeToUpdate.Medias.Clear();

                    await service.UpdateOne(recipeToUpdate);
                }
                using (var context = new RecipesContext(options))
                {
                    // VERIFY
                    var service       = new RecipesService(context, this._loggerMock.Object, this._mediaHelper, this._mapper);
                    var recipeUpdated = await service.GetOne(recipeId);

                    Assert.IsEmpty(recipeUpdated.Medias);
                    // Verify logger wrote INFO specifying that Images were deleted, for all 3 images
                    this._loggerMock.Verify(l =>
                                            l.Log(LogLevel.Information, 0, It.Is <It.IsAnyType>((v, t) => v.ToString().Contains("DELETED")), It.IsAny <Exception>(), (Func <It.IsAnyType, Exception, string>)It.IsAny <object>())
                                            , Times.Exactly(3));
                    // Verify files no longer exist
                    foreach (var media in this._contextMedia)
                    {
                        Assert.IsFalse(File.Exists(media.MediaPath));
                    }
                }
            }
            finally
            {
                connection.Close();
            }
        }
Ejemplo n.º 30
0
        public async Task GetAllRecipes_WithZeroData_ShouldReturnEmptyResult()
        {
            string errorMessagePrefix = "RecipesService Method GetAllRecipes() does not work properly.";

            var context = MyLifeStyleInmemoryFactory.InitializeContext();

            this.recipsService = new RecipesService(context);

            IEnumerable <AllRecipesViewModel> actualResultsEnumerable = await this.recipsService.GetAllRecipes <AllRecipesViewModel>();

            List <AllRecipesViewModel> actualResults = actualResultsEnumerable.ToList();

            Assert.True(actualResults.Count == 0, errorMessagePrefix);
        }