Beispiel #1
0
        public async Task GetByAuthor_NotFound()
        {
            var authorKey   = "non_exist_author";
            var reactionKey = "non_exist_reaction";

            var storageMock = new Mock <IReactionStorage>();

            storageMock
            .Setup(s => s.GetReactionByAuthorAsync(reactionKey, authorKey))
            .ReturnsAsync(default(Reaction));

            var client = TestServerHelper.New(collection =>
            {
                collection.AddScoped(_ => storageMock.Object);
            });

            var request = new HttpRequestMessage(HttpMethod.Get, $"reactions/{reactionKey}/author");

            request.Headers.Add("author", authorKey);

            // Act
            var response = await client.SendAsync(request);

            // Assert
            Assert.AreEqual(HttpStatusCode.NotFound, response.StatusCode);
        }
Beispiel #2
0
        public async Task GetByAuthor_Ok()
        {
            // Setup
            var authorKey   = "some_author";
            var reactionKey = "some_reaction";
            var type        = "some_type";

            var reaction = new Reaction(reactionKey, type);

            var storageMock = new Mock <IReactionStorage>();

            storageMock
            .Setup(s => s.GetReactionByAuthorAsync(reactionKey, authorKey))
            .ReturnsAsync(reaction);

            var client = TestServerHelper.New(collection =>
            {
                collection.AddScoped(_ => storageMock.Object);
            });

            var request = new HttpRequestMessage(HttpMethod.Get, $"reactions/{reactionKey}/author");

            request.Headers.Add("author", authorKey);

            // Act
            var response = await client.SendAsync(request);

            var result = JsonConvert.DeserializeObject <Reaction>(await response.Content.ReadAsStringAsync());

            // Assert
            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
            Assert.AreEqual(reaction.Key, result.Key);
            Assert.AreEqual(reaction.Type, result.Type);
        }
Beispiel #3
0
        public async Task Update_NotFound()
        {
            //Setup
            var id = Guid.NewGuid();

            var input = new ProfileUpdateViewModel()
            {
                FirstName   = "Upd",
                LastName    = "Upd",
                Gender      = "Upd",
                DateOfBirth = DateTimeOffset.Now.AddDays(1),
                City        = "Ct"
            };

            var serviceMock = new Mock <IProfileService>();

            serviceMock
            .Setup(x => x.UpdateAsync(id, input.FirstName, input.LastName, input.Gender, input.DateOfBirth, input.City, string.Empty))
            .ReturnsAsync(DomainResult.Error("NotFound"));

            var client = TestServerHelper.New(collection =>
            {
                collection.AddScoped(_ => serviceMock.Object);
            });

            //Act
            var response = await client.PutAsync($"profiles/{id}", input.AsJsonContent());

            //Assert
            Assert.AreEqual(HttpStatusCode.BadRequest, response.StatusCode);
        }
        public async Task Execute_AnyScalarDefaultSerialization_Test()
        {
            // arrange
            using var cts       = new CancellationTokenSource(20_000);
            using IWebHost host = TestServerHelper.CreateServer(
                      builder =>
            {
                builder.AddTypeExtension <QueryResolvers>();
            },
                      out var port);
            var serviceCollection = new ServiceCollection();

            serviceCollection.AddHttpClient(
                AnyScalarDefaultSerializationClient.ClientName,
                c => c.BaseAddress = new Uri("http://localhost:" + port + "/graphql"));
            serviceCollection.AddWebSocketClient(
                AnyScalarDefaultSerializationClient.ClientName,
                c => c.Uri = new Uri("ws://localhost:" + port + "/graphql"));
            serviceCollection.AddAnyScalarDefaultSerializationClient();
            IServiceProvider services = serviceCollection.BuildServiceProvider();
            AnyScalarDefaultSerializationClient client =
                services.GetRequiredService <AnyScalarDefaultSerializationClient>();

            // act
            IOperationResult <IGetJsonResult> result = await client.GetJson.ExecuteAsync(cts.Token);

            // assert
            Assert.Empty(result.Errors);
            result.Data?.Json.RootElement.ToString().MatchSnapshot();
        }
        public void Execute_MultiProfile_Test()
        {
            // arrange
            using IWebHost host = TestServerHelper.CreateServer(
                      _ => { },
                      out var port);
            var serviceCollection = new ServiceCollection();

            serviceCollection.AddHttpClient(
                MultiProfileClient.ClientName,
                c => c.BaseAddress = new Uri("http://localhost:" + port + "/graphql"));
            serviceCollection.AddWebSocketClient(
                MultiProfileClient.ClientName,
                c => c.Uri = new Uri("ws://localhost:" + port + "/graphql"));

            // act
            serviceCollection.AddMultiProfileClient(
                profile: MultiProfileClientProfileKind.Default);

            IServiceProvider   services = serviceCollection.BuildServiceProvider();
            MultiProfileClient client   = services.GetRequiredService <MultiProfileClient>();

            // assert
            Assert.NotNull(client);
        }
        public async Task Publication_NotFound()
        {
            // Setup
            var userId        = Guid.Parse("B4E69138-CE54-444A-8226-2CFABFD352C6");
            var publicationId = Guid.NewGuid().ToString();

            NewsFeedStorageMock
            .Setup(s => s.GetByIdAsync(publicationId))
            .ReturnsAsync(default(NewsFeedPublication));

            CurrentUserProviderMock
            .Setup(s => s.UserId)
            .Returns(userId.ToString());

            var client = TestServerHelper.New(collection =>
            {
                collection.AddAuthentication("Test")
                .AddScheme <AuthenticationSchemeOptions, TestAuthHandler>("Test", _ => { });
                collection.AddScoped(_ => NewsFeedStorageMock.Object);
                collection.AddScoped(_ => CurrentUserProviderMock.Object);
            });

            var input = new CreateNewsFeedPublication {
                Content = "123"
            };

            // Act
            var response = await client.PutAsync($"/newsfeed/{publicationId}", input.AsJsonContent());

            // Assert
            Assert.AreEqual(HttpStatusCode.NotFound, response.StatusCode);
        }
Beispiel #7
0
        public UserControllerFixture()
        {
            // permet d'initialiser
            // - un server web pour le test à partir du fichier startup de l'appli
            // - un accès à la token factory pour mocker un token
            // - un accès à la connection factory pour accéder si besoin directement à la base
            this.ServerHelper = new TestServerHelper()
                                .InitServer()
                                .InitJwtFactory()
                                .InitConnectionFactory();

            // prepare client http
            this.HttpClient = this.ServerHelper.CreateClient();

            // prepare jwttoken
            var id = this.ServerHelper.GenerateClaimsIdentity(1, "nicolas", "*****@*****.**", "nicolas", "delaval");

            this.JwtToken = this.ServerHelper.GenerateEncodedToken("nicolas", id);

            // prepare db
            // purge & création d'un user (pour permettre l'accès à l'api un user doit exister, pour gestion du token auth)
            // on init direct via sql
            IDbConnection connection  = this.ServerHelper.ConnectionFactory.CreateDefaultConnection();
            string        insertQuery = @"TRUNCATE TABLE Users; INSERT INTO Users (UserName, Email, Password, FirstName, LastName) 
                                VALUES(@UserName, @Email, @Password, @FirstName, @LastName);
                                SELECT CAST(SCOPE_IDENTITY() as int)";

            this.MockAdmin.Id = connection.ExecuteScalar <int>(insertQuery, this.MockAdmin);
        }
Beispiel #8
0
        public async Task Create_Created()
        {
            //Setup
            var id = Guid.NewGuid();

            var model = new WorkExperienceCreateViewModel
            {
                CompanyName = "Some",
                Description = "Desc",
                StartWork   = DateTimeOffset.Now,
                FinishWork  = DateTimeOffset.Now.AddDays(1),
                ProfileId   = Guid.NewGuid()
            };

            var serviceMock        = new Mock <IWorkExperienceService>();
            var profileServiceMock = new Mock <IProfileService>();

            serviceMock
            .Setup(x => x.CreateAsync(model.CompanyName, model.Description, model.StartWork, model.FinishWork,
                                      model.ProfileId))
            .ReturnsAsync((DomainResult.Success(), id));

            var client = TestServerHelper.New(collection =>
            {
                collection.AddScoped(_ => serviceMock.Object);
                collection.AddScoped(_ => profileServiceMock.Object);
            });

            //Act
            var response = await client.PostAsync($"/WorkExperiences", model.AsJsonContent());

            //Assert
            Assert.AreEqual(HttpStatusCode.Created, response.StatusCode);
        }
Beispiel #9
0
        public async Task Update_NotFound()
        {
            //Setup
            var id = Guid.NewGuid();

            var model = new WorkExperienceUpdateViewModel
            {
                CompanyName = "Company",
                Description = "Desc",
                StartWork   = DateTimeOffset.Now,
                FinishWork  = DateTimeOffset.Now.AddDays(1)
            };

            var profileServiceMock    = new Mock <IProfileService>();
            var experienceServiceMock = new Mock <IWorkExperienceService>();

            experienceServiceMock
            .Setup(x => x.UpdateAsync(id, model.CompanyName, model.Description, model.StartWork, model.FinishWork))
            .ReturnsAsync(DomainResult.Error("SomeError"));

            var client = TestServerHelper.New(collection =>
            {
                collection.AddScoped(_ => experienceServiceMock.Object);
                collection.AddScoped(_ => profileServiceMock.Object);
            });

            //Act
            var response = await client.PutAsync($"/WorkExperiences/{id}", model.AsJsonContent());

            //Assert
            Assert.AreEqual(HttpStatusCode.BadRequest, response.StatusCode);
        }
        public async Task Execute_StarWarsIntrospection_Test()
        {
            // arrange
            CancellationToken ct = new CancellationTokenSource(20_000).Token;

            using IWebHost host = TestServerHelper.CreateServer(
                      _ => { },
                      out var port);
            var serviceCollection = new ServiceCollection();

            serviceCollection.AddHttpClient(
                StarWarsIntrospectionClient.ClientName,
                c => c.BaseAddress = new Uri("http://localhost:" + port + "/graphql"));
            serviceCollection.AddWebSocketClient(
                StarWarsIntrospectionClient.ClientName,
                c => c.Uri = new Uri("ws://localhost:" + port + "/graphql"));
            serviceCollection.AddStarWarsIntrospectionClient();
            IServiceProvider            services = serviceCollection.BuildServiceProvider();
            StarWarsIntrospectionClient client   = services.GetRequiredService <StarWarsIntrospectionClient>();

            // act
            IOperationResult <IIntrospectionQueryResult> result =
                await client.IntrospectionQuery.ExecuteAsync(ct);

            // assert
            result.MatchSnapshot();
        }
        public async Task DeleteById_NoContent()
        {
            // Setup
            const string commentId     = "someId";
            const string publicationId = "somePublicationId";
            const string author        = "Some Author";

            var comment = new Comment(
                commentId,
                "content",
                DateTimeOffset.Now,
                publicationId,
                null,
                new UserInfo(Guid.Empty, author, null));

            var serviceMock = new Mock <ICommentsService>();

            serviceMock.Setup(s => s.GetByIdAsync(commentId)).ReturnsAsync(comment);

            var client = TestServerHelper.New(collection =>
            {
                collection.AddScoped(_ => serviceMock.Object);
            });

            // Act
            var response = await client.DeleteAsync($"/comments/{commentId}");

            // Assert
            Assert.AreEqual(response.StatusCode, HttpStatusCode.NoContent);
        }
        public async Task User_Not_Found()
        {
            // Setup
            var userId = Guid.NewGuid();

            var usersStorageMock = new Mock<IUsersStorage>();
            usersStorageMock
                .Setup(s => s.GetByIdAsync(userId))
                .ReturnsAsync(default(User));

            var currentUserProviderMock = new Mock<ICurrentUserProvider>();
            currentUserProviderMock
                .Setup(s => s.UserId)
                .Returns(userId.ToString());

            var client = TestServerHelper.New(collection =>
            {
                collection.AddAuthentication("Test")
                    .AddScheme<AuthenticationSchemeOptions, TestAuthHandler>("Test", _ => { });
                collection.AddScoped(_ => usersStorageMock.Object);
                collection.AddScoped(_ => currentUserProviderMock.Object);
            });

            // Act
            var response = await client.PutAsync($"/users/{userId}", new UpdateUserInput().AsJsonContent());

            // Assert
            Assert.AreEqual(HttpStatusCode.NotFound, response.StatusCode);
        }
Beispiel #13
0
        public async Task DeleteByKey_Ok()
        {
            // Setup
            var key = "key1";

            var stats = new Dictionary <string, int>
            {
                ["key2"] = 1
            };

            var storageMock = new Mock <IReactionStorage>();

            storageMock
            .Setup(s => s.GetStats(key))
            .ReturnsAsync(stats);

            var client = TestServerHelper.New(collection =>
            {
                collection.AddScoped(_ => storageMock.Object);
            });

            // Act
            var response = await client.DeleteAsync($"reactions/{key}");

            var result = await response.Content.DeserializeContent <Dictionary <string, int> >();

            // Assert
            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
            Assert.AreEqual(stats["key2"], result["key2"]);
        }
        public async Task Execute_StarWarsUnionList_Test()
        {
            // arrange
            using var cts = new CancellationTokenSource(20_000);

            using IWebHost host = TestServerHelper.CreateServer(
                      _ => { },
                      out var port);
            var serviceCollection = new ServiceCollection();

            serviceCollection.AddHttpClient(
                StarWarsUnionListClient.ClientName,
                c => c.BaseAddress = new Uri("http://localhost:" + port + "/graphql"));
            serviceCollection.AddWebSocketClient(
                StarWarsUnionListClient.ClientName,
                c => c.Uri = new Uri("ws://localhost:" + port + "/graphql"));
            serviceCollection.AddStarWarsUnionListClient();
            IServiceProvider        services = serviceCollection.BuildServiceProvider();
            StarWarsUnionListClient client   = services.GetRequiredService <StarWarsUnionListClient>();

            // act
            var result = await client.SearchHero.ExecuteAsync(cts.Token);

            // assert
            result.EnsureNoErrors();
            result.Data.MatchSnapshot();
        }
        public async Task Comment_NotFound()
        {
            // Setup
            var userId    = Guid.Parse("B4E69138-CE54-444A-8226-2CFABFD352C6");
            var commentId = Guid.NewGuid().ToString();

            const string content = "New Content";

            NewsFeedCommentsStorageMock
            .Setup(s => s.GetByIdAsync(commentId))
            .ReturnsAsync(default(PublicationComment));

            var client = TestServerHelper.New(collection =>
            {
                collection.AddAuthentication("Test")
                .AddScheme <AuthenticationSchemeOptions, TestAuthHandler>("Test", _ => { });
                collection.AddScoped(_ => NewsFeedStorageMock.Object);
            });

            var input = new UpdateNewsFeedComment {
                Content = content
            };

            // Act
            var response = await client.PutAsync($"/newsfeed/comments/{commentId}", input.AsJsonContent());

            // Assert
            Assert.AreEqual(HttpStatusCode.NotFound, response.StatusCode);
        }
Beispiel #16
0
        public async Task GetByUserId_Ok()
        {
            //Setup
            var userId = Guid.NewGuid();

            var securitySetting = new Profiles.SecuritySettings.SecuritySetting(
                userId,
                new SecuritySettingsSection(Access.Everyone, new List <Guid>()),
                new SecuritySettingsSection(Access.Everyone, new List <Guid>()));

            var serviceMock = new Mock <ISecuritySettingService>();

            serviceMock
            .Setup(x => x.GetByUserIdAsync(userId))
            .ReturnsAsync(securitySetting);

            var client = TestServerHelper.New(collection =>
            {
                collection.AddScoped(_ => serviceMock.Object);
            });

            //Act
            var response = await client.GetAsync($"/profiles/{userId}/security-settings");

            //Assert
            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
        }
Beispiel #17
0
        public async Task Delete_NoContent()
        {
            //Setup
            var id = Guid.NewGuid();

            var serviceMock        = new Mock <IWorkExperienceService>();
            var profileServiceMock = new Mock <IProfileService>();

            serviceMock
            .Setup(x => x.GetByIdAsync(id))
            .ReturnsAsync(new Profiles.WorkExperiences.WorkExperience(id, It.IsAny <string>(), It.IsAny <string>(),
                                                                      DateTimeOffset.Now, DateTimeOffset.Now, Guid.NewGuid()));

            var client = TestServerHelper.New(collection =>
            {
                collection.AddScoped(_ => serviceMock.Object);
                collection.AddScoped(_ => profileServiceMock.Object);
            });

            //Act
            var response = await client.DeleteAsync($"/WorkExperiences/{id}");

            //Assert
            Assert.AreEqual(HttpStatusCode.NoContent, response.StatusCode);
        }
Beispiel #18
0
        public async Task Update_NotFound()
        {
            // Setup
            var id    = "some_id";
            var input = new UpdatePublicationModel
            {
                Content = "some content"
            };

            var serviceMock = new Mock <IPublicationService>();

            serviceMock
            .Setup(s => s.GetByIdAsync(id))
            .ReturnsAsync(default(Publication));

            var client = TestServerHelper.New(collection =>
            {
                collection.AddScoped(provider => serviceMock.Object);
            });

            // Act
            var response = await client.PutAsync($"/publications/{id}/", input.AsJsonContent());

            // Assert
            Assert.AreEqual(HttpStatusCode.NotFound, response.StatusCode);
        }
Beispiel #19
0
        public async Task Execute_StarWarsGetFriends_Test()
        {
            // arrange
            CancellationToken ct = new CancellationTokenSource(20_000).Token;

            using IWebHost host = TestServerHelper.CreateServer(
                      _ => { },
                      out var port);
            var serviceCollection = new ServiceCollection();

            serviceCollection
            .AddStarWarsGetFriendsClient()
            .ConfigureHttpClient(
                c => c.BaseAddress = new Uri("http://localhost:" + port + "/graphql"))
            .ConfigureWebSocketClient(
                c => c.Uri = new Uri("ws://localhost:" + port + "/graphql"));

            IServiceProvider          services = serviceCollection.BuildServiceProvider();
            IStarWarsGetFriendsClient client   =
                services.GetRequiredService <IStarWarsGetFriendsClient>();

            // act
            IOperationResult <IGetHeroResult> result = await client.GetHero.ExecuteAsync(ct);

            // assert
            Assert.Equal("R2-D2", result.Data?.Hero?.Name);
            Assert.Collection(
                result.Data !.Hero !.Friends !.Nodes !,
                item => Assert.Equal("Luke Skywalker", item?.Name),
                item => Assert.Equal("Han Solo", item?.Name),
                item => Assert.Equal("Leia Organa", item?.Name));
        }
Beispiel #20
0
        public async Task Update_NoContent()
        {
            // Setup
            var id    = "some_id";
            var input = new UpdatePublicationModel
            {
                Content = "some content"
            };

            var publication = new Publication(id, input.Content, Enumerable.Empty <string>(), null, DateTimeOffset.Now, DateTimeOffset.Now);

            var serviceMock = new Mock <IPublicationService>();

            serviceMock
            .Setup(s => s.UpdateAsync(id, input.Content))
            .ReturnsAsync(DomainResult.Success());

            serviceMock
            .Setup(s => s.GetByIdAsync(id))
            .ReturnsAsync(publication);

            var client = TestServerHelper.New(collection =>
            {
                collection.AddScoped(provider => serviceMock.Object);
            });

            // Act
            var response = await client.PutAsync($"/publications/{id}/", input.AsJsonContent());

            // Assert
            Assert.AreEqual(HttpStatusCode.NoContent, response.StatusCode);
        }
Beispiel #21
0
        public async Task SearchByIds_Ok()
        {
            //Setup
            var model = new ProfilesQueryModel()
            {
                Ids = new List <Guid>()
            };

            var serviceMock = new Mock <IProfileService>();

            serviceMock
            .Setup(x => x.SearchByIdsAsync(model.Ids))
            .ReturnsAsync(new List <Profiles.Profile>());

            var client = TestServerHelper.New(collection =>
            {
                collection.AddScoped(_ => serviceMock.Object);
            });

            //Act
            var response = await client.PostAsync($"profiles/search", model.AsJsonContent());

            //Assert
            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
        }
Beispiel #22
0
        public async Task Update_NotFound()
        {
            // Setup
            const string commentId = "someId";
            var          model     = new UpdateCommentModel
            {
                Content = "New Content"
            };

            DomainResult domainResult = DomainResult.Success();

            var serviceMock = new Mock <ICommentsService>();

            serviceMock.Setup(s => s.UpdateAsync(commentId, model.Content)).ReturnsAsync(domainResult);
            serviceMock.Setup(s => s.GetByIdAsync(commentId)).ReturnsAsync(default(Comment));

            var client = TestServerHelper.New(collection =>
            {
                collection.AddScoped(_ => serviceMock.Object);
            });

            // Act
            var response = await client.PutAsync($"comments/{commentId}", model.AsJsonContent());

            Assert.AreEqual(response.StatusCode, HttpStatusCode.NotFound);
        }
        public async Task Forbidden_Update_Other_Users()
        {
            // Setup
            var userId = Guid.Parse("B4E69138-CE54-444A-8226-2CFABFD352C6");
            var currentUserId = Guid.Parse("B4E69138-CE54-444A-8226-2CFABFD352C7");

            var usersStorageMock = new Mock<IUsersStorage>();
            var currentUserProviderMock = new Mock<ICurrentUserProvider>();
            currentUserProviderMock
                .Setup(s => s.UserId)
                .Returns(currentUserId.ToString());

            var client = TestServerHelper.New(collection =>
            {
                collection.AddAuthentication("Test")
                    .AddScheme<AuthenticationSchemeOptions, TestAuthHandler>("Test", _ => { });
                collection.AddScoped(_ => usersStorageMock.Object);
                collection.AddScoped(_ => currentUserProviderMock.Object);
            });

            // Act
            var response = await client.PutAsync($"/users/{userId}", new UpdateUserInput().AsJsonContent());

            // Assert
            Assert.AreEqual(HttpStatusCode.Forbidden, response.StatusCode);
        }
Beispiel #24
0
        public async Task DeleteByAuthor_NotFound()
        {
            // Setup
            var key    = "key1";
            var author = "some_author";

            var reactions = new Dictionary <string, int>();

            var storageMock = new Mock <IReactionStorage>();

            storageMock
            .Setup(s => s.GetStats(key))
            .ReturnsAsync(reactions);

            var client = TestServerHelper.New(collection =>
            {
                collection.AddScoped(_ => storageMock.Object);
            });

            var request = new HttpRequestMessage(HttpMethod.Delete, $"reactions/{key}/author");

            request.Headers.Add("author", author);

            // Act
            var response = await client.SendAsync(request);

            // Assert
            Assert.AreEqual(HttpStatusCode.NotFound, response.StatusCode);
        }
Beispiel #25
0
        public async Task SearchFeatured_Ok()
        {
            // Setup
            const string firstPublicationId  = "firstId";
            const string secondPublicationId = "secondId";

            int commentId = 1;

            var author = new UserInfo(Guid.NewGuid(), "SomeName", null);

            var featuredComments = new Dictionary <string, FeaturedInfo>()
            {
                {
                    firstPublicationId, new FeaturedInfo(
                        new Comment[]
                    {
                        new Comment((commentId++).ToString(), "someContent1", DateTimeOffset.Now, firstPublicationId, null, author),
                        new Comment((commentId++).ToString(), "someContent2", DateTimeOffset.Now, firstPublicationId, null, author),
                    }, 2)
                },
                {
                    secondPublicationId, new FeaturedInfo(
                        new Comment[]
                    {
                        new Comment((commentId++).ToString(), "someContent1", DateTimeOffset.Now, secondPublicationId, null, author),
                        new Comment((commentId++).ToString(), "someContent2", DateTimeOffset.Now, secondPublicationId, null, author),
                    }, 2)
                }
            };

            var model = new FeaturedQuery()
            {
                Keys = new string[] { firstPublicationId, secondPublicationId }
            };

            var serviceMock = new Mock <ICommentsService>();

            serviceMock
            .Setup(s => s.SearchFeaturedAsync(new string[] { firstPublicationId, secondPublicationId }))
            .ReturnsAsync(featuredComments);

            var client = TestServerHelper.New(collection =>
            {
                collection.AddScoped(_ => serviceMock.Object);
            });

            // Act
            var response = await client.PostAsync("Comments/comments/featured", model.AsJsonContent());

            var result = await response.Content.DeserializeContent <Dictionary <string, FeaturedInfo> >();

            // Assert
            Assert.AreEqual(response.StatusCode, HttpStatusCode.OK);

            Assert.IsTrue(result.Count == 2);
            Assert.IsTrue(result[firstPublicationId].Comments.Count() == 2);
            Assert.IsTrue(result[secondPublicationId].Comments.Count() == 2);
        }
        private async Task <(HttpStatusCode status, string content)> PostDocAsync(Document document)
        {
            var jsonContent = JsonConvert.SerializeObject(document);

            using (var client = TestServerHelper.CreateClient())
                using (var response = await client.PostAsync("api/docs", new StringContent(jsonContent, Encoding.UTF8, "application/json")))
                {
                    return(response.StatusCode, await response.Content.ReadAsStringAsync());
                }
        }
        public async Task Comment_BadRequest()
        {
            // Setup
            var userId        = Guid.Parse("B4E69138-CE54-444A-8226-2CFABFD352C6");
            var publicationId = Guid.NewGuid().ToString();
            var commentId     = Guid.NewGuid().ToString();

            const string oldContent = "Old Content";
            string       newContent = string.Empty;

            NewsFeedCommentsStorageMock
            .Setup(s => s.GetByIdAsync(commentId))
            .ReturnsAsync(
                new PublicationComment(
                    commentId,
                    oldContent,
                    publicationId,
                    new UserInfo(userId, string.Empty, null),
                    DateTimeOffset.Now));

            NewsFeedCommentsStorageMock
            .Setup(s => s.UpdateAsync(commentId, newContent))
            .ThrowsAsync(new ApiException {
                ErrorCode = (int)HttpStatusCode.BadRequest
            });

            CurrentUserProviderMock
            .Setup(s => s.UserId)
            .Returns(userId.ToString());

            var client = TestServerHelper.New(collection =>
            {
                collection.AddAuthentication("Test")
                .AddScheme <AuthenticationSchemeOptions, TestAuthHandler>("Test", _ => { });
                collection.AddScoped(_ => NewsFeedStorageMock.Object);
                collection.AddScoped(_ => CurrentUserProviderMock.Object);
            });

            var input = new UpdateNewsFeedComment {
                Content = newContent
            };

            // Act
            var response = await client.PutAsync($"/newsfeed/comments/{commentId}", input.AsJsonContent());

            // Assert
            Assert.AreEqual(HttpStatusCode.BadRequest, response.StatusCode);
        }
Beispiel #28
0
        public async Task Create_Ok()
        {
            // Setup
            const string commentId     = "commentId";
            const string publicationId = "publicationId";
            const string content       = "asd";
            const string authorId      = "3fa85f64-5717-4562-b3fc-2c963f66afa7";

            var author = new UserInfo(new Guid(authorId), "FName LName", null);

            var model = new CreateCommentModel()
            {
                Key            = publicationId,
                Content        = content,
                ReplyCommentId = null,
                AuthorId       = authorId
            };

            var commentServiceMock = new Mock <ICommentsService>();

            commentServiceMock
            .Setup(s => s.CreateAsync(publicationId, content, null, author))
            .ReturnsAsync((DomainResult.Success(), "commentId"));

            commentServiceMock
            .Setup(s => s.GetByIdAsync(commentId))
            .ReturnsAsync(new Comment(commentId, content, DateTimeOffset.Now, publicationId, null, author));

            var userProvideMock = new Mock <IUserProvider>();

            userProvideMock
            .Setup(s => s.GetByIdAsync(model.AuthorId))
            .ReturnsAsync(author);

            var client = TestServerHelper.New(collection =>
            {
                collection.AddScoped(_ => commentServiceMock.Object);
                collection.AddScoped(_ => userProvideMock.Object);
            });

            // Act
            var response = await client.PostAsync("comments", model.AsJsonContent());

            // Asser
            Assert.AreEqual(response.StatusCode, HttpStatusCode.Created);
        }
Beispiel #29
0
        public async Task GetById_NotFound()
        {
            // Setup
            const string commentId = "someId";

            var    serviceMock = new Mock <ICommentsService>();
            object p           = serviceMock.Setup(s => s.GetByIdAsync(commentId)).ReturnsAsync(default(Comment));

            var client = TestServerHelper.New(collection =>
            {
                collection.AddScoped(_ => serviceMock.Object);
            });

            // Act
            var response = await client.GetAsync($"/comments/{commentId}");

            // Assert
            Assert.AreEqual(response.StatusCode, HttpStatusCode.NotFound);
        }
Beispiel #30
0
        public async Task Watch_CacheFirst_StarWarsGetHero_Test()
        {
            // arrange
            CancellationToken ct = new CancellationTokenSource(20_000).Token;

            using IWebHost host = TestServerHelper.CreateServer(
                      _ => { },
                      out var port);
            var serviceCollection = new ServiceCollection();

            serviceCollection.AddStarWarsGetHeroClient()
            .ConfigureHttpClient(
                c => c.BaseAddress = new Uri("http://localhost:" + port + "/graphql"))
            .ConfigureWebSocketClient(
                c => c.Uri = new Uri("ws://localhost:" + port + "/graphql"));

            IServiceProvider      services = serviceCollection.BuildServiceProvider();
            StarWarsGetHeroClient client   = services.GetRequiredService <StarWarsGetHeroClient>();

            // act
            await client.GetHero.ExecuteAsync(ct);

            string?     name    = null;
            IDisposable session =
                client.GetHero
                .Watch(ExecutionStrategy.CacheFirst)
                .Subscribe(result =>
            {
                name = result.Data?.Hero?.Name;
            });

            while (name is null && !ct.IsCancellationRequested)
            {
                await Task.Delay(10, ct);
            }

            session.Dispose();

            // assert
            Assert.Equal("R2-D2", name);
        }