public CocktailDbModel ToDbModel(CocktailDto item)
        {
            var cocktailType = Enum.TryParse(typeof(CocktailType), item.CocktailType, out var result);

            if (cocktailType)
            {
                if (item.Id == 0)
                {
                    return(new CocktailDbModel
                    {
                        Name = item.Name, Type = (CocktailType)result, Description = item.Description,
                        PhotoPath = item.PhotoPath
                    });
                }
                else
                {
                    return(new CocktailDbModel
                    {
                        Id = item.Id, Name = item.Name, Type = (CocktailType)result, Description = item.Description,
                        PhotoPath = item.PhotoPath
                    });
                }
            }
            else
            {
                throw new InvalidCastException(nameof(result));
            }
        }
        public async Task Create_Cocktail_Correctly()
        {
            //Arrange
            var options = TestUtilities.GetOptions(nameof(Create_Cocktail_Correctly));
            var mockCocktailDtoMapper         = new Mock <IDtoMapper <Cocktail, CocktailDto> >();
            var mockCocktailIngretientService = new Mock <ICocktailIngredientService>();
            var mockIngredientsService        = new Mock <IIngredientService>();
            var mockDateTimeProvider          = new Mock <IDateTimeProvider>();
            var ingredient = new Ingredient
            {
                Id   = 1,
                Name = "TestIngredient"
            };

            var ingredientDto = new IngredientDto
            {
                Id   = 1,
                Name = "TestIngredient"
            };

            string[] ingredients = new string[] { "TestIngredient" };

            var cocktailDto = new CocktailDto
            {
                Id          = 1,
                Name        = "TestCocktail",
                Ingredients = ingredients,
            };

            var cocktailIngredient = new CocktailIngredient
            {
                CocktailId   = cocktailDto.Id,
                IngredientId = ingredient.Id
            };

            mockCocktailDtoMapper.Setup(x => x.MapDto(It.IsAny <Cocktail>())).Returns(cocktailDto);
            mockIngredientsService.Setup(x => x.GetIngredientByNameAsync(It.IsAny <string>()))
            .Returns(Task.FromResult(ingredient));
            mockCocktailIngretientService.Setup(x => x.CreateCocktailIngredientAsync(It.IsAny <int>(), It.IsAny <int>())).Returns(Task.FromResult(cocktailIngredient));
            using (var arrangeContext = new CocktailMagicianContext(options))
            {
                await arrangeContext.Ingredients.AddAsync(ingredient);

                await arrangeContext.SaveChangesAsync();
            }

            //Act and Assert
            using (var assertContext = new CocktailMagicianContext(options))
            {
                var sut    = new CocktailService(assertContext, mockCocktailDtoMapper.Object, mockDateTimeProvider.Object, mockCocktailIngretientService.Object, mockIngredientsService.Object);
                var result = await sut.CreateCocktailAsync(cocktailDto);

                Assert.IsInstanceOfType(result, typeof(CocktailDto));
                Assert.AreEqual(1, result.Id);
                Assert.AreEqual("TestCocktail", result.Name);
                Assert.AreEqual("TestIngredient", result.Ingredients.First());
            }
        }
        public static CocktailDto MapToCocktailDto(this CocktailReviewViewModel cocktailVm)
        {
            var cocktailDto = new CocktailDto();

            cocktailDto.Id          = cocktailVm.Id;
            cocktailDto.Description = cocktailVm.Description;
            cocktailDto.Rating      = (double)Math.Round((decimal)(cocktailVm.Rating ?? 0), 2);
            return(cocktailDto);
        }
        public async Task ReturnCorrectTypeOfInstance()
        {
            //Arrange
            var options = TestUtilities.GetOptions(nameof(ReturnCorrectTypeOfInstance));

            var mapperMock                = new Mock <IDtoMapper <Cocktail, CocktailDto> >();
            var barMapperMock             = new Mock <IDtoMapper <Bar, BarDto> >();
            var cocktailDetailsMapperMock = new Mock <IDtoMapper <Cocktail, DetailsCocktailDto> >();
            var ingredientMapperMock      = new Mock <IDtoMapper <Ingredient, IngredientDto> >();

            var ingredientServiceMock         = new Mock <IIngredientService>();
            var cocktailIngredientServiceMock = new Mock <ICocktailIngredientService>();

            var testGuid = Guid.NewGuid();

            var entity = new Cocktail
            {
                Id        = testGuid,
                Name      = "TestOneName",
                ImagePath = "ImagePathOne",
                Info      = "TestInfo"
            };

            var dtoEntity = new CocktailDto
            {
                Id        = testGuid,
                Name      = "TestOneName",
                ImagePath = "ImagePathOne",
                Info      = "TestInfo"
            };

            mapperMock.Setup(x => x.MapFrom(It.IsAny <Cocktail>())).Returns(dtoEntity);

            using (var actContext = new CWContext(options))
            {
                //Act
                await actContext.Cocktails.AddAsync(entity);

                await actContext.SaveChangesAsync();
            }
            using (var assertContext = new CWContext(options))
            {
                //Assert
                var sut = new CocktailService(assertContext, mapperMock.Object, barMapperMock.Object, cocktailDetailsMapperMock.Object,
                                              ingredientServiceMock.Object, cocktailIngredientServiceMock.Object);
                var result = await sut.DeleteAsync(testGuid);

                Assert.IsInstanceOfType(result, typeof(CocktailDto));
                Assert.AreEqual(dtoEntity.Name, result.Name);
                Assert.AreEqual(dtoEntity.Info, result.Info);
                Assert.AreEqual(dtoEntity.ImagePath, result.ImagePath);
                Assert.AreEqual(dtoEntity.Id, result.Id);
            }
        }
        public async Task ReturnNull_When_NoIngredientsFound()
        {
            //Arrange
            var options = TestUtilities.GetOptions(nameof(ReturnNull_When_NoIngredientsFound));
            var mockCocktailDtoMapper         = new Mock <IDtoMapper <Cocktail, CocktailDto> >();
            var mockCocktailIngretientService = new Mock <ICocktailIngredientService>();
            var mockIngredientsService        = new Mock <IIngredientService>();
            var mockDateTimeProvider          = new Mock <IDateTimeProvider>();
            var ingredient = new Ingredient
            {
                Id   = 1,
                Name = "TestIngredient"
            };

            var ingredientDto = new IngredientDto
            {
                Id   = 1,
                Name = "TestIngredient"
            };

            string[] ingredients = new string[] { "TestIngredient" };

            var cocktailDto = new CocktailDto
            {
                Id          = 1,
                Name        = "TestCocktail",
                Ingredients = ingredients,
            };

            var cocktailIngredient = new CocktailIngredient
            {
                CocktailId   = cocktailDto.Id,
                IngredientId = ingredient.Id
            };

            mockCocktailDtoMapper.Setup(x => x.MapDto(It.IsAny <Cocktail>())).Returns(cocktailDto);
            mockCocktailIngretientService.Setup(x => x.CreateCocktailIngredientAsync(It.IsAny <int>(), It.IsAny <int>())).Returns(Task.FromResult(cocktailIngredient));
            using (var arrangeContext = new CocktailMagicianContext(options))
            {
                await arrangeContext.Ingredients.AddAsync(ingredient);

                await arrangeContext.SaveChangesAsync();
            }

            //Act and Assert
            using (var assertContext = new CocktailMagicianContext(options))
            {
                var sut    = new CocktailService(assertContext, mockCocktailDtoMapper.Object, mockDateTimeProvider.Object, mockCocktailIngretientService.Object, mockIngredientsService.Object);
                var result = await sut.CreateCocktailAsync(cocktailDto);

                Assert.IsNull(result);
            }
        }
Ejemplo n.º 6
0
        //Tested
        public async Task <string> Update(CocktailDto cocktailDto)
        {
            cocktailDto.ValidateIfNull("Model is invalid!");
            var cocktailToEdit = await GetCocktail(cocktailDto.Id);

            var cocktail = cocktailDto.MapToEditModel();

            var uniqueFileNamePath = _fileUploadService.SetUniqueImagePathForCocktail(cocktailDto.CocktailImage);

            cocktail.Image  = uniqueFileNamePath;
            cocktail.Rating = cocktailToEdit.Rating;
            var newCocktailComponents = new List <CocktailComponent>();

            foreach (var component in cocktail.CocktailComponents)
            {
                var ingridientId = await _ingredientServices
                                   .GetIngredientIdByNameAsync(component.Name);

                if (ingridientId == null)
                {
                    var newIngr = new Ingredient()
                    {
                        Name = component.Name
                    };
                    _context.Add(newIngr);
                    await _context.SaveChangesAsync();

                    ingridientId = newIngr.Id;
                }
                newCocktailComponents.Add(
                    new CocktailComponent
                {
                    CocktailId   = cocktailDto.Id,
                    IngredientId = ingridientId
                });
            }
            cocktail.CocktailComponents = newCocktailComponents;
            cocktail.Recepie            = await _recipeServices.ExtractRecipe(cocktail);

            _context.Entry(cocktailToEdit).CurrentValues.SetValues(cocktail);
            _context.RemoveRange(cocktailToEdit.CocktailComponents);
            _context.AddRange(cocktail.CocktailComponents);
            await _context.SaveChangesAsync();

            cocktail.Recepie = await _recipeServices.ExtractRecipe(cocktailToEdit);

            await _context.SaveChangesAsync();

            return(cocktailToEdit.Name);
        }
        public async Task ReturnCorrectDtoWhen_ParamsAreValid()
        {
            //Arrange
            var options = TestUtilities.GetOptions(nameof(ReturnCorrectDtoWhen_ParamsAreValid));

            var mapperMock                = new Mock <IDtoMapper <Cocktail, CocktailDto> >();
            var barMapperMock             = new Mock <IDtoMapper <Bar, BarDto> >();
            var cocktailDetailsMapperMock = new Mock <IDtoMapper <Cocktail, DetailsCocktailDto> >();
            var ingredientMapperMock      = new Mock <IDtoMapper <Ingredient, IngredientDto> >();

            var ingredientServiceMock         = new Mock <IIngredientService>();
            var cocktailIngredientServiceMock = new Mock <ICocktailIngredientService>();

            var testGuid = Guid.NewGuid();

            var cocktail = new Cocktail
            {
                Id        = testGuid,
                Name      = "TestOneName",
                ImagePath = "ImagePathOne"
            };

            var cocktailDto = new CocktailDto
            {
                Id        = testGuid,
                Name      = "TestOneName",
                ImagePath = "ImagePathOne"
            };

            mapperMock.Setup(x => x.MapFrom(It.IsAny <Cocktail>())).Returns(cocktailDto);

            using (var arrangeContext = new CWContext(options))
            {
                await arrangeContext.Cocktails.AddAsync(cocktail);

                await arrangeContext.SaveChangesAsync();
            }

            using (var assertContext = new CWContext(options))
            {
                //Act & Assert
                var sut = new CocktailService(assertContext, mapperMock.Object, barMapperMock.Object, cocktailDetailsMapperMock.Object,
                                              ingredientServiceMock.Object, cocktailIngredientServiceMock.Object);

                var result = await sut.GetCocktailAsync(testGuid);

                Assert.IsInstanceOfType(result, typeof(CocktailDto));
                Assert.AreEqual("TestOneName", result.Name);
            }
        }
Ejemplo n.º 8
0
        public async Task <CocktailDto> AddBarsAsync(CocktailDto cocktailDto, List <string> selectedBars)
        {
            var cocktail = await this.context.Cocktails
                           .Where(b => b.IsDeleted == false)
                           .FirstOrDefaultAsync(b => b.Id == cocktailDto.Id);

            if (cocktail == null)
            {
                throw new BusinessLogicException(ExceptionMessages.CocktailNull);
            }

            if (!selectedBars.Any())
            {
                throw new BusinessLogicException(ExceptionMessages.BarNull);
            }

            foreach (var item in selectedBars)
            {
                var bar = await this.context.Bars
                          .Where(c => c.IsDeleted == false)
                          .FirstOrDefaultAsync(c => c.Name == item) ?? throw new BusinessLogicException(ExceptionMessages.BarNull);

                var barCocktail = await this.context.BarCocktails
                                  .Where(c => c.BarId == bar.Id && c.CocktailId == cocktail.Id)
                                  .FirstOrDefaultAsync();

                if (barCocktail == null)
                {
                    barCocktail = new BarCocktail
                    {
                        Bar      = bar,
                        Cocktail = cocktail,
                    };
                    await this.context.BarCocktails.AddAsync(barCocktail);

                    bar.BarCocktails.Add(barCocktail);
                    cocktail.BarCocktails.Add(barCocktail);
                }
                else
                {
                    barCocktail.IsDeleted = false;
                    barCocktail.DeletedOn = DateTime.MinValue;
                }
            }

            await this.context.SaveChangesAsync();

            return(cocktailDto);
        }
        public static CocktailDto MapToCocktailDto(this Cocktail cocktail)
        {
            var cocktailDto = new CocktailDto();

            cocktailDto.Id          = cocktail.Id;
            cocktailDto.Name        = cocktail.Name;
            cocktailDto.Rating      = cocktail.Rating;
            cocktailDto.Image       = cocktail.Image;
            cocktailDto.Ingredients = cocktail.CocktailComponents
                                      .Select(c => c.MapToCocktailDto()).ToList();
            cocktailDto.CocktailReviews = cocktail.Reviews;               //mapToDto
            cocktailDto.DateDeleted     = cocktail.DateDeleted;
            cocktailDto.BarCocktails    = cocktail.BarCocktails.ToList(); // map to
            return(cocktailDto);
        }
        public static Cocktail MapToCocktailModel(this CocktailDto cocktailDto)
        {
            var cocktailModel = new Cocktail();

            //cocktailModel.CocktailComponents = cocktailDto.Ingredients.Select(c => new CocktailComponent() {Name = c.Ingredient , Quantity = c.Quantity, Unit = c.Unit, IngredientId = _ingredientService}).ToList();
            // Care !!! --> vse oshte nqma Id!
            cocktailModel.Name    = cocktailDto.Name;
            cocktailModel.Id      = cocktailDto.Id;
            cocktailModel.Rating  = cocktailDto.Rating;
            cocktailModel.Image   = cocktailDto.Image;
            cocktailModel.Recepie = cocktailDto.Recipe;
            //cocktailModel.CocktailComponents = new List<CocktailComponent>();
            //cocktailModel.CocktailIngredients = cocktailDto.CocktailIngredients;
            cocktailModel.Reviews = cocktailDto.CocktailReviews;
            return(cocktailModel);
        }
        public static CocktailReviewViewModel MapToCocktailReviewViewModel(this CocktailDto cocktailDto)
        {
            var cocktailVm = new CocktailReviewViewModel();

            cocktailVm.Id          = cocktailDto.Id;
            cocktailVm.CocktailID  = cocktailDto.CocktailId;
            cocktailVm.Name        = cocktailDto.Name;
            cocktailVm.Rating      = (double)Math.Round((decimal)(cocktailDto.Rating ?? 0), 2);
            cocktailVm.Description = cocktailDto.Description;
            cocktailVm.Image       = cocktailDto.Image;
            cocktailVm.ReviewDate  = cocktailDto.ReviewDate;
            //cocktailVm.Ingredients = cocktailDto.Ingredients;
            cocktailVm.LikeCount    = cocktailDto.LikeCount;
            cocktailVm.LikedByUsers = cocktailDto.LikedByUsers;
            return(cocktailVm);
        }
        public static CocktailDto MapToCocktailDTO(this CocktailViewModel cocktailVM)
        {
            var cocktailDto = new CocktailDto();

            cocktailDto.Id            = cocktailVM.Id;
            cocktailDto.Name          = cocktailVM.Name;
            cocktailDto.Image         = cocktailVM.Image;
            cocktailDto.CocktailImage = cocktailVM.CocktailImage;
            cocktailDto.Ingredients   = cocktailVM.Ingredients
                                        .Where(i => i.Ingredient != null)
                                        .Select(
                i => i.MapCockTailComponentVMToDTo()
                ).ToList();
            cocktailDto.Recipe = cocktailVM.Recipe;
            return(cocktailDto);
        }
        public static CocktailViewModel MapToCocktailViewModel(this CocktailDto cocktailDto)
        {
            var cocktailVm = new CocktailViewModel();

            cocktailVm.Id                 = cocktailDto.Id;
            cocktailVm.Name               = cocktailDto.Name;
            cocktailVm.Rating             = (double)Math.Round((decimal)(cocktailDto.Rating ?? 0), 2);
            cocktailVm.Image              = cocktailDto.Image;
            cocktailVm.DateDeleted        = cocktailDto.DateDeleted;
            cocktailVm.CocktailComponents = cocktailDto.Ingredients.Select(i => i.MapToCocktailComponentVM()).ToList();
            cocktailVm.BarCocktails       = cocktailDto.BarCocktails;
            cocktailVm.LikeCount          = cocktailDto.LikeCount;
            cocktailVm.LikeByUsers        = cocktailDto.LikedByUsers;
            //cocktailVm.Ingredients = cocktailDto.Ingredients.Select(i => i.MapIngredientToViewModel());
            return(cocktailVm);
        }
        public async Task ThrowWhen_CocktailIsNull()
        {
            //Arrange
            var options                   = TestUtilities.GetOptions(nameof(ThrowWhen_CocktailIsNull));
            var mapperMock                = new Mock <IDtoMapper <Cocktail, CocktailDto> >();
            var barMapperMock             = new Mock <IDtoMapper <Bar, BarDto> >();
            var cocktailDetailsMapperMock = new Mock <IDtoMapper <Cocktail, DetailsCocktailDto> >();
            var ingredientMapperMock      = new Mock <IDtoMapper <Ingredient, IngredientDto> >();

            var ingredientServiceMock         = new Mock <IIngredientService>();
            var cocktailIngredientServiceMock = new Mock <ICocktailIngredientService>();

            var testGuid  = Guid.NewGuid();
            var testGuid2 = Guid.NewGuid();

            var cocktail = new Cocktail
            {
                Id        = testGuid,
                Name      = "TestOneName",
                ImagePath = "ImagePathOne"
            };

            var cocktailDto = new CocktailDto
            {
                Id        = testGuid,
                Name      = "TestOneName",
                ImagePath = "ImagePathOne"
            };

            mapperMock.Setup(x => x.MapFrom(It.IsAny <Cocktail>())).Returns(cocktailDto);

            using (var arrangeContext = new CWContext(options))
            {
                await arrangeContext.Cocktails.AddAsync(cocktail);

                await arrangeContext.SaveChangesAsync();
            }

            using (var assertContext = new CWContext(options))
            {
                //Act & Assert
                var sut = new CocktailService(assertContext, mapperMock.Object, barMapperMock.Object, cocktailDetailsMapperMock.Object,
                                              ingredientServiceMock.Object, cocktailIngredientServiceMock.Object);

                await Assert.ThrowsExceptionAsync <BusinessLogicException>(() => sut.GetCocktailBarsAsync(testGuid2));
            }
        }
Ejemplo n.º 15
0
        public async Task Return_Correct_Cocktail_WhenParamsAreValid()
        {
            //Arrange
            var options = TestUtilities.GetOptions(nameof(Return_Correct_Cocktail_WhenParamsAreValid));
            var mockCocktailDtoMapper         = new Mock <IDtoMapper <Cocktail, CocktailDto> >();
            var mockCocktailIngretientService = new Mock <ICocktailIngredientService>();
            var mockIngredientsService        = new Mock <IIngredientService>();
            var mockDateTimeProvider          = new Mock <IDateTimeProvider>();

            var bar = new Bar {
                Id = 1
            };
            var cocktail = new Cocktail {
                Id = 1, Name = "TestCocktail"
            };
            var barCocktail = new BarCocktail {
                BarId = 1, CocktailId = 1
            };
            var cocktailDto = new CocktailDto
            {
                Id   = 1,
                Name = "TestCocktail",
            };

            mockCocktailDtoMapper.Setup(x => x.MapDto(It.IsAny <Cocktail>())).Returns(cocktailDto);
            using (var arrangeContext = new CocktailMagicianContext(options))
            {
                await arrangeContext.BarCocktails.AddAsync(barCocktail);

                await arrangeContext.Cocktails.AddAsync(cocktail);

                await arrangeContext.Bars.AddAsync(bar);

                await arrangeContext.SaveChangesAsync();
            }
            //Act and Assert
            using (var assertContext = new CocktailMagicianContext(options))
            {
                var sut    = new CocktailService(assertContext, mockCocktailDtoMapper.Object, mockDateTimeProvider.Object, mockCocktailIngretientService.Object, mockIngredientsService.Object);
                var result = await sut.GetBarCocktailsAsync(1);

                Assert.IsInstanceOfType(result, typeof(ICollection <CocktailDto>));
                Assert.AreEqual(1, result.First().Id);
                Assert.AreEqual("TestCocktail", result.First().Name);
            }
        }
        public async Task Update_Cocktail_Correctly()
        {
            //Arrange
            var options = TestUtilities.GetOptions(nameof(Update_Cocktail_Correctly));
            var mockCocktailDtoMapper         = new Mock <IDtoMapper <Cocktail, CocktailDto> >();
            var mockCocktailIngretientService = new Mock <ICocktailIngredientService>();
            var mockIngredientsService        = new Mock <IIngredientService>();
            var mockDateTimeProvider          = new Mock <IDateTimeProvider>();


            var cocktail = new Cocktail
            {
                Id               = 1,
                Name             = "TestCocktail",
                ShortDescription = "TestShortDescription",
                LongDescription  = "TestLongDescription",
            };
            var cocktailDto = new CocktailDto
            {
                Id               = 1,
                Name             = "NewTestCocktail",
                ShortDescription = "NewTestShortDescription",
                LongDescription  = "NewTestLongDescription",
            };

            mockCocktailDtoMapper.Setup(x => x.MapDto(It.IsAny <Cocktail>())).Returns(cocktailDto);
            using (var arrangeContext = new CocktailMagicianContext(options))
            {
                await arrangeContext.Cocktails.AddAsync(cocktail);

                await arrangeContext.SaveChangesAsync();
            }
            //Act and Assert
            using (var assertContext = new CocktailMagicianContext(options))
            {
                var sut    = new CocktailService(assertContext, mockCocktailDtoMapper.Object, mockDateTimeProvider.Object, mockCocktailIngretientService.Object, mockIngredientsService.Object);
                var result = await sut.UpdateCocktailAsync(cocktailDto);

                var editedCocktail = await assertContext.Cocktails.FirstAsync();

                Assert.IsInstanceOfType(result, typeof(CocktailDto));
                Assert.AreEqual("NewTestCocktail", editedCocktail.Name);
                Assert.AreEqual("NewTestShortDescription", editedCocktail.ShortDescription);
                Assert.AreEqual("NewTestLongDescription", editedCocktail.LongDescription);
            }
        }
        private async Task <bool> TryUpdateCocktailIngredients(CocktailDto cocktail)
        {
            try
            {
                if (cocktail.Ingredients != null)
                {
                    var ingredientsToAdd = cocktail.Ingredients.Where(e => e.Id == 0).ToList();
                    if (ingredientsToAdd.Count != 0)
                    {
                        await _context.AddRangeAsync(_ingredientMapper.ToDbModelList(ingredientsToAdd));
                    }

                    var ingredientIdsList = await _context.IngredientsSet.Where(e => e.CocktailId == cocktail.Id)
                                            .Select(e => e.Id).ToListAsync();

                    foreach (var ingredientId in ingredientIdsList)
                    {
                        if (cocktail.Ingredients.Any(e => e.Id == ingredientId))
                        {
                            var ingredientToUpdate = cocktail.Ingredients.First(e => e.Id == ingredientId);
                            _context.Entry(_ingredientMapper.ToDbModel(ingredientToUpdate)).State =
                                EntityState.Modified;
                        }
                        else
                        {
                            var ingredientToRemove = await _context.IngredientsSet.FindAsync(ingredientId);

                            _context.IngredientsSet.Remove(ingredientToRemove);
                        }
                    }
                }
                else
                {
                    var ingredientsToRemove = await _context.IngredientsSet.Where(e => e.CocktailId == cocktail.Id)
                                              .ToListAsync();

                    _context.IngredientsSet.RemoveRange(ingredientsToRemove);
                }

                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
Ejemplo n.º 18
0
        public async Task CreateCocktailReview(string userId, CocktailDto cocktailDto)
        {
            //validations

            var cocktailReview = new CocktailReview
            {
                UserId      = userId,
                CocktailId  = cocktailDto.Id,
                Description = cocktailDto.Description,
                Rating      = cocktailDto.Rating,
                ReviewDate  = DateTime.Now.Date
            };

            _context.CocktailReviews.Add(cocktailReview);
            await _context.SaveChangesAsync().ConfigureAwait(false);

            await this.SetAverrageRating(cocktailDto.Id);
        }
        public async Task <IActionResult> PutCocktail(int id, CocktailDto cocktail)
        {
            if (id != cocktail.Id)
            {
                return(BadRequest());
            }

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (!CocktailExists(id))
            {
                return(NotFound());
            }

            var updateCocktailSucceed = await TryUpdateCocktail(cocktail);

            var updateCocktailIngredientsSucceed = await TryUpdateCocktailIngredients(cocktail);

            if (!updateCocktailSucceed || !updateCocktailIngredientsSucceed)
            {
                return(BadRequest());
            }

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!CocktailExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
Ejemplo n.º 20
0
        public async Task <CocktailDto> CreateCocktailAsync(CocktailDto tempCocktailDto)
        {
            if (tempCocktailDto == null)
            {
                throw new ArgumentNullException("No entity found");
            }

            if (tempCocktailDto.Ingredients.Count == 0)
            {
                throw new ArgumentNullException("The ingredients are missing");
            }

            var cocktail = new Cocktail
            {
                Name              = tempCocktailDto.Name,
                ShortDescription  = tempCocktailDto.ShortDescription,
                LongDescription   = tempCocktailDto.LongDescription,
                ImageUrl          = tempCocktailDto.ImageUrl,
                ImageThumbnailUrl = tempCocktailDto.ImageThumbnailUrl,
            };

            await _context.Cocktails.AddAsync(cocktail);

            await _context.SaveChangesAsync();

            foreach (var item in tempCocktailDto.Ingredients)
            {
                var ingredient = await this._ingredientService.GetIngredientByNameAsync(item);

                if (ingredient == null)
                {
                    return(null);
                }

                var cocktailIngredient = await this._cocktailIngredientService.CreateCocktailIngredientAsync(cocktail.Id, ingredient.Id);

                cocktail.CocktailIngredients.Add(cocktailIngredient);
                await this._context.SaveChangesAsync();
            }

            var cocktailDto = this._cocktailDtoMapper.MapDto(cocktail);

            return(cocktailDto);
        }
Ejemplo n.º 21
0
        public IHttpActionResult PutCocktail(int id, CocktailDto cocktailDto)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            var cocktail = _context.Cocktails.SingleOrDefault(c => c.Id == id);

            if (cocktail == null)
            {
                return(NotFound());
            }

            Mapper.Map <CocktailDto, Cocktail>(cocktailDto, cocktail);
            _context.SaveChanges();

            return(Ok());
        }
        public void MapFrom_Should_ReturnCorrectInstanceOf_CocktailViewModel()
        {
            //Arrange
            var sut = new CocktailViewModelMapper();

            var cocktail = new CocktailDto
            {
                Id        = Guid.NewGuid(),
                Name      = "testName",
                Info      = "testInfo",
                ImagePath = "testPath",
            };

            //Act
            var result = sut.MapFrom(cocktail);

            //Assert
            Assert.IsInstanceOfType(result, typeof(CocktailViewModel));
        }
        public void MapFrom_Should_CorrectlyMapRatingFrom_CocktailDto_To_CocktailViewModel_WhenCollectionIsNotEmpty()
        {
            //Arrange
            var sut = new CocktailViewModelMapper();

            var cocktail = new CocktailDto
            {
                Id            = Guid.NewGuid(),
                Name          = "testName",
                Info          = "testInfo",
                ImagePath     = "testPath",
                AverageRating = 4.55,
            };

            //Act
            var result = sut.MapFrom(cocktail);

            //Assert
            Assert.AreEqual(result.AverageRating, 4.55);
        }
        public async Task CallUploadFileMethod_WithCorrectParameters()
        {
            var options      = TestUtils.GetOptions(nameof(CallUploadFileMethod_WithCorrectParameters));
            var cocktailName = "Mojito";
            var recipe       = "111";
            var image        = new Mock <IFormFile>().Object;
            var cocktailDTO  = new CocktailDto()
            {
                Name = cocktailName, Recipe = recipe, CocktailImage = image
            };


            using (var assertContext = new CMContext(options))
            {
                var sut = new CocktailServices(assertContext, _fileUploadService.Object,
                                               _ingredientServices.Object, _recipeServices.Object);
                await sut.AddCocktail(cocktailDTO);

                _fileUploadService.Verify(n => n.SetUniqueImagePathForCocktail(image), Times.Once());
            }
        }
        public async Task AddAllDependentEntities_WhenValidModelIsPassed()
        {
            var cocktailName = "Mojito";
            var image        = new Mock <IFormFile>().Object;
            var recipe       = "111";
            var options      = TestUtils.GetOptions(nameof(AddAllDependentEntities_WhenValidModelIsPassed));
            var cocktailDTO  = new CocktailDto()
            {
                Name          = cocktailName,
                CocktailImage = image,
                Recipe        = recipe,
                Ingredients   = new List <CocktailComponentDTO>
                {
                    new CocktailComponentDTO
                    {
                        IngredientId = "1",
                        Quantity     = 200,
                        Unit         = Unit.ml,
                        Ingredient   = "Vodka"
                    },
                    new CocktailComponentDTO
                    {
                        IngredientId = "2",
                        Quantity     = 300,
                        Unit         = Unit.ml,
                        Ingredient   = "Vodka2"
                    }
                }
            };

            using (var arrangeContext = new CMContext(options))
            {
                var sut = new CocktailServices(arrangeContext, _fileUploadService.Object,
                                               _ingredientServices.Object, _recipeServices.Object);
                await sut.AddCocktail(cocktailDTO);

                Assert.AreEqual(cocktailName, arrangeContext.Cocktails.First().Name);
                Assert.AreEqual(2, arrangeContext.Cocktails.First().CocktailComponents.Count);
            }
        }
        public void MapFrom_Should_CorrectlyMapFrom_Cocktail_To_CocktailViewModel()
        {
            //Arrange
            var sut = new CocktailViewModelMapper();

            var cocktail = new CocktailDto
            {
                Id        = Guid.NewGuid(),
                Name      = "testName",
                Info      = "testInfo",
                ImagePath = "testPath",
            };

            //Act
            var result = sut.MapFrom(cocktail);

            //Assert
            Assert.AreEqual(result.Id, cocktail.Id);
            Assert.AreEqual(result.Name, cocktail.Name);
            Assert.AreEqual(result.Info, cocktail.Info);
            Assert.AreEqual(result.ImagePath, cocktail.ImagePath);
        }
Ejemplo n.º 27
0
        public async Task <CocktailDto> CreateAsync(CocktailDto tempCocktail)
        {
            if (tempCocktail == null)
            {
                throw new BusinessLogicException(ExceptionMessages.CocktailNull);
            }

            if (!tempCocktail.CocktailIngredients.Any())
            {
                throw new BusinessLogicException(ExceptionMessages.CocktailIngredientsNull);
            }

            var cocktail = new Cocktail
            {
                Name      = tempCocktail.Name,
                Info      = tempCocktail.Info,
                ImagePath = tempCocktail.ImagePath,
            };

            await this.context.Cocktails.AddAsync(cocktail);

            await this.context.SaveChangesAsync();

            foreach (var item in tempCocktail.CocktailIngredients)
            {
                var ingredient = await this.ingredientService.GetIngredientAsync(item) ?? throw new ArgumentException(ExceptionMessages.IngredientNull);

                var cocktailIngredient = await this.cocktailIngredientService.CreateCocktailIngredientAsync(cocktail.Id, ingredient.Id);

                cocktail.CocktailIngredients.Add(cocktailIngredient);
                await this.context.SaveChangesAsync();
            }

            var cocktailDto = this.dtoMapper.MapFrom(cocktail);

            return(cocktailDto);
        }
        public async Task ThrowWhen_CocktailInredientsIsEmpty()
        {
            //Arrange
            var options = TestUtilities.GetOptions(nameof(ThrowWhen_CocktailInredientsIsEmpty));

            var mapperMock                = new Mock <IDtoMapper <Cocktail, CocktailDto> >();
            var barMapperMock             = new Mock <IDtoMapper <Bar, BarDto> >();
            var cocktailDetailsMapperMock = new Mock <IDtoMapper <Cocktail, DetailsCocktailDto> >();
            var ingredientMapperMock      = new Mock <IDtoMapper <Ingredient, IngredientDto> >();

            var ingredientServiceMock         = new Mock <IIngredientService>();
            var cocktailIngredientServiceMock = new Mock <ICocktailIngredientService>();

            string[] ingredients = new string[] { };

            var entityDto = new CocktailDto
            {
                Id                  = Guid.NewGuid(),
                Name                = "TestName",
                Info                = "TestInfo",
                ImagePath           = "TestImagePath",
                CocktailIngredients = ingredients
            };

            mapperMock.Setup(x => x.MapFrom(It.IsAny <Cocktail>())).Returns(It.IsAny <CocktailDto>);


            using (var assertContext = new CWContext(options))
            {
                //Act & Assert
                var sut = new CocktailService(assertContext, mapperMock.Object, barMapperMock.Object, cocktailDetailsMapperMock.Object,
                                              ingredientServiceMock.Object, cocktailIngredientServiceMock.Object);

                await Assert.ThrowsExceptionAsync <BusinessLogicException>(() => sut.CreateAsync(entityDto));
            }
        }
        public async Task <ActionResult <CocktailDto> > PostCocktail(CocktailDto cocktail)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (!string.IsNullOrEmpty(cocktail.PhotoPath))
            {
                cocktail.PhotoPath = await _storageService.SaveFile(
                    Convert.FromBase64String(PhotoPathHelper.GetBase64String(cocktail.PhotoPath)), "jpg", "cocktails");
            }

            var cocktailDbModel = _cocktailMapper.ToDbModel(cocktail);
            await _context.CocktailsSet.AddAsync(cocktailDbModel);

            await _context.SaveChangesAsync();

            var createdCocktail = _context.CocktailsSet.OrderByDescending(e => e.Id).First();

            if (cocktail.Ingredients != null)
            {
                foreach (var ingredientDto in cocktail.Ingredients)
                {
                    ingredientDto.CocktailId = createdCocktail.Id;
                }

                var ingredientDbModels = _ingredientMapper.ToDbModelList(cocktail.Ingredients);
                await _context.IngredientsSet.AddRangeAsync(ingredientDbModels);

                await _context.SaveChangesAsync();
            }

            return(CreatedAtAction(nameof(GetCocktail), new { id = createdCocktail.Id },
                                   _cocktailMapper.ToDto(createdCocktail)));
        }
Ejemplo n.º 30
0
 public async Task <bool> CheckIfUserCanReview(string userId, CocktailDto cocktailDto)
 => cocktailDto.CocktailReviews.Any(c => c.UserId == userId && c.CocktailId == cocktailDto.Id);