コード例 #1
0
        public async Task UpdateAsyncShould_ReturnsFalseIf_EventCreatorIsAnotherUser()
        {
            const string UpdaterId = "789io87714w78ex5";

            //Arrange
            var htmlServiceMock = IHtmlServiceMock.New(ContentForUpdate);

            var service = new BlogArticleService(Db, htmlServiceMock.Object, null);

            var author = UserCreator.Create();

            await this.Db.AddAsync(author);

            var article = ArticleCreator.Create(author.Id, null);

            await this.Db.AddAsync(article);

            await this.Db.SaveChangesAsync();

            //Act
            var result = await service.UpdateAsync(article.Id, UpdaterId, TitleForUpdate, ContentForUpdate);

            //Assert
            result.Should().BeFalse();

            htmlServiceMock.Verify(h => h.Sanitize(It.IsAny <string>()), Times.Never);
        }
コード例 #2
0
        private static async Task Stage1(CloudStorageContext cloudAcct, MicroBlogConfiguration.MicroBlogOptions allOpts, ILogger logger)
        {
            var s = "Welcome to Stage1";

            logger.LogInformation(s);
            var creationUpdation = DateTime.Now;
            var blogOh1          = new CompleteBlogEntry("my-new-url", "The first Title I Choosed",
                                                         "On top of the old help finishes an adult handicap. When can the drivel chew? How does the senior priest do the skip? Why can't a backlog pile a concentrate? The saga wins the proprietary equilibrium. The arrogance sponsors the jazz.", "article",
                                                         "Paul lawrence",
                                                         new List <string> {
                "KEllogs", "Tonka", "Roos"
            },
                                                         new List <string> {
                "New-Science", "Killer-Bees", "Rune Doogle"
            },
                                                         creationUpdation, DateTime.Today.AddDays(-100), creationUpdation, true);

            // In a whorld where this is a functionapp.
            // we pass this entire BlogPost into  function
            BlogArticleService bas = new BlogArticleService(cloudAcct, allOpts, logger);
            var newPost            = await CreatePost(bas, blogOh1);

            var editedPost = new CompleteBlogEntry(newPost).WithTitle("Jelly bean fiend");

            var ratherEditedPost = await UpdatePost(bas, editedPost);

            logger.LogInformation($"{ratherEditedPost.Id} {ratherEditedPost.Url}");
            var furtherEditedPost = await UpdatePost(bas, ratherEditedPost);

            logger.LogInformation($"{furtherEditedPost.Id} {furtherEditedPost.Url}");
        }
コード例 #3
0
        public async Task ArticleDetailsAsync()
        {
            // Arrange
            this.context.Articles.Add(new Article {
                Id = 1, Title = "First article"
            });
            await this.context.SaveChangesAsync();

            this.blogRepositoryMock
            .Setup(x => x.Details())
            .Returns(this.context.Articles)
            .Verifiable();

            var service = new BlogArticleService(this.blogRepositoryMock.Object, this.mapper);

            // Act
            var result = service.ArticleDetailsAsync <ArticleDetailsViewModel>(1);

            // Assert
            Assert.NotNull(result);
            await Assert.IsAssignableFrom <Task <ArticleDetailsViewModel> >(result);

            Assert.Equal(1, result.Id);
            Assert.Equal("First article", result.Result.Title);
        }
コード例 #4
0
        public async Task AllAsyncShould_ReturnsCorrectArticlesWith_DifferentPageIndex(int page)
        {
            //Arrange

            var article       = ArticleCreator.Create(Guid.NewGuid().ToString());
            var secondArticle = ArticleCreator.Create(Guid.NewGuid().ToString());
            var thirdArticle  = ArticleCreator.Create(Guid.NewGuid().ToString());
            var fourthArticle = ArticleCreator.Create(Guid.NewGuid().ToString());

            await this.Db.AddRangeAsync(article, secondArticle, thirdArticle, fourthArticle);

            await this.Db.SaveChangesAsync();

            var service = new BlogArticleService(Db, null, null);

            //Act
            var result = (await service.AllAsync <BlogArticleListingModel>(page)).ToList();

            var expectedCount = this.Db.Articles
                                .Skip((page - 1) * ArticlesPageSize)
                                .Take(ArticlesPageSize)
                                .Count();

            //Assert
            result.Should().AllBeOfType <BlogArticleListingModel>();
            result.Should().HaveCount(expectedCount);
            result.Should().BeInDescendingOrder(x => x.PublishDate);
        }
コード例 #5
0
        public async Task CreateAsyncShould_SetTheCorrectParametersForArticlePropertiesAnd_ReturnsArticleId()
        {
            const int    NewImageId = 258;
            const string Title      = "Title";
            const string Content    = "Content123";
            const string AuthorId   = "8945opi7563k87";

            //Arrange
            var picService = IPictureServiceMock.New(NewImageId);

            var htmlService = IHtmlServiceMock.New(Content);

            var service = new BlogArticleService(Db, htmlService.Object, picService.Object);

            //Act
            var resultId = await service.CreateAsync(Title, Content, null, AuthorId);

            var savedEntry = await Db.FindAsync <Article>(resultId);

            //Assert
            resultId.Should().Be(savedEntry.Id);

            htmlService.Verify(h => h.Sanitize(It.IsAny <string>()), Times.Once);

            picService.Verify(p =>
                              p.UploadImageAsync(It.IsAny <string>(), It.IsAny <IFormFile>()), Times.Once);

            savedEntry.Id.Should().Be(resultId);
            savedEntry.Title.Should().Match(Title);
            savedEntry.Content.Should().Match(Content);
            savedEntry.AuthorId.Should().Match(AuthorId);
            savedEntry.CloudinaryImageId.Should().Be(NewImageId);
        }
コード例 #6
0
        public async Task DeleteAsyncShould_ReturnsFalseIf_EventCreatorIsAnotherUser_And_ShouldNotDeleteArticle_AndImage()
        {
            const string anotherAuthorId = "899f4fgg5f57dm888m";

            //Arrange
            var picServiceMock = IPictureServiceMock.New(imageToDeleteId);

            var service = new BlogArticleService(Db, null, picServiceMock.Object);

            var author = UserCreator.Create();

            await this.Db.AddAsync(author);

            var article = ArticleCreator.Create(author.Id, null);

            await this.Db.AddAsync(article);

            await this.Db.SaveChangesAsync();

            //Act
            var result = await service.DeleteAsync(article.Id, anotherAuthorId);

            //Assert
            result.Should().BeFalse();

            picServiceMock.Verify(p => p.DeleteImageAsync(It.IsAny <int>()), Times.Never);

            this.Db.Articles.Should().Contain(a => a.Id == article.Id);
        }
コード例 #7
0
        public async Task DeleteAsyncShould_ReturnsTrueIf_EventCreatorIsAnotherUser_AndShouldDeleteArticle_AndImage()
        {
            //Arrange
            var picServiceMock = IPictureServiceMock.New(imageToDeleteId);

            var service = new BlogArticleService(Db, null, picServiceMock.Object);

            var author = UserCreator.Create();

            await this.Db.AddAsync(author);

            var image = ImageInfoCreator.CreateWithFullData(author.Id);

            await this.Db.AddAsync(image);

            var article = ArticleCreator.Create(author.Id, imageToDeleteId);

            await this.Db.AddAsync(article);

            await this.Db.SaveChangesAsync();

            //Act
            var result = await service.DeleteAsync(article.Id, author.Id);

            //Assert
            result.Should().BeTrue();

            picServiceMock.Verify(p => p.DeleteImageAsync(It.IsAny <int>()), Times.Once);

            this.Db.Articles.Should().NotContain(a => a.Id == article.Id);
        }
コード例 #8
0
        public async Task AllArticles_WithFewArticles_ShouldReturnAllArticles()
        {
            // Arrange
            this.context.Articles.Add(new Article {
                Id = 1, Title = "First article"
            });
            this.context.Articles.Add(new Article {
                Id = 2, Title = "Second article"
            });
            this.context.Articles.Add(new Article {
                Id = 3, Title = "Third article"
            });
            await this.context.SaveChangesAsync();

            this.blogRepositoryMock
            .Setup(m => m.Get())
            .Returns(this.context.Articles)
            .Verifiable();

            var service = new BlogArticleService(this.blogRepositoryMock.Object, this.mapper);

            // Act
            var result = service.AllArticles <BlogArticleViewModel>();

            // Assert
            this.blogRepositoryMock.Verify();
            Assert.NotNull(result);
            Assert.Equal(3, result.Count());
            Assert.Equal(new[] { 1, 2, 3 }, result.Select(c => c.Id).ToArray());
        }
コード例 #9
0
        public async Task UpdateAsyncShould_UpdateTheCorrectPropertiesAnd_ShouldReturnsTrueIf_EventCreatorIsTheSame()
        {
            //Arrange
            var htmlService = IHtmlServiceMock.New(ContentForUpdate);

            var service = new BlogArticleService(Db, htmlService.Object, null);

            var author = UserCreator.Create();

            await this.Db.AddAsync(author);

            var article = ArticleCreator.Create(author.Id, null);

            await this.Db.AddAsync(article);

            await this.Db.SaveChangesAsync();

            //Act
            var result = await service.UpdateAsync(article.Id, author.Id, TitleForUpdate, ContentForUpdate);

            var updatedEntry = await Db.FindAsync <Article>(article.Id);

            //Assert
            result.Should().BeTrue();

            htmlService.Verify(h => h.Sanitize(It.IsAny <string>()), Times.Once);

            Assert.Equal(updatedEntry.Title, TitleForUpdate);
            Assert.Equal(updatedEntry.Content, ContentForUpdate);
        }
コード例 #10
0
        private static async Task Stage2(CloudStorageContext cloudAcct, MicroBlogConfiguration.MicroBlogOptions allOpts, ILogger logger)
        {
            var s = "Welcome to Stage2";

            logger.LogInformation(s);
            var createdUpdate = DateTime.Now;
            var blogOh2       = new CompleteBlogEntry("Further-Missions-OfMercy", "Another Blog Post I created",
                                                      "Behaviour we improving at something to. Evil true high lady roof men had open. To projection considered it precaution an melancholy or. Wound young you thing worse along being ham. Dissimilar of favourable solicitude if sympathize middletons at. Forfeited up if disposing perfectly in an eagerness perceived necessary. Belonging sir curiosity discovery extremity yet forfeited prevailed own off. Travelling by introduced of mr terminated. Knew as miss my high hope quit. In curiosity shameless dependent knowledge up. ",
                                                      @"Behaviour we improving at something to. Evil true high lady roof men had open. To projection considered it precaution an melancholy or. Wound young you thing worse along being ham. Dissimilar of favourable solicitude if sympathize middletons at. Forfeited up if disposing perfectly in an eagerness perceived necessary. Belonging sir curiosity discovery extremity yet forfeited prevailed own off. Travelling by introduced of mr terminated. Knew as miss my high hope quit. In curiosity shameless dependent knowledge up. 

Remember outweigh do he desirous no cheerful. Do of doors water ye guest. We if prosperous comparison middletons at. Park we in lose like at no. An so to preferred convinced distrusts he determine. In musical me my placing clothes comfort pleased hearing. Any residence you satisfied and rapturous certainty two. Procured outweigh as outlived so so. On in bringing graceful proposal blessing of marriage outlived. Son rent face our loud near. 

Do commanded an shameless we disposing do. Indulgence ten remarkably nor are impression out. Power is lived means oh every in we quiet. Remainder provision an in intention. Saw supported too joy promotion engrossed propriety. Me till like it sure no sons. 

You vexed shy mirth now noise. Talked him people valley add use her depend letter. Allowance too applauded now way something recommend. Mrs age men and trees jokes fancy. Gay pretended engrossed eagerness continued ten. Admitting day him contained unfeeling attention mrs out. 

Domestic confined any but son bachelor advanced remember. How proceed offered her offence shy forming. Returned peculiar pleasant but appetite differed she. Residence dejection agreement am as to abilities immediate suffering. Ye am depending propriety sweetness distrusts belonging collected. Smiling mention he in thought equally musical. Wisdom new and valley answer. Contented it so is discourse recommend. Man its upon him call mile. An pasture he himself believe ferrars besides cottage. 

Do play they miss give so up. Words to up style of since world. We leaf to snug on no need. Way own uncommonly travelling now acceptance bed compliment solicitude. Dissimilar admiration so terminated no in contrasted it. Advantages entreaties mr he apartments do. Limits far yet turned highly repair parish talked six. Draw fond rank form nor the day eat. 

Passage its ten led hearted removal cordial. Preference any astonished unreserved mrs. Prosperous understood middletons in conviction an uncommonly do. Supposing so be resolving breakfast am or perfectly. Is drew am hill from mr. Valley by oh twenty direct me so. Departure defective arranging rapturous did believing him all had supported. Family months lasted simple set nature vulgar him. Picture for attempt joy excited ten carried manners talking how. Suspicion neglected he resolving agreement perceived at an. 

Rooms oh fully taken by worse do. Points afraid but may end law lasted. Was out laughter raptures returned outweigh. Luckily cheered colonel me do we attacks on highest enabled. Tried law yet style child. Bore of true of no be deal. Frequently sufficient in be unaffected. The furnished she concluded depending procuring concealed. 

Agreed joy vanity regret met may ladies oppose who. Mile fail as left as hard eyes. Meet made call in mean four year it to. Prospect so branched wondered sensible of up. For gay consisted resolving pronounce sportsman saw discovery not. Northward or household as conveying we earnestly believing. No in up contrasted discretion inhabiting excellence. Entreaties we collecting unpleasant at everything conviction. 

It real sent your at. Amounted all shy set why followed declared. Repeated of endeavor mr position kindness offering ignorant so up. Simplicity are melancholy preference considered saw companions. Disposal on outweigh do speedily in on. Him ham although thoughts entirely drawings. Acceptance unreserved old admiration projection nay yet him. Lasted am so before on esteem vanity oh. 

",
                                                      "Paul lawrence",
                                                      new List <string> {
                "tag01", "Fag02", "Snag-3"
            },
                                                      new List <string> {
                "People", "Flowers", "Dept of rage"
            },
                                                      createdUpdate, DateTime.Today.AddDays(-100), DateTime.Now, true);

            // In a whorld where this is a functionapp.
            // we pass this entire BlogPost into  function
            BlogArticleService bas = new BlogArticleService(cloudAcct, allOpts, logger);
            var newPost            = await CreatePost(bas, blogOh2);

            var editedPost = new CompleteBlogEntry(newPost).WithTags(new List <string> {
                "Jelly", "Future", "Pillow"
            });

            var ratherEditedPost = new CompleteBlogEntry(await UpdatePost(bas, editedPost));

            logger.LogInformation($"{ratherEditedPost.Id} {ratherEditedPost.Url}");
            var editedUrl         = ratherEditedPost.WithUrl("Slander-on-my-harmer");
            var furtherEditedPost = await UpdatePost(bas, editedUrl);

            logger.LogInformation($"{furtherEditedPost.Id} {furtherEditedPost.Url}");
        }
コード例 #11
0
        public async Task CreateArticleAsync_WithNullArticle_ShouldThrowException()
        {
            // Arrange
            Article article = null;
            var     servise = new BlogArticleService(null, null);

            // Act
            var result = servise.CreateArticleAsync(article, null);

            // Assert
            await Assert.ThrowsAsync <ArgumentNullException>(() => result);
        }
コード例 #12
0
        public async Task CreateArticleSavesToDatabase()
        {
            // Arrange
            TestStartUp startUp        = new TestStartUp();
            var         db             = startUp.GetDbContext();
            var         articleService = new BlogArticleService(db);

            // Act
            await articleService.CreateAsync("Title", "Content", "1");

            // Assert
            Assert.True(db.Articles.Any(a => a.Title == "Title"));
        }
コード例 #13
0
        public static async Task <IActionResult> Run([HttpTrigger(AuthorizationLevel.Admin, "post", Route = null)] HttpRequest req, ILogger log, ExecutionContext context)
        {
            log.LogInformation("CreateBlogEntry processed a request.");

            var completeArticle = AppConfigSettings.IngestRequest <CompleteClientArticle>(req, context);
            var articleInput    = AppConfigSettings.IngestRequest <CompleteClientArticle>(req, context);
            var mOpts           = AppConfigSettings.GetOptions();

            var bas     = new BlogArticleService(new CloudStorageContext(mOpts.StorageAccount), mOpts, log);
            var article = await bas.Add(completeArticle);

            return(new OkObjectResult(article));
        }
コード例 #14
0
        public static async Task <IActionResult> Run([HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req, ILogger log, ExecutionContext context)
        {
            log.LogInformation("GetArticleHeaders function processed a request.");

            var headersQuery = AppConfigSettings.IngestRequest <GetArticleHeadersInput>(req, context);
            List <IArticleDetails> results = new List <IArticleDetails>();
            var articleInput = AppConfigSettings.IngestRequest <CompleteClientArticle>(req, context);
            var mOpts        = AppConfigSettings.GetOptions();

            var bas = new BlogArticleService(new CloudStorageContext(mOpts.StorageAccount), mOpts, log);

            results.AddRange(await bas.FindArticlDetails(headersQuery.Start, headersQuery.End, headersQuery.Take, headersQuery.Skip));
            return(new OkObjectResult(results));
        }
コード例 #15
0
        public async Task DeleteArticleFromDatabase()
        {
            // Arrange
            TestStartUp startUp = new TestStartUp();
            var         db      = startUp.GetDbContext();

            this.PopulateDb(db);
            var articleService = new BlogArticleService(db);

            // Act
            await articleService.DeleteArticleAsync(2);

            // Assert
            Assert.True(!db.Articles.Any(a => a.Id == 2));
        }
コード例 #16
0
        public async Task GetArticleById()
        {
            // Arrange
            TestStartUp startUp = new TestStartUp();

            TestStartUp.InitializeMapper();
            var db = startUp.GetDbContext();

            this.PopulateDb(db);
            var articleService = new BlogArticleService(db);

            // Act
            var result = await articleService.ById(2);

            // Assert
            Assert.True(result.Id == 2);
        }
コード例 #17
0
        private static async Task Stage3(CloudStorageContext cloudAcct, MicroBlogConfiguration.MicroBlogOptions allOpts, ILogger logger)
        {
            BlogPostTests      bpt       = new BlogPostTests();
            var                FakePosts = bpt.CreateFakePosts().ToList();
            BlogArticleService bas       = new BlogArticleService(cloudAcct, allOpts, logger);
            var                tasks     = new List <Task <ICompletePost> >();

            FakePosts.ForEach((a) => tasks.Add(bas.Add(a)));
            Task.WaitAll(tasks.ToArray());
            //await bas.Add(FakePosts[0]);
            //await bas.Add(FakePosts[1]);
            //await bas.Add(FakePosts[2]);
            //await bas.Add(FakePosts[3]);
            //await bas.Add(FakePosts[4]);
            //await bas.Add(FakePosts[5]);
            //await bas.Add(FakePosts[9]);
        }
コード例 #18
0
        public async Task TotalAsync_ShouldReturnCorrectResult()
        {
            // Arrange
            this.blogRepositoryMock
            .Setup(x => x.GetCountAsync())
            .ReturnsAsync(1)
            .Verifiable();

            var service = new BlogArticleService(this.blogRepositoryMock.Object, null);

            // Act
            var result = await service.TotalAsync();

            // Assert
            this.blogRepositoryMock.Verify();
            Assert.Equal(1, result);
        }
コード例 #19
0
        public async Task UpdateArticleSaveToDatabase()
        {
            // Arrange
            TestStartUp startUp = new TestStartUp();

            TestStartUp.InitializeMapper();
            var db = startUp.GetDbContext();

            this.PopulateDb(db);
            var articleService = new BlogArticleService(db);

            // Act
            var article = await articleService.ById(2);

            await articleService.UpdateArticleAsync(article.Id, "New Title", article.Content);

            // Assert
            Assert.True(db.Articles.Any(a => a.Id == article.Id && a.Title == "New Title"));
        }
コード例 #20
0
        public async Task AllArticlesShouldReturnCorrectResult()
        {
            // Arrange
            TestStartUp startUp = new TestStartUp();

            TestStartUp.InitializeMapper();
            var db = startUp.GetDbContext();

            this.PopulateDb(db);
            var articleService = new BlogArticleService(db);

            // Act
            var result = await articleService.AllAsync();

            // Assert
            result
            .Should()
            .Match(r => r.ElementAt(0).Id == 4 && r.ElementAt(1).Id == 3 && r.ElementAt(2).Id == 2)
            .And
            .HaveCount(3);
        }
コード例 #21
0
        public async Task GetAsyncShould_ReturnsCorrectArticleModel()
        {
            //Arrange
            var user = UserCreator.Create();

            await this.Db.AddAsync(user);

            var image = ImageInfoCreator.CreateWithFullData(user.Id);

            await this.Db.AddAsync(image);

            var article       = ArticleCreator.Create(user.Id, image.Id);
            var secondArticle = ArticleCreator.Create(user.Id, image.Id);
            var thirdArticle  = ArticleCreator.Create(user.Id, image.Id);

            await this.Db.AddRangeAsync(article, secondArticle, thirdArticle);

            await this.Db.SaveChangesAsync();

            var service = new BlogArticleService(Db, null, null);

            //Act
            var result = await service.GetAsync <ArticleDetailsModel>(secondArticle.Id);

            var secondResult = await service.GetAsync <EditArticleViewModel>(article.Id);

            var thirdResult = await service.GetAsync <EditArticleViewModel>(4589);

            //Assert
            result.Should().BeOfType <ArticleDetailsModel>();
            Assert.Equal(secondArticle.Id, result.Id);

            secondResult.Should().BeOfType <EditArticleViewModel>();
            Assert.Equal(article.Id, secondResult.Id);

            Assert.Null(thirdResult);
        }
コード例 #22
0
 private static async Task <ICompletePost> CreatePost(BlogArticleService bas, CompleteBlogEntry blogOh1)
 {
     return(await bas.Add(blogOh1));
 }
コード例 #23
0
 private static async Task <ICompletePost> UpdatePost(BlogArticleService bas, ICompletePost blogPost)
 {
     return(await bas.Update(blogPost));
 }