Beispiel #1
0
        public async Task GetByUserShouldTakeTwo()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString());
            var context = new ApplicationDbContext(options.Options);
            await context.Users.AddAsync(new ApplicationUser()
            {
                Id = "1"
            });

            var repository = new EfDeletableEntityRepository <Post>(context);
            var service    = new PostService(repository);
            var models     = new List <CreatePostInputModel>()
            {
                new CreatePostInputModel()
                {
                    Title    = "new",
                    Category = "Action",
                    Content  = "test",
                    ImageUrl = "google",
                },
                new CreatePostInputModel()
                {
                    Title    = "new2",
                    Category = "Action",
                    Content  = "test2",
                    ImageUrl = "google2",
                },
            };

            foreach (var model in models)
            {
                await service.CreateAsync(model, "1");
            }

            var lastModel = new CreatePostInputModel()
            {
                Title    = "new3",
                Category = "Rpg",
                Content  = "test3",
                ImageUrl = "google3",
            };
            await service.CreateAsync(lastModel, "2");

            var actual = await service.GetByUserAsync <PostViewModel>("1", 5, 0);

            Assert.Equal(2, actual.Count());
        }
        public async Task SearchPostShouldFindOneByTitle()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString());
            var context = new ApplicationDbContext(options.Options);
            await context.Users.AddAsync(new ApplicationUser()
            {
                Id = "1"
            });

            var postRepository   = new EfDeletableEntityRepository <Post>(context);
            var guideRepository  = new EfDeletableEntityRepository <Guide>(context);
            var searchBarService = new SearchBarService(postRepository, guideRepository);

            var postService = new PostService(postRepository);
            var postModel   = new CreatePostInputModel()
            {
                Title    = "testings",
                Category = "Action",
                Content  = "new",
                ImageUrl = "google",
            };

            await postService.CreateAsync(postModel, "1");

            var actual = await searchBarService.SearchPost <PostViewModel>("test", 5, 0);

            Assert.Single(actual);
        }
        public async Task CreateShouldReturnTrueIfUserExists()
        {
            // Arrange
            var db = MockManager.GetMockDatabase();

            var firstUser = new User
            {
                Id        = Guid.NewGuid().ToString(),
                UserName  = "******",
                Email     = "*****@*****.**",
                FirstName = "John",
                LastName  = "Doe"
            };

            await db.Users.AddAsync(firstUser);

            await db.SaveChangesAsync();

            var postService = new PostService(db);

            // Act
            var result = await postService.CreateAsync(firstUser.UserName, "Some title", "Some Content");

            // Assert
            result
            .Should()
            .Be(true);

            var post = await db.Posts.FirstOrDefaultAsync();

            post
            .Should()
            .NotBeNull();
        }
Beispiel #4
0
        public async Task EditPostShouldEditTitle()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString());
            var context = new ApplicationDbContext(options.Options);
            await context.Users.AddAsync(new ApplicationUser()
            {
                Id = "2"
            });

            var repository = new EfDeletableEntityRepository <Post>(context);
            var service    = new PostService(repository);
            var model      = new CreatePostInputModel()
            {
                Title    = "new",
                Category = "Action",
                Content  = "test",
                ImageUrl = "google",
            };

            var postId = await service.CreateAsync(model, "2");

            var oldPost = await service.GetPostByIdAsync <EditPostViewModel>(postId);

            var titleOldValue = oldPost.Title;

            await service.EditPostAsync(oldPost.Id, "NewValue", oldPost.Content);

            var newPost = await service.GetPostByIdAsync <EditPostViewModel>(postId);

            Assert.NotEqual(titleOldValue, newPost.Title);
        }
Beispiel #5
0
        public async Task DoesPostBelongToUserShouldReturnFalse()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString());
            var context = new ApplicationDbContext(options.Options);
            await context.Users.AddAsync(new ApplicationUser()
            {
                Id = "1"
            });

            await context.Users.AddAsync(new ApplicationUser()
            {
                Id = "2"
            });

            var repository = new EfDeletableEntityRepository <Post>(context);
            var service    = new PostService(repository);
            var model      = new CreatePostInputModel()
            {
                Title    = "new",
                Category = "Action",
                Content  = "test",
                ImageUrl = "google",
            };

            var postId = await service.CreateAsync(model, "2");

            var actual = await service.DoesPostBelongToUserAsync("1", postId);

            Assert.False(actual);
        }
Beispiel #6
0
        public async Task GetPostByIdShouldNotReturnModel()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString());
            var context = new ApplicationDbContext(options.Options);
            await context.Users.AddAsync(new ApplicationUser()
            {
                Id = "1"
            });

            var repository = new EfDeletableEntityRepository <Post>(context);
            var service    = new PostService(repository);
            var model      = new CreatePostInputModel()
            {
                Title    = "new",
                Category = "Action",
                Content  = "test",
                ImageUrl = "google",
            };

            await service.CreateAsync(model, "1");

            var actual = await service.GetPostByIdAsync <PostViewModel>("1234");

            Assert.Null(actual);
        }
Beispiel #7
0
        public async Task <ActionResult <PostResult> > Create(PostModel model)
        {
            await _postService.CreateAsync(model.CategoryId, model.Date.Value, model.Headline, model.Description,
                                           model.Price, model.EventDate, model.Image);

            return(Ok());
        }
Beispiel #8
0
        public async Task CreateAsync_WhenCalled_CreatesPostAndReturnsPostEntity()
        {
            var result = await _postService.CreateAsync(_postEntity);

            Assert.IsNotNull(result);
            Assert.AreEqual(_postId, result.Id);
            Assert.AreEqual(_postEntity.Title, result.Title);
            Assert.AreEqual(_postEntity.UserId, result.UserId);
        }
Beispiel #9
0
        public async Task GetCountBySearchShouldTakeThree()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString());
            var context = new ApplicationDbContext(options.Options);

            var repository = new EfDeletableEntityRepository <Post>(context);
            var service    = new PostService(repository);
            var models     = new List <CreatePostInputModel>()
            {
                new CreatePostInputModel()
                {
                    Title    = "new",
                    Category = "Action",
                    Content  = "test",
                    ImageUrl = "google",
                },
                new CreatePostInputModel()
                {
                    Title    = "testing it",
                    Category = "Action",
                    Content  = "test2",
                    ImageUrl = "google2",
                },
            };

            foreach (var model in models)
            {
                await service.CreateAsync(model, "1");
            }

            var newModel = new CreatePostInputModel()
            {
                Title    = "new3",
                Category = "Action",
                Content  = "test3",
                ImageUrl = "google3",
            };
            await service.CreateAsync(newModel, "2");

            var actual = await service.GetCountBySearchAsync("test");

            Assert.Equal(3, actual);
        }
        private async Task <Post> CreateEntity()
        {
            var entity = new Post()
            {
                Title = _entitySequence.ToString(),
                Body  = _entitySequence.ToString(),
            };

            var result = await _service.CreateAsync(entity);

            _entitySequence++;

            return(result.Result);
        }
        public async Task CreateAsyncShouldCreatedNewPostSuccessfully()
        {
            // Arrange
            var list = new List <Post>();

            var mockRepo = new Mock <IDeletableEntityRepository <Post> >();

            mockRepo.Setup(x => x.All())
            .Returns(list.AsQueryable);
            mockRepo.Setup(x => x.AddAsync(It.IsAny <Post>()))
            .Callback((Post post) => list.Add(post));

            var service = new PostService(mockRepo.Object);

            // Act
            await service.CreateAsync("Game of Thrones", "The best ever", 1, "v1");

            await service.CreateAsync("BMW", "The best BMW", 2, "v1");

            await service.CreateAsync("XUnit", "The best XUnit", 3, "v1");

            // Assert
            Assert.Equal(3, list.Count);
        }
Beispiel #12
0
        public async Task <IActionResult> AddPost(CreatePostViewModel model)
        {
            var u    = _userService.GetByLogin(User.Identity.Name);
            var post = new Post()
            {
                Body          = model.Body,
                Category      = model.Category,
                Comments      = null,
                CreatedDate   = DateTime.Now,
                Likes         = null,
                OwnerUserName = User.Identity.Name,
                CreateBy      = $"{u.Name} {u.Surname}",
            };
            await _postService.CreateAsync(post);

            return(RedirectToAction("News", "Home"));
        }
        public async Task CreateAsyncShouldCreateNewPostSuccessfullyAndReturnPostId()
        {
            // Arrange
            var list = new List <Post>();

            var mockRepo = new Mock <IDeletableEntityRepository <Post> >();

            mockRepo.Setup(x => x.All())
            .Returns(list.AsQueryable);
            mockRepo.Setup(x => x.AddAsync(It.IsAny <Post>()))
            .Callback((Post post) => list.Add(post));

            var service = new PostService(mockRepo.Object);

            // Act
            var postId = await service.CreateAsync("Game of Thrones", "The best ever", 1, "v1");

            // Assert
            Assert.Single(list);
            Assert.Equal(postId, list.FirstOrDefault().Id);
        }
        public async Task CreateShouldReturnFalseIfUserDoesNotExist()
        {
            // Arrange
            var db = MockManager.GetMockDatabase();

            var postService = new PostService(db);

            // Act
            var result = await postService.CreateAsync("unexistingUsername", "Some title", "Some Content");

            // Assert
            result
            .Should()
            .Be(false);

            var post = await db.Posts.FirstOrDefaultAsync();

            post
            .Should()
            .BeNull();
        }
Beispiel #15
0
        public async Task AddOnPostShouldAdd()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString());
            var context = new ApplicationDbContext(options.Options);

            var repository = new EfDeletableEntityRepository <Post>(context);
            var service    = new PostService(repository);
            var model      = new CreatePostInputModel()
            {
                Title    = "new",
                Category = "Action",
                Content  = "test",
                ImageUrl = "google",
            };

            await service.CreateAsync(model, "1");

            var actual = await service.GetAllCountAsync();

            Assert.Equal(1, actual);
        }
        public async Task GetByIdShouldReturnCorrectPost()
        {
            // Arrange
            var list = new List <Post>();

            var mockRepo = new Mock <IDeletableEntityRepository <Post> >();

            mockRepo.Setup(x => x.AllAsNoTracking())
            .Returns(list.AsQueryable);
            mockRepo.Setup(x => x.AddAsync(It.IsAny <Post>()))
            .Callback((Post post) => list.Add(post));

            var service = new PostService(mockRepo.Object);

            // Act
            var postId = await service.CreateAsync("Game of Thrones", "The best ever", 1, "v1");

            var post = await service.GetById <PostModel>(postId);

            // Assert
            Assert.Equal(post.Id, postId);
            Assert.Single(list);
        }
Beispiel #17
0
        public async Task CreateMethodShouldAddCorrectNewPostToDb()
        {
            var optionsBuilder = new DbContextOptionsBuilder <ApplicationDbContext>()
                                 .UseInMemoryDatabase(Guid.NewGuid().ToString());
            var dbContext = new ApplicationDbContext(optionsBuilder.Options);

            var postService = new PostService(dbContext);

            var postToAdd = new AddPostInputModel
            {
                CategoryId = 1,
                Content    = "testContent",
                Title      = "testTitle",
                UserId     = "testUser",
            };

            await postService.CreateAsync(postToAdd);

            Assert.NotNull(dbContext.Posts.FirstOrDefaultAsync());
            Assert.Equal("testContent", dbContext.Posts.FirstAsync().Result.Content);
            Assert.Equal("testTitle", dbContext.Posts.FirstAsync().Result.Title);
            Assert.Equal(1, dbContext.Posts.FirstAsync().Result.CategoryId);
        }
        public async Task <IActionResult> CreateOrEdit(PostEditViewModel model,
                                                       [FromServices] LinkGenerator linkGenerator,
                                                       [FromServices] IPingbackSender pingbackSender)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(Conflict(ModelState));
                }

                var tags = string.IsNullOrWhiteSpace(model.Tags)
                    ? Array.Empty <string>()
                    : model.Tags.Split(',').ToArray();

                var request = new EditPostRequest(model.PostId)
                {
                    Title               = model.Title.Trim(),
                    Slug                = model.Slug.Trim(),
                    EditorContent       = model.EditorContent,
                    EnableComment       = model.EnableComment,
                    ExposedToSiteMap    = model.ExposedToSiteMap,
                    IsFeedIncluded      = model.FeedIncluded,
                    ContentLanguageCode = model.ContentLanguageCode,
                    IsPublished         = model.IsPublished,
                    Tags                = tags,
                    CategoryIds         = model.SelectedCategoryIds
                };

                var tzDate = _dateTimeResolver.NowOfTimeZone;
                if (model.ChangePublishDate &&
                    model.PublishDate.HasValue &&
                    model.PublishDate <= tzDate &&
                    model.PublishDate.GetValueOrDefault().Year >= 1975)
                {
                    request.PublishDate = model.PublishDate;
                }

                var postEntity = model.PostId == Guid.Empty ?
                                 await _postService.CreateAsync(request) :
                                 await _postService.UpdateAsync(request);

                if (model.IsPublished)
                {
                    _logger.LogInformation($"Trying to Ping URL for post: {postEntity.Id}");

                    var pubDate = postEntity.PubDateUtc.GetValueOrDefault();

                    var link = linkGenerator.GetUriByAction(HttpContext, "Slug", "Post",
                                                            new
                    {
                        year  = pubDate.Year,
                        month = pubDate.Month,
                        day   = pubDate.Day,
                        postEntity.Slug
                    });

                    if (_blogConfig.AdvancedSettings.EnablePingBackSend)
                    {
                        _ = Task.Run(async() => { await pingbackSender.TrySendPingAsync(link, postEntity.PostContent); });
                    }
                }

                return(Json(new { PostId = postEntity.Id }));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error Creating New Post.");
                Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                return(Json(ex.Message));
            }
        }
        public async Task SearchPostShouldTakeFive()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString());
            var context = new ApplicationDbContext(options.Options);
            await context.Users.AddAsync(new ApplicationUser()
            {
                Id = "1"
            });

            var postRepository   = new EfDeletableEntityRepository <Post>(context);
            var guideRepository  = new EfDeletableEntityRepository <Guide>(context);
            var searchBarService = new SearchBarService(postRepository, guideRepository);

            var postService = new PostService(postRepository);
            var postModels  = new List <CreatePostInputModel>()
            {
                new CreatePostInputModel()
                {
                    Title    = "new",
                    Category = "Action",
                    Content  = "test",
                    ImageUrl = "google",
                },
                new CreatePostInputModel()
                {
                    Title    = "new",
                    Category = "Action",
                    Content  = "test1",
                    ImageUrl = "google",
                },
                new CreatePostInputModel()
                {
                    Title    = "testttt",
                    Category = "Action",
                    Content  = "new",
                    ImageUrl = "google",
                },
                new CreatePostInputModel()
                {
                    Title    = "new",
                    Category = "Action",
                    Content  = "test5",
                    ImageUrl = "google",
                },
                new CreatePostInputModel()
                {
                    Title    = "new",
                    Category = "Action",
                    Content  = "test7",
                    ImageUrl = "google",
                },
                new CreatePostInputModel()
                {
                    Title    = "newtest3",
                    Category = "Action",
                    Content  = "eee",
                    ImageUrl = "google",
                },
            };

            foreach (var postModel in postModels)
            {
                await postService.CreateAsync(postModel, "1");
            }

            var actual = await searchBarService.SearchPost <PostViewModel>("test", 5, 0);

            Assert.Equal(5, actual.Count());
        }
 public async Task <IActionResult> CreateAsync(Post item)
 {
     return(Ok(await postService.CreateAsync(GetUserInfo(User), item)));
 }