Пример #1
0
        public async Task DeleteCommentTest()
        {
            var options           = new DbContextOptionsBuilder <ApplicationDbContext>().UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString());
            var commentRepository = new EfDeletableEntityRepository <Comment>(new ApplicationDbContext(options.Options));
            var commentService    = new CommentService(commentRepository);
            var userId            = "userId";
            var carId             = "carId";
            var comment           = new CarCommentsInputModel
            {
                UserId  = userId,
                CarId   = carId,
                Content = "test comment",
                Title   = "test",
            };
            var secComment = new CarCommentsInputModel
            {
                UserId  = userId,
                CarId   = carId,
                Content = "secTest comment",
                Title   = "secTest",
            };
            await commentService.CreateAsync(comment);

            await commentService.CreateAsync(secComment);

            Assert.Equal(2, await commentRepository.All().CountAsync());
            var commentShouldBeDeleted = await commentRepository.All().FirstAsync();

            var commentId = commentShouldBeDeleted.Id;
            await commentService.DeleteCommentAsync(commentId);

            Assert.Equal(1, await commentRepository.All().CountAsync());
        }
        public void CreateComment_validationfail()
        {
            CommentDto commentDto = new CommentDto();

            Func <Task> action = async() => await _service.CreateAsync(commentDto);

            action.Should().Throw <InvalidQueryParamsException>();
        }
Пример #3
0
        public async Task TestCreateWithNonExistingPost()
        {
            var entity = new Comment()
            {
                Body = _entitySequence.ToString(),
            };

            var result = await _service.CreateAsync(entity);

            Assert.False(result.IsSuccess);
            Assert.Contains("The post was not found.", result.Errors);
        }
Пример #4
0
        public async Task CreateAsync_ShouldReturnModifiedCommentDTOAsync()
        {
            //Arrange
            var options = InMemory.GetOptions("CreateAsync_ShouldReturnModifiedCommentDTOAsync");

            using (var context = new BOContext(options))
            {
            }

            using (var context = new BOContext(options))
            {
                var commentDTO = new CommentDTO
                {
                    Description = "Gotham",
                    User        = new UserDTO()
                    {
                        Name = "Batman"
                    },
                    Review = new ReviewDTO()
                    {
                        Description = "Description"
                    }
                };
                //Act
                var sut    = new CommentService(context);
                var result = await sut.CreateAsync(commentDTO);

                var dbresult = await context.Comments.FindAsync(1);

                //Assert
                Assert.AreEqual(result.ID, dbresult.ID);
                Assert.AreEqual(result.Description, dbresult.Description);
            }
        }
Пример #5
0
        public async Task CreatingComments()
        {
            // Arrange

            var db = this.GetDatabase();

            var product = new Product {
                Id = 1, Name = "product"
            };
            var author = new User {
                Id = "first", Name = "author"
            };

            db.AddRange(product, author);
            await db.SaveChangesAsync();

            var productService = new ProductService(db);
            var commentService = new CommentService(db, productService);

            // Act

            var createdProduct = commentService.CreateAsync("test", product.Id, author.Id);
            var result         = db.Comments.Select(c => c.Content).FirstOrDefault();

            // Assert

            result
            .Should()
            .Equals("test");
        }
Пример #6
0
        public async Task Post_comments()
        {
            var svc = new CommentService(DbContext, Mapper, null);
            var dto = new PostCommentDto
            {
                Content   = Guid.NewGuid().ToString(),
                Name      = Guid.NewGuid().ToString(),
                ArticleId = 1,
                Code      = "1234",
                Email     = "*****@*****.**",
                IPv4      = "localhost:123"
            };
            await svc.CreateAsync(dto);

            var result = await DbContext.Comments.FirstOrDefaultAsync();

            Assert.AreEqual(dto.Content, result.Content);
            Assert.AreEqual(dto.ArticleId, result.ArticleId);
            Assert.AreEqual(dto.Name, result.Name);
            Assert.AreEqual(DateTimeOffset.Now.ToString("yyyy-MM-dd"), result.CreateTime.ToString("yyyy-MM-dd"));
            Assert.AreEqual(dto.Email, result.Email);
            Assert.AreEqual(1, result.Id);
            Assert.AreEqual("localhost:123", result.IPv4);
            Assert.AreEqual(BaseStatus.Enabled, result.Status);
        }
Пример #7
0
        public async Task <IActionResult> Create(CommentUpdateModel createComment)
        {
            var comment = createComment.Adapt <Comment>();
            await _commentService.CreateAsync(comment);

            var bookRated = await _bookService.GetAsync(comment.BookId);

            bookRated.Comments.Add(comment);

            await _bookService.UpdateAsync(bookRated.Id, bookRated);

            //Update status comment in order
            var order = await _orderService.GetOrderAsync(comment.OrderId);

            foreach (var item in order.Items)
            {
                if (item.BookId == comment.BookId)
                {
                    item.StatusRate = true;
                }
            }
            await _orderService.UpdateStatusRateAsync(order);

            return(Ok());
        }
Пример #8
0
        public async Task <ActionResult> Create(CreateStudentViewModel student)
        {
            if (ModelState.IsValid)
            {
                Student newStudent = new Student()
                {
                    Name             = student.Name,
                    LastName         = student.LastName,
                    FatherName       = student.FatherName,
                    PhoneNumber      = student.PhoneNumber,
                    DateOfBirthday   = student.DateOfBirthday,
                    TrialDate        = student.TrialDate,
                    ParentName       = student.ParentName,
                    ParentLastName   = student.ParentLastName,
                    ParentFatherName = student.ParentFatherName
                };
                var studentId = await _studentService.CreateAsyncReturnId(student);

                if (student.Comment != null)
                {
                    Comment comment = new Comment
                    {
                        StudentId = studentId,
                        Text      = student.Comment,
                        Create    = DateTime.Now
                    };
                    await _commentService.CreateAsync(comment);
                }

                return(RedirectToAction(nameof(SelectLeadStudents)));
            }

            return(View(student));
        }
Пример #9
0
        public async Task CreateAsync_ShouldReturnCommentDTOAsync()
        {
            //Arrange
            var options = InMemory.GetOptions("CreateAsync_ShouldReturnCommentDTOAsync");

            using (var context = new BOContext(options))
            {
            }

            using (var context = new BOContext(options))
            {
                var commentDTO = new CommentDTO
                {
                    Description = "Gotham",
                    User        = new UserDTO()
                    {
                        Name = "Batman"
                    },
                    Review = new ReviewDTO()
                    {
                        Description = "Description"
                    }
                };
                //Act
                var sut    = new CommentService(context);
                var result = await sut.CreateAsync(commentDTO);

                //Assert
                Assert.IsInstanceOfType(result, typeof(CommentDTO));
            }
        }
Пример #10
0
        public async Task <IActionResult> NewComment(PostSlugViewModelWrapper model,
                                                     [FromServices] ISessionBasedCaptcha captcha)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    Response.StatusCode = (int)HttpStatusCode.BadRequest;
                    return(Json(new CommentResponse(false, CommentResponseCode.InvalidModel)));
                }

                if (!_blogConfig.ContentSettings.EnableComments)
                {
                    Response.StatusCode = (int)HttpStatusCode.Forbidden;
                    return(Json(new CommentResponse(false, CommentResponseCode.CommentDisabled)));
                }

                // Validate BasicCaptcha Code
                if (!captcha.ValidateCaptchaCode(model.NewCommentViewModel.CaptchaCode, HttpContext.Session))
                {
                    Logger.LogWarning("Wrong Captcha Code");
                    ModelState.AddModelError(nameof(model.NewCommentViewModel.CaptchaCode), "Wrong Captcha Code");

                    Response.StatusCode = (int)HttpStatusCode.BadRequest;
                    return(Json(new CommentResponse(false, CommentResponseCode.WrongCaptcha)));
                }

                var commentPostModel = model.NewCommentViewModel;
                var response         = await _commentService.CreateAsync(new NewCommentRequest(commentPostModel.PostId)
                {
                    Username  = commentPostModel.Username,
                    Content   = commentPostModel.Content,
                    Email     = commentPostModel.Email,
                    IpAddress = HttpContext.Connection.RemoteIpAddress.ToString()
                });

                if (_blogConfig.NotificationSettings.SendEmailOnNewComment && null != _notificationClient)
                {
                    _ = Task.Run(async() =>
                    {
                        await _notificationClient.NotifyNewCommentAsync(response, s => Utils.MarkdownToContent(s, Utils.MarkdownConvertType.Html));
                    });
                }
                var cResponse = new CommentResponse(true,
                                                    _blogConfig.ContentSettings.RequireCommentReview ?
                                                    CommentResponseCode.Success :
                                                    CommentResponseCode.SuccessNonReview);

                return(Json(cResponse));
            }
            catch (Exception e)
            {
                Logger.LogError(e, "Error NewComment");
                Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                return(Json(new CommentResponse(false, CommentResponseCode.UnknownError)));
            }
        }
Пример #11
0
        public async Task GetComments()
        {
            var options           = new DbContextOptionsBuilder <ApplicationDbContext>().UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString());
            var carRepository     = new EfDeletableEntityRepository <Car>(new ApplicationDbContext(options.Options));
            var commentRepository = new EfDeletableEntityRepository <Comment>(new ApplicationDbContext(options.Options));
            var commentService    = new CommentService(commentRepository);
            var userId            = "userId";
            var car = new Car
            {
                ImgsPaths = "asd",
            };
            await carRepository.AddAsync(car);

            await carRepository.SaveChangesAsync();

            var addedCar = await carRepository.All().FirstAsync();

            var carId   = addedCar.Id;
            var comment = new CarCommentsInputModel
            {
                UserId  = userId,
                CarId   = carId,
                Content = "test comment",
                Title   = "test",
            };
            var secComment = new CarCommentsInputModel
            {
                UserId  = userId,
                CarId   = carId,
                Content = "Second comment",
                Title   = "SecCom",
            };
            await commentService.CreateAsync(comment);

            await commentService.CreateAsync(secComment);

            AutoMapperConfig.RegisterMappings(typeof(CarCommentViewModel).Assembly);
            var addedComment = await commentService.GetComments <CarCommentViewModel>(carId);

            Assert.Equal(2, addedComment.Count);
        }
Пример #12
0
 public async Task CreateComment(Guid userId, Guid articleId, string content)
 {
     using (ICommentService commentService = new CommentService())
     {
         await commentService.CreateAsync(new Comment()
         {
             UserId    = userId,
             ArticleId = articleId,
             Content   = content
         });
     }
 }
Пример #13
0
        public async Task CreateAsyncShouldReturnCorrectly()
        {
            ApplicationDbContext db = GetDb();

            var repositiry = new EfDeletableEntityRepository <Comment>(db);

            var service = new CommentService(repositiry);

            await service.CreateAsync(1, "userId", "Test");

            Assert.Single(db.Comments.Where(x => x.Content == "Test"));
        }
Пример #14
0
        public async Task <IActionResult> Create([FromBody] CommentViewModel model, [FromRoute] int coachId, CancellationToken ct)
        {
            var comment = model.Adapt <Comment>();
            var coach   = await _coachService.GetAsync(coachId, ct);

            if (coach == null)
            {
                return(BadRequest());
            }

            var user = await GetCurrentUserAsync();

            if (user.Coach?.Id == coachId)
            {
                return(BadRequest());
            }

            comment.Coach = coach;
            comment.User  = user;

            await _commentService.CreateAsync(comment, ct);

            return(Ok(comment.Id));
        }
Пример #15
0
        public async Task CreateAsync_ShouldCreateNewComment()
        {
            // Arrange
            FitStoreDbContext database = this.Database;

            ICommentService commentService = new CommentService(database);

            // Act
            await commentService.CreateAsync(content, userId, supplementId);

            // Assert
            Comment comment = database.Comments.Find(commentId);

            comment.Content.Should().Be(content);
            comment.AuthorId.Should().Be(userId);
            comment.SupplementId.Should().Be(supplementId);
        }
Пример #16
0
        public async Task <IActionResult> Post(PostCommentDto dto)
        {
            if (ModelState.IsValid)
            {
                if (_captcha.ValidateCaptchaCode(dto.Code, HttpContext.Session))
                {
                    dto.IPv4 = Request.Host.ToString();
                    await _commentService.CreateAsync(dto);

                    return(RedirectToAction("Detail", "Article", new { id = dto.ArticleId }));
                }
                else
                {
                    TempData["ErrorCaptcha"] = true;
                }
            }
            TempData.Put("ErrorModel", dto);
            return(RedirectToAction("Detail", "Article", new { id = dto.ArticleId }));
        }
Пример #17
0
        public async Task CreateAsync_ShouldReturnNullIfCommentInputNullAsync()
        {
            //Arrange
            var options = InMemory.GetOptions("CreateAsync_ShouldReturnNullIfCommentInputNullAsync");

            using (var context = new BOContext(options))
            {
            }

            using (var context = new BOContext(options))
            {
                //Act
                var sut    = new CommentService(context);
                var result = await sut.CreateAsync(null);

                //Assert
                Assert.AreEqual(result, null);
            }
        }
Пример #18
0
        public async Task CreateCommentTest()
        {
            var options           = new DbContextOptionsBuilder <ApplicationDbContext>().UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString());
            var commentRepository = new EfDeletableEntityRepository <Comment>(new ApplicationDbContext(options.Options));
            var commentService    = new CommentService(commentRepository);
            var userId            = "userId";
            var carId             = "carId";
            var comment           = new CarCommentsInputModel
            {
                UserId  = userId,
                CarId   = carId,
                Content = "test comment",
                Title   = "test",
            };
            await commentService.CreateAsync(comment);

            var createdComment = await commentRepository.All().FirstOrDefaultAsync(x => x.UserId == userId && x.CarId == carId && x.Title == "test");

            Assert.NotNull(createdComment);
        }
Пример #19
0
        public async Task <IActionResult> NewComment(Guid postId, NewCommentModel model, [FromServices] ISessionBasedCaptcha captcha)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            if (!_blogConfig.ContentSettings.EnableComments)
            {
                return(Forbid());
            }

            if (!captcha.ValidateCaptchaCode(model.CaptchaCode, HttpContext.Session))
            {
                ModelState.AddModelError(nameof(model.CaptchaCode), "Wrong Captcha Code");
                return(Conflict(ModelState));
            }

            var response = await _commentService.CreateAsync(new CommentRequest(postId)
            {
                Username  = model.Username,
                Content   = model.Content,
                Email     = model.Email,
                IpAddress = DNT ? "N/A" : HttpContext.Connection.RemoteIpAddress.ToString()
            });

            if (_blogConfig.NotificationSettings.SendEmailOnNewComment && _notificationClient is not null)
            {
                _ = Task.Run(async() =>
                {
                    await _notificationClient.NotifyCommentAsync(response,
                                                                 s => ContentProcessor.MarkdownToContent(s, ContentProcessor.MarkdownConvertType.Html));
                });
            }

            if (_blogConfig.ContentSettings.RequireCommentReview)
            {
                return(Created("moonglade://empty", response));
            }

            return(Ok());
        }
Пример #20
0
        public async Task CreateAsync_ThrowsException_WhenNullDto()
        {
            Func <Task> action = async() => await _commentServices.CreateAsync(null);

            await action.Should().ThrowAsync <InvalidServiceOperationException>().WithMessage("Is null comment dto");
        }
Пример #21
0
        public async Task <IActionResult> NewComment(PostSlugViewModelWrapper model,
                                                     [FromServices] ISessionBasedCaptcha captcha)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    // Validate BasicCaptcha Code
                    if (!captcha.ValidateCaptchaCode(model.NewCommentViewModel.CaptchaCode, HttpContext.Session))
                    {
                        Logger.LogWarning("Wrong Captcha Code");
                        ModelState.AddModelError(nameof(model.NewCommentViewModel.CaptchaCode), "Wrong Captcha Code");

                        Response.StatusCode = (int)HttpStatusCode.BadRequest;
                        var cResponse = new CommentResponse(false, CommentResponseCode.WrongCaptcha);
                        return(Json(cResponse));
                    }

                    var commentPostModel = model.NewCommentViewModel;
                    var response         = await _commentService.CreateAsync(new NewCommentRequest(commentPostModel.PostId)
                    {
                        Username  = commentPostModel.Username,
                        Content   = commentPostModel.Content,
                        Email     = commentPostModel.Email,
                        IpAddress = HttpContext.Connection.RemoteIpAddress.ToString(),
                        UserAgent = UserAgent
                    });

                    if (response.IsSuccess)
                    {
                        if (_blogConfig.NotificationSettings.SendEmailOnNewComment && null != _notificationClient)
                        {
                            _ = Task.Run(async() =>
                            {
                                await _notificationClient.SendNewCommentNotificationAsync(response.Item, s => Utils.ConvertMarkdownContent(s, Utils.MarkdownConvertType.Html));
                            });
                        }
                        var cResponse = new CommentResponse(true,
                                                            _blogConfig.ContentSettings.RequireCommentReview ?
                                                            CommentResponseCode.Success :
                                                            CommentResponseCode.SuccessNonReview);

                        return(Json(cResponse));
                    }

                    CommentResponse failedResponse;
                    switch (response.ResponseCode)
                    {
                    case (int)ResponseFailureCode.CommentDisabled:
                        Logger.LogWarning("Comment is disabled in settings, but user somehow called NewComment() method.");
                        Response.StatusCode = (int)HttpStatusCode.Forbidden;
                        failedResponse      = new CommentResponse(false, CommentResponseCode.CommentDisabled);
                        break;

                    default:
                        Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                        failedResponse      = new CommentResponse(false, CommentResponseCode.UnknownError);
                        break;
                    }
                    return(Json(failedResponse));
                }

                Response.StatusCode = (int)HttpStatusCode.BadRequest;
                return(Json(new CommentResponse(false, CommentResponseCode.InvalidModel)));
            }
            catch (Exception e)
            {
                Logger.LogError(e, "Error NewComment");
                Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                return(Json(new CommentResponse(false, CommentResponseCode.UnknownError)));
            }
        }
Пример #22
0
        public async Task CreateAsync_ShouldUndeleteCommentRecordIfExist()
        {
            //Arrange
            var options = InMemory.GetOptions("CreateAsync_ShouldUndeleteCommentRecordIfExist");

            using (var context = new BOContext(options))
            {
                var country = new Country()
                {
                    Name      = "Bulgaria",
                    Breweries = new List <Brewery>()
                    {
                        new Brewery()
                        {
                            Name  = "Brewery",
                            Beers = new List <Beer>()
                            {
                                new Beer()
                                {
                                    ABV     = 4.5f,
                                    Rating  = 2,
                                    Name    = "Carlsberg",
                                    Country = new Country()
                                    {
                                        Name = "Germany"
                                    },
                                    Style = new BeerStyle()
                                    {
                                        Name = "Ale"
                                    }
                                }
                            }
                        }
                    }
                };
                context.Countries.Add(country);
                await context.SaveChangesAsync();

                var user = new User()
                {
                    Name = "SuperMan"
                };
                context.Users.Add(user);
                await context.SaveChangesAsync();

                var review = new Review
                {
                    Description = "Great",
                    Beer        = await context.Beers.FirstOrDefaultAsync(b => b.Name == "Carlsberg"),
                    User        = await context.Users.FirstOrDefaultAsync(b => b.Name == "SuperMan"),
                };
                context.Reviews.Add(review);
                await context.SaveChangesAsync();

                var comment = new Comment()
                {
                    Description = "Gotham",
                    User        = await context.Users.FirstOrDefaultAsync(b => b.Name == "SuperMan"),
                    Review      = await context.Reviews.FindAsync(1),
                    IsDeleted   = true,
                    DeletedOn   = DateTime.UtcNow
                };
                context.Comments.Add(comment);
                await context.SaveChangesAsync();
            }

            using (var context = new BOContext(options))
            {
                var commentDTO = new CommentDTO
                {
                    Description = "Gotham",
                    UserID      = 1,
                    ReviewID    = 1
                };
                //Act
                var sut = new CommentService(context);
                await sut.CreateAsync(commentDTO);

                var dbresult = await context.Comments.FindAsync(1);

                //Assert
                Assert.AreEqual(dbresult.Description, "Gotham");
                Assert.AreEqual(dbresult.DeletedOn, null);
                Assert.AreEqual(dbresult.IsDeleted, false);
            }
        }