public async Task AddCommentAsync_Should_AddCommentToUow() { var dto = new CommentAddDTO { PhotoId = 1, Text = "text" }; mockUow.Setup(uow => uow.Photos.GetByIdAsync(dto.PhotoId)).ReturnsAsync(new Photo()); mockUow.Setup(uow => uow.Comments.AddAsync(It.Is <Comment>(c => c.Text == dto.Text))).Verifiable(); await service.AddCommentAsync(dto); mockUow.Verify(); }
public async Task AddCommentAsyncShouldWorkCorrectIfParametersAreValid() { //Arange var options = new DbContextOptionsBuilder <ApplicationDbContext>() .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString()).Options; //Act var db = new ApplicationDbContext(options); var config = new MapperConfiguration(cfg => { cfg.AddProfile <ApplicationProfile>(); }); var mapper = new Mapper(config); var commentService = new CommentService(db, mapper); var user = new ApplicationUser { UserName = "******", Email = "*****@*****.**", PasswordHash = "abcdefg1" }; await db.Users.AddAsync(user); await db.SaveChangesAsync(); await commentService.AddCommentAsync(user.Id, "Niko", "Hello!"); //assert Assert.True(await db.Comments.CountAsync() == 1); }
public async Task <IActionResult> PostComment([FromBody] Comment comment) { Result <CommentModel> result = await _commentService.AddCommentAsync(comment); return(result.ResultType switch { ResultType.Created => StatusCode(StatusCodes.Status201Created, result.Payload), ResultType.NotFound => NotFound(result.Message), _ => StatusCode(StatusCodes.Status500InternalServerError, result.Message), });
public async Task AddComment_ShouldCallAddMethodAsync( [Frozen] Mock <IDbOperations <CommentModel> > commentModelDbOperationsMock, CommentService commentService) { var commentResult = await commentService.AddCommentAsync(1, "testContent"); commentModelDbOperationsMock.Verify( x => x.AddAsync(It.Is <CommentModel>(y => y.TaskId == 1 && y.Content == "testContent")), Times.Once); }
public async Task <IActionResult> AddComment([FromBody] AddCommentDto dto) { if (!HttpContext.User.Identity.IsAuthenticated) { return(Forbid()); } Result result = await _commentService.AddCommentAsync(dto, UserId, UserName, UserPhotoUrl); return(FromResult(result)); }
public async Task AddCommentAsyncTest() { var context = EssayCompetitionContextInMemoryFactory.InitializeContext(); var essay = await this.seeder.SeedEssayAsync(context); var commentContent = "testComment"; var user = await this.seeder.SeedUserAsync(context, "*****@*****.**"); var commentRepository = new EfDeletableEntityRepository <Comment>(context); var service = new CommentService(commentRepository); await service.AddCommentAsync(user.Id, essay.Id, commentContent); var result = service.GetCommentsFromEssay <CommentViewModel>(essay.Id); Assert.True(result.Any(x => x.Content == commentContent) == true, "AddCommentAsync method does not work correctly"); }
public async Task GetAllAsyncShouldReturnCollection() { //Arange var options = new DbContextOptionsBuilder <ApplicationDbContext>() .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString()).Options; //Act var db = new ApplicationDbContext(options); var config = new MapperConfiguration(cfg => { cfg.AddProfile <ApplicationProfile>(); }); var mapper = new Mapper(config); var commentService = new CommentService(db, mapper); var user = new ApplicationUser { UserName = "******", Email = "*****@*****.**", PasswordHash = "abcdefg1" }; var post = new Post { ImageUrl = "https://media.istockphoto.com/vectors/set-of-round-minus-and-plus-sign-icons-buttons-flat-negative-and-on-vector-id1189799128?b=1&k=6&m=1189799128&s=612x612&w=0&h=Dh3OKJ30k2hJj8948AU4MpNHfDL6Au3YrtcKD_UpMK8=", Title = "Some Post", Description = "Some Description", CreatedOn = DateTime.UtcNow }; await db.Users.AddAsync(user); await db.Posts.AddAsync(post); await db.SaveChangesAsync(); await commentService.AddCommentAsync(user.Id, "Niko", "Hello!"); var postModel = await db.Posts.FirstOrDefaultAsync(); await commentService.AddCommentToPostAsync(user.Id, "Niksan", "Hi", post.Id); var models = commentService.GetAllAsync(); //assert Assert.True(models != null); }
public async Task <IActionResult> Index(DailyViewModel model) { if (ModelState.IsValid) { // get the currently logged in user (or null if there isn't one) var user = await _userManager.GetUserAsync(HttpContext.User); model.Comment.UserId = user?.Id; // TODO: Check for the ImageHalf in the db by its id before doing this? // to prevent this comment from being tied to a different or nonexistant image model.Comment.ImageGrid = model.ImageHalf; // attempt to add the comment to the database bool commentAdded = await _commentService.AddCommentAsync(model.Comment); } else { ModelState.AddModelError("", "Invalid input"); } return(View(model)); }
public async Task <ActionResult> CommonCreate(CreateRouteCommentModel comment) { try { await CommentService.AddCommentAsync(new services.models.AddComment { CenterNumber = comment.CenterNumber, CreatedBy = LastFirstName.ToUpperInvariant(), Status = (comment.IsInternal ? 2 : 3), PrimaryRecordId = $"{comment.BillTo}-{comment.ShipTo}", SecondaryRecordId = comment.RoutePlanId.ToString(), Screen = comment.Screen, ShortComment = comment.Category, LongComment = comment.LongComment }); return(RedirectToAction("ListByBillToShipTo", new { billTo = comment.BillTo, shipTo = comment.ShipTo, stopNumber = comment.StopNumber, routePlanId = comment.RoutePlanId, centerNumber = comment.CenterNumber, screen = comment.Screen })); } catch { return(null); } }
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.AddCommentAsync(new NewCommentRequest(commentPostModel.PostId) { Username = commentPostModel.Username, Content = commentPostModel.Content, Email = commentPostModel.Email, IpAddress = HttpContext.Connection.RemoteIpAddress.ToString(), UserAgent = GetUserAgent() }); if (response.IsSuccess) { if (_blogConfig.EmailSettings.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.EmailDomainBlocked: Logger.LogWarning("User email domain is blocked."); Response.StatusCode = (int)HttpStatusCode.Forbidden; failedResponse = new CommentResponse(false, CommentResponseCode.EmailDomainBlocked); break; 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))); } }
public async Task <ActionResult <int> > AddCommentAsync(int id, string content) { var commentResult = await _commentService.AddCommentAsync(id, content); return(ActionResultHelper <int> .GetActionResult(commentResult)); }