예제 #1
0
        public async Task GivenValidRequest_WhenTheArticleExists_AddsCommentToArticle()
        {
            // Arrange
            var commentDto = new AddCommentDto
            {
                Body = "This article sucks!"
            };
            var addCommentCommand = new AddCommentCommand
            {
                Slug    = "how-to-train-your-dragon",
                Comment = commentDto
            };
            var articleComments = Context.Articles
                                  .Include(a => a.Comments)
                                  .FirstOrDefault(a => a.Slug == "how-to-train-your-dragon")?
                                  .Comments;

            articleComments?.Count.ShouldBe(2);
            articleComments?.ShouldNotContain(c => c.Body == "This article sucks!");

            // Act
            var handler  = new AddCommentCommandHandler(CurrentUserContext, Context, Mapper, MachineDateTime);
            var response = await handler.Handle(addCommentCommand, CancellationToken.None);

            // Assert
            response.ShouldNotBeNull();
            response.ShouldBeOfType <CommentViewModel>();
            response.Comment.ShouldNotBeNull();
            response.Comment.ShouldBeOfType <CommentDto>();
            articleComments?.Count.ShouldBe(3);
            articleComments?.ShouldContain(c => c.Body == "This article sucks!");
        }
예제 #2
0
        public async Task GivenValidRequest_WhenTheArticleDoesNotExist_ThrowsApiException()
        {
            // Arrange
            var commentDto = new AddCommentDto
            {
                Body = "This article sucks!"
            };
            var addCommentCommand = new AddCommentCommand
            {
                Slug    = "how-to-not-train-your-dragon",
                Comment = commentDto
            };

            // Act
            var handler  = new AddCommentCommandHandler(CurrentUserContext, Context, Mapper, MachineDateTime);
            var response = await Should.ThrowAsync <ConduitApiException>(async() =>
            {
                await handler.Handle(addCommentCommand, CancellationToken.None);
            });

            // Assert
            response.StatusCode.ShouldBe(HttpStatusCode.NotFound);
            response.ShouldNotBeNull();
            response.ShouldBeOfType <ConduitApiException>();
        }
예제 #3
0
            public async Task <Result <CommentDto> > Handle(AddCommentCommand request, CancellationToken cancellationToken)
            {
                var activity = await _context.Activities.FindAsync(request.ActivityId);

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

                var user = await _context.Users
                           .Include(p => p.Photos)
                           .SingleOrDefaultAsync(x => x.UserName == _userAccessor.GetUsername());

                var comment = new Comment
                {
                    Author   = user,
                    Activity = activity,
                    Body     = request.Body
                };

                activity.Comments.Add(comment);

                var succeess = await _context.SaveChangesAsync() > 0;

                if (succeess)
                {
                    return(Result <CommentDto> .Success(_mapper.Map <CommentDto>(comment)));
                }

                return(Result <CommentDto> .Failure("Failed to add comment"));
            }
예제 #4
0
        public async Task GivenValidRequest_WhenTheArticleExists_ReturnsCommentViewModel()
        {
            // Arrange
            var comment = new AddCommentCommand
            {
                Comment = new AddCommentDto
                {
                    Body = "You stink!"
                }
            };
            var requestContent = await ContentHelper.GetRequestContentWithAuthorization(comment, Client, IntegrationTestConstants.SecondaryUser);

            // Act
            var response = await Client.PostAsync($"{ArticlesEndpoint}/how-to-train-your-dragon/comments", requestContent);

            var responseContent = await ContentHelper.GetResponseContent <CommentViewModel>(response);

            // Assert
            response.EnsureSuccessStatusCode();
            responseContent.ShouldNotBeNull();
            responseContent.ShouldBeOfType <CommentViewModel>();
            responseContent.Comment.ShouldNotBeNull();
            responseContent.Comment.ShouldBeOfType <CommentDto>();
            responseContent.Comment.Body.ShouldNotBeEmpty(comment.Comment.Body);
            responseContent.Comment.Author.Username.ShouldBe("test.user");
        }
        public virtual PartialViewResult Add(CommentCreateModel model)
        {
            var commentsTarget = FullContext.GetCommentsTarget();
            var targetEntityId = commentsTarget.EntityId.Value;

            if (!ModelState.IsValid)
            {
                return(OverView(targetEntityId));
            }

            var createDto = MapToCreateDto(model, targetEntityId);
            var command   = new AddCommentCommand(FullContext, createDto);

            _commandPublisher.Publish(command);

            OnCommentCreated(createDto.Id);

            switch (commentsTarget.Type.ToInt())
            {
            case int type
                when ContextExtensions.HasFlagScalar(type, ContextType.Activity | ContextType.PagePromotion):
                var activityCommentsInfo = GetActivityComments(targetEntityId);

                return(OverView(activityCommentsInfo));

            default:
                return(OverView(targetEntityId));
            }
        }
        public async Task <AddCommentResponse> Handle(AddCommentRequest request, CancellationToken cancellationToken)
        {
            var query = new GetAssignmentQuery()
            {
                Id = request.AssignmentId
            };
            var assignment = await queryExecutor.Execute(query);

            if (assignment == null)
            {
                return(new AddCommentResponse()
                {
                    Error = new ErrorModel(ErrorType.NotFound)
                });
            }

            var comment = mapper.Map <Comment>(request);
            var command = new AddCommentCommand()
            {
                Parameter = comment
            };
            var commentFromDb = await commandExecutor.Execute(command);

            return(new AddCommentResponse()
            {
                Data = mapper.Map <CommentDto>(commentFromDb)
            });
        }
예제 #7
0
        public void AddComment_Success()
        {
            //Arrange
            CommonInstances.CreateTestInstances();
            var fakeMember    = new Member("TestMemberName");
            var fakeCurrTeam  = Commons.currentTeam;
            var fakeCurrBoard = Commons.currentBoard;

            fakeCurrTeam.Members.Add(fakeMember);
            var listParams = new List <string>()
            {
                "WorkItemTitle", "TestMemberName", "BlaBlaBla"
            };
            var workItem = new Bug("WorkItemTitle", "WorkItemDescription", Priority.High, Severity.Critical);

            fakeCurrBoard.WorkItems.Add(workItem);
            var fakeMemberProvider = new FakeMemberProvider();

            fakeMemberProvider.Add(fakeMember);

            var sut = new AddCommentCommand(listParams, fakeMemberProvider);

            //Act
            sut.Execute();

            //Assert
            Assert.AreEqual(1, workItem.Comments.Count);
        }
        public void Should_have_error_when_comment_text_is_empty()
        {
            var postRepository = new Mock <IPostRepository>();
            var validator      = new AddCommentCommandValidator(postRepository.Object);
            var command        = new AddCommentCommand(Guid.NewGuid(), "", false);

            validator.ShouldHaveValidationErrorFor(x => x.Text, command);
        }
예제 #9
0
        public async Task <IActionResult> AddComment(Guid id, [FromBody] AddCommentCommand command, CancellationToken cancellationToken)
        {
            command.MeetupId = id;

            var commentId = await _mediator.Send(command, cancellationToken);

            return(Ok(commentId));
        }
예제 #10
0
        public void Constructor_SetsProperties()
        {
            var dut = new AddCommentCommand(
                1,
                _comment);

            Assert.AreEqual(1, dut.InvitationId);
            Assert.AreEqual(_comment, dut.Comment);
        }
예제 #11
0
        public async Task <IActionResult> Post(int postId, [FromBody] AddCommentCommand command)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState.Errors().First()));
            }
            await Mediator.Send(command);

            return(NoContent());
        }
        public void Setup_OkState()
        {
            _invitationValidatorMock = new Mock <IInvitationValidator>();
            _invitationValidatorMock.Setup(inv => inv.IpoExistsAsync(_invitationId, default)).Returns(Task.FromResult(true));
            _command = new AddCommentCommand(
                _invitationId,
                _commentText);

            _dut = new AddCommentCommandValidator(_invitationValidatorMock.Object);
        }
예제 #13
0
        public void AddComment_ReturnsCorrectOutput()
        {
            var factory    = new Mock <IFactory>();
            var parameters = new List <string>()
            {
                "2", "Member1", "This is a comment."
            };
            var command = new AddCommentCommand(parameters, database, factory.Object);

            Assert.AreEqual("Member: 'Member1' added comment: 'This is a comment.' to work item: '2'", command.Execute());
        }
예제 #14
0
        public async Task <int> AddComment(CommentDto commentDto)
        {
            var command = new AddCommentCommand()
            {
                Id     = commentDto.Id,
                NewsId = commentDto.NewsId,
                Text   = commentDto.Text,
                UserId = commentDto.UserId
            };

            return(await _mediator.Send(command));
        }
예제 #15
0
        public async Task <ActionResult> Create(int postId, CommentRequest commentRequest)
        {
            var addCommentCommand = new AddCommentCommand
            {
                Content = commentRequest.Content,
                PostId  = postId,
                UserId  = User.FindFirst(ClaimTypes.NameIdentifier)?.Value
            };
            var createdCommentId = await Mediator.Send(addCommentCommand);

            return(StatusCode(201, createdCommentId));
        }
        public void Should_have_error_when_post_does_not_exist()
        {
            var postId = Guid.NewGuid();

            var postRepository = new Mock <IPostRepository>();

            postRepository.Setup(x => x.GetById(postId)).Returns <Post>(null);

            var validator = new AddCommentCommandValidator(postRepository.Object);
            var command   = new AddCommentCommand(postId, "", false);

            validator.ShouldHaveValidationErrorFor(x => x.PostId, command);
        }
예제 #17
0
        public async Task ValidateAsync_OnAddCommentCommand_ShouldReturnFalse_WhenNoAccessToProject()
        {
            // Arrange
            var command = new AddCommentCommand(
                _invitationIdWithoutAccessToProject,
                null);

            // act
            var result = await _dut.ValidateAsync(command);

            // Assert
            Assert.IsFalse(result);
        }
        public async Task <Response <bool> > Handle(AddCommentCommand request, CancellationToken cancellationToken)
        {
            var comment = new Comment
            {
                CreatedDate = DateTime.UtcNow,
                senderId    = request.Userid,
                Description = request.Description,
                BookId      = request.bookId
            };
            await commentRepo.AddAsync(comment);

            return(Response.Ok());
        }
예제 #19
0
        public async Task <IActionResult> AddComment([FromBody] CommentToAddRequest comment, CancellationToken cancellationToken)
        {
            var identifier = User.GetUserId();

            var command = new AddCommentCommand
            {
                Comment      = comment,
                LoggedUserId = identifier
            };

            await _mediator.Send(command);

            return(NoContent());
        }
예제 #20
0
        public async Task <IActionResult> AddComment(AddCommentViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(RedirectToAction(nameof(BlogPostBySlug), new { slug = model.Slug }));
            }

            if (model.Text != null)
            {
                model.Text = model.Text.Replace("<", "&lt;");
                model.Text = model.Text.Replace(">", "&gt;");
            }

            // validate comment isn't spam
            var comment = new AkismetComment
            {
                UserIp      = Request.HttpContext.Connection.RemoteIpAddress.ToString(),
                UserAgent   = Request.Headers["User-Agent"].ToString(),
                Author      = model.Name,
                AuthorEmail = model.Email,
                AuthorUrl   = model.Website,
                CommentType = "comment",
                Content     = model.Text,
                Permalink   = _akismetClient.BlogUrl + Url.Action(nameof(BlogPostBySlug), new { slug = model.Slug })
            };

            if (await _akismetClient.IsCommentSpam(comment))
            {
                return(RedirectToAction(nameof(BlogPostBySlug), new { slug = model.Slug }));
            }

            var addComment = new AddCommentCommand
            {
                Name       = model.Name,
                Email      = model.Email,
                Website    = model.Website,
                Text       = model.Text,
                BlogPostId = model.Id
            };

            var result = await _cp.ProcessAsync(addComment);

            if (result.Succeeded)
            {
                return(RedirectToAction(nameof(BlogPostBySlug), new { slug = model.Slug }));
            }
            _logger.LogError("Error adding comment...");

            return(RedirectToAction(nameof(BlogPostBySlug), new { slug = model.Slug }));
        }
예제 #21
0
        public void AddComment_ExecuteLessParams_ThrowEx()
        {
            //Arrange
            var listParams = new List <string>()
            {
                "WorkItemTitle", "TeamMemberName"
            };
            var fakeMemberProvider = new FakeMemberProvider();

            var sut = new AddCommentCommand(listParams, fakeMemberProvider);

            //Act & Assert
            Assert.ThrowsException <ArgumentException>(() => sut.Execute(), "Parameters count is not valid!");
        }
        public async Task AddComment_ShouldResponseBool()
        {
            //tested..works fine
            await AuthenticateMeBabyAsync();

            var command = new AddCommentCommand
            {
                Description = "خیلی خوبه خوشم اومد",
                bookId      = "083c9930-3327-4d28-86fa-b4c830c7e188"
            };
            var response = await Client.PostAsJsonAsync("api/comment", command);

            var content = await response.Content.ReadAsAsync <Response <bool> >();

            content.Item.Should().Be(true);
        }
        public async Task AddComment(AddCommentCommand addCommentCommand)
        {
            var queryRequest = new QueryRequest()
                               .Statement($"UPDATE `{_eventsBucket.Name}` USE KEYS $eventId SET comments = ARRAY_APPEND(IFMISSINGORNULL(comments,[]), $comment);")
                               .AddNamedParameter("$eventId", addCommentCommand.EventId)
                               .AddNamedParameter("$comment", new EventCommentDocument {
                Comment = addCommentCommand.Comment, CommentatorId = addCommentCommand.CommentatorId, CommentedDate = addCommentCommand.CommentedDate
            });

            var queryResult = await _eventsBucket.QueryAsync <dynamic>(queryRequest);

            if (!queryResult.Success)
            {
                throw queryResult.Exception;
            }
        }
예제 #24
0
        public void Should_call_validate_command_when_add_new_comment()
        {
            var comment = Comment.CreateNew(Guid.NewGuid(), "Text", false);
            var command = new AddCommentCommand(comment.PostId, comment.Text, comment.Approved);

            var commentRepository = new Mock <ICommentRepository>();

            var validator = new Mock <IValidator <AddCommentCommand> >();

            validator.Setup(x => x.Validate(command)).Returns(new ValidationResult());

            var addCommentCommandHandler = new AddCommentCommandHandler(commentRepository.Object, validator.Object);

            addCommentCommandHandler.Handle(command);

            validator.Verify(x => x.Validate(command));
        }
        public async Task <IActionResult> Post(Guid?parentId, [FromBody] CommentViewModel comment)
        {
            var command = new AddCommentCommand
            {
                ParentId      = parentId.GetValueOrDefault(),
                ParentVersion = comment.ParentVersion.Value.GetValueOrDefault(),
                CommentText   = comment.CommentText.Value,
                UserName      = comment.UserName.Value,
                TenantId      = comment.TenantId.Value
            };

            var result = await _mediator.Send(command);

            return(result.Success
                ? Created($"~/api/valuecomment/{result.Model.ParentId}/{result.Model.Id}", ToViewModel(result.Model))
                : CreateBadRequestResult(result));
        }
예제 #26
0
        public void AddComment_NoWorkItemToAddCommentTo_ThrowEx()
        {
            //Arrange
            CommonInstances.CreateTestInstances();
            var fakeCurrBoard = Commons.currentBoard;
            var listParams    = new List <string>()
            {
                "WorkItemTitle", "TestMemberName", "BlaBlaBla"
            };
            var workItem           = new Bug("WorkItemTitle", "WorkItemDescription", Priority.High, Severity.Critical);
            var fakeMemberProvider = new FakeMemberProvider();

            var sut = new AddCommentCommand(listParams, fakeMemberProvider);

            //Act & Assert
            Assert.ThrowsException <ArgumentException>(() => sut.Execute(), "No items in this board!");
        }
예제 #27
0
        public async Task <IActionResult> AddComment(AddCommentCommand commentDto)
        {
            if (!ModelState.IsValid)
            {
                Log.ForContext("Message", "AddComment")
                .ForContext("Error", "ModelStateNotValid").Error($"Error: ** AddComment");
                return(Error(new { info = "اطلاعات بدرستی وارد نشده است." }));
            }


            var result = await _mediator.Send(new AddCommentCommand()
            {
                PostId = commentDto.PostId,
                Text   = commentDto.Text
            });

            return(result == ResultStatus.Success ? Success(result) : Error(new { info = "خطایی رخ داده است" }));
        }
예제 #28
0
        public void AddComment_WorkItemNotInTheBoard_ThrowEx()
        {
            //Arrange
            CommonInstances.CreateTestInstances();
            var fakeMember    = new Member("TestMemberName");
            var fakeCurrTeam  = Commons.currentTeam;
            var fakeCurrBoard = Commons.currentBoard;
            var listParams    = new List <string>()
            {
                "WorkItemTitle", "TestMemberName", "BlaBlaBla"
            };
            var fakeMemberProvider = new FakeMemberProvider();

            var sut = new AddCommentCommand(listParams, fakeMemberProvider);

            //Act & Assert
            Assert.ThrowsException <ArgumentException>(() => sut.Execute(), $"Work item with title WorkItemTitle does not exist in board {fakeCurrBoard.Name}.");
        }
예제 #29
0
        public async Task <IHttpActionResult> Add([FromBody] CommentCreateModel model)
        {
            if (model.EntityType.Is(IntranetEntityTypeEnum.Social, IntranetEntityTypeEnum.News, IntranetEntityTypeEnum.Events))
            {
                var member = await _intranetMemberService.GetCurrentMemberAsync();

                var activityGroupId = _groupActivityService.GetGroupId(model.EntityId);

                if (activityGroupId.HasValue)
                {
                    var group = _groupService.Get(activityGroupId.Value);
                    if (group == null || group.IsHidden)
                    {
                        return(StatusCode(HttpStatusCode.Forbidden));
                    }
                }

                if (activityGroupId.HasValue && !member.GroupIds.Contains(activityGroupId.Value))
                {
                    return(StatusCode(HttpStatusCode.Forbidden));
                }
            }

            var createDto = await MapToCreateDtoAsync(model, model.EntityId);

            var command = new AddCommentCommand(model.EntityId, model.EntityType, createDto);

            _commandPublisher.Publish(command);

            await OnCommentCreatedAsync(createDto.Id, model.EntityType);

            switch (model.EntityType)
            {
            case IntranetEntityTypeEnum type
                when type.Is(IntranetEntityTypeEnum.News, IntranetEntityTypeEnum.Social, IntranetEntityTypeEnum.Events):
                var activityCommentsInfo = GetActivityComments(model.EntityId);

                return(Ok(await _commentsHelper.OverViewAsync(activityCommentsInfo.Id, activityCommentsInfo.Comments, activityCommentsInfo.IsReadOnly)));

            default:
                return(Ok(await _commentsHelper.OverViewAsync(model.EntityId)));
            }
        }
예제 #30
0
        /// <summary>
        /// Add a new Comment to a Post
        /// </summary>
        /// <param name="addCommentCommand"></param>
        /// <param name="currentUserEmail"></param>
        public void AddCommentToPost(AddCommentCommand addCommentCommand, string currentUserEmail)
        {
            if (string.IsNullOrWhiteSpace(currentUserEmail))
            {
                throw new NullReferenceException("Couldn't verify current User's identity");
            }
            var post = _postRepository.GetPostById(addCommentCommand.PostId);

            if (post == null)
            {
                throw new NullReferenceException(string.Format("Could not find a Post with ID:{0}", addCommentCommand.PostId));
            }
            // If the Commenter's email is not equal to the current user's email, do not proceed
            if (!currentUserEmail.Equals(addCommentCommand.AuthorEmail))
            {
                throw new InvalidOperationException("Email verification mismatch. Aborting operation");
            }
            post.AddNewComment(addCommentCommand.AuthorEmail, addCommentCommand.Text);
            _postRepository.Update(post);
        }