Esempio n. 1
0
        public async Task ReturnsResponseContent()
        {
            //Arrange
            var mockHandler = new Mock <HttpMessageHandlerWrapper> {
                CallBase = true
            };
            var httpClient = new HttpClient(mockHandler.Object);
            var url        = "http://test";
            var expectedResponseContent = "{}";

            var graphQlClient = new GraphQLClient(httpClient, url);

            mockHandler
            .Setup(mock => mock.Send(It.IsAny <HttpRequestMessage>()))
            .Returns(new HttpResponseMessage
            {
                Content = new StringContent(expectedResponseContent)
            });

            //Act
            var responseContent = await graphQlClient.QueryAsync("query", new { x = 1, y = 2 });

            //Assert
            responseContent.Should().Be(expectedResponseContent);
        }
Esempio n. 2
0
        public async Task <IEntity> GraphqlConexionEntity(string query, object variable, bool requiredToken)
        {
            try
            {
                var GraphQLApiUrl = Environment.GetEnvironmentVariable("GRAPHQL_URI");

                // These are added on each request so you can safely use an HttpClient instance that is
                // shared across your application
                var requestHeaders = new NameValueCollection();
                if (!requiredToken)
                {
                    var JWToken = _identityHelper.GetCurrentToken();
                    requestHeaders.Add("Authorization", $"Bearer {JWToken}");
                }

                IGraphQLClient graphQLClient = new GraphQLClient(new HttpClient(), GraphQLApiUrl, requestHeaders);
                IEntity        repository    = await graphQLClient.QueryAsync <IEntity>(query, variable);

                return(repository);
            }
            catch (Exception ex)
            {
                return(null);
            }
        }
Esempio n. 3
0
        public async Task SendRequestsWithProperQueryAndVariablesContent()
        {
            //Arrange
            var mockHandler = new Mock <HttpMessageHandlerWrapper> {
                CallBase = true
            };
            var httpClient    = new HttpClient(mockHandler.Object);
            var url           = "http://test";
            var graphQlClient = new GraphQLClient(httpClient, url);

            mockHandler
            .Setup(mock => mock.Send(It.IsAny <HttpRequestMessage>()))
            .Returns(new HttpResponseMessage());

            var query                 = "QUERY";
            var varibles              = new { var1 = "test1", var2 = "test2" };
            var expectedJsonContent   = "{\"query\":\"QUERY\",\"variables\":{\"var1\":\"test1\",\"var2\":\"test2\"}}";
            var expectedStringContent = new StringContent(string.Empty, Encoding.UTF8, "application/json");


            //Act
            await graphQlClient.QueryAsync(query, varibles);

            //Assert
            mockHandler
            .Verify(mock => mock.Send(It.Is <HttpRequestMessage>(value => TestHelpers.AreEqual(value.Content, expectedStringContent))));

            mockHandler
            .Verify(mock => mock.Send(It.Is <HttpRequestMessage>(value => TestHelpers.AreEqual(value.Content.ReadAsStringAsync().Result, expectedJsonContent))));
        }
Esempio n. 4
0
        public async Task SendsRequestWithVariblesAndDeserialzesSimpleRepsonse()
        {
            //Arrange
            var mockHandler = new Mock <HttpMessageHandlerWrapper> {
                CallBase = true
            };
            var httpClient   = new HttpClient(mockHandler.Object);
            var url          = "http://test";
            var returnString = "{data : { testDto : { property1: \"value1\", property2 : \"value2\"}}}";

            var graphQlClient = new GraphQLClient(httpClient, url);

            mockHandler
            .Setup(mock => mock.Send(It.IsAny <HttpRequestMessage>()))
            .Returns(new HttpResponseMessage
            {
                Content = new StringContent(returnString)
            });

            var expectedTestDTO = new TestDTO
            {
                Property1 = "value1",
                Property2 = "value2"
            };

            //Act
            var resposneTestDTO = await graphQlClient.QueryAsync <TestDTO>(null, new { varible1 = "value" });

            //Assert
            resposneTestDTO.ShouldBeEquivalentTo(expectedTestDTO);
        }
Esempio n. 5
0
        public async Task GetAllCountries()
        {
            var query          = @"{
	                        Country{
                            _id
                            name
                          }
                        }";
            var responseObject = await GraphQLClient.QueryAsync(query);

            Assert.IsNull(responseObject.GetException());
            var countryList = responseObject.GetParsedData <CountryList>();

            Assert.IsTrue(countryList.Country.Count == 250);
        }
Esempio n. 6
0
        public async Task HandlesRequestError()
        {
            //Arrange
            var mockHandler = new Mock <HttpMessageHandlerWrapper> {
                CallBase = true
            };
            var httpClient   = new HttpClient(mockHandler.Object);
            var url          = "http://test";
            var returnString = "{data : null, errors : [{message : \"errorMessage1\"}, {message: \"errorMessage2\"}]}";

            var graphQlClient = new GraphQLClient(httpClient, url);

            var headerToReturn = new KeyValuePair <string, string>("X-SomeCustomHeader", "SomeCustomerHeaderValue");

            var responseMessageToReturn = new HttpResponseMessage();

            responseMessageToReturn.Headers.Add(headerToReturn.Key, headerToReturn.Value);
            responseMessageToReturn.StatusCode = HttpStatusCode.InternalServerError;
            responseMessageToReturn.Content    = new StringContent(returnString);

            mockHandler
            .Setup(mock => mock.Send(It.IsAny <HttpRequestMessage>()))
            .Returns(responseMessageToReturn);

            var expectedTestDTO = new TestDTO
            {
                Property1 = "value1",
                Property2 = "value2"
            };

            GraphQLRequestException expectedException = null;

            //Act
            try
            {
                await graphQlClient.QueryAsync(null);
            }
            catch (GraphQLRequestException ex)
            {
                expectedException = ex;
            }

            //Assert
            expectedException.Should().NotBeNull();
            expectedException.Message.Should().Be("Request failed with status code of InternalServerError");
            expectedException.ResponseBody.Should().Be(returnString);
            expectedException.ResponseHeaders.GetValues(headerToReturn.Key).FirstOrDefault().Should().Be(headerToReturn.Value);
        }
Esempio n. 7
0
        public async Task GetOneCountry()
        {
            var query          = @"query($id:String) {
	                        Country(_id:$id) {
                            _id
                            name
                          }
                        }";
            var variables      = new { id = "51" };
            var responseObject = await GraphQLClient.QueryAsync(query, variables);

            Assert.IsNull(responseObject.GetException());
            var countryList = responseObject.GetParsedData <CountryList>();

            Assert.AreEqual(countryList.Country.Count, 1);
        }
        public async Task GenerateBewitForUrlOnHotChocolate_ValidateOnMvc_ShouldAccept()
        {
            //Arrange MVC Server
            string secret = "4r8FfT!$p0Ortz";

            IMongoDatabase database = _mongoResource.CreateDatabase();
            TestServer     hcServer = HCServerHelper.CreateHotChocolateServer(
                secret,
                _mongoResource.ConnectionString,
                database.DatabaseNamespace.DatabaseName);

            HttpClient    hcClient    = hcServer.CreateClient();
            GraphQLClient gqlHcClient = new GraphQLClient(hcClient);
            QueryRequest  query       = new QueryRequest(
                string.Empty,
                @"mutation giveMeAccess {
                    RequestAccess: RequestAccessUrl
                }",
                "giveMeAccess",
                new Dictionary <string, object>());

            TestServer mvcServer = MvcServerHelper.CreateMvcServer(
                secret,
                _mongoResource.ConnectionString,
                database.DatabaseNamespace.DatabaseName);
            HttpClient mvcClient = mvcServer.CreateClient();

            //Act
            /* 1. Get Url from HotChocolate */
            QueryResponse <GiveMeAccessResult> requireAccessResult =
                await gqlHcClient.QueryAsync <GiveMeAccessResult>(query,
                                                                  CancellationToken.None);

            /* 2. Invoke this url on the MvcServer */
            HttpResponseMessage mvcResponse = await mvcClient.GetAsync(
                requireAccessResult.Data.RequestAccess,
                CancellationToken.None);

            //Assert
            mvcResponse.StatusCode.Should().Be(HttpStatusCode.OK);
            string content = await mvcResponse.Content.ReadAsStringAsync();

            content.Should().Be("bar");
        }
Esempio n. 9
0
        public async Task SendRequestsUsingPost()
        {
            //Arrange
            var mockHandler = new Mock <HttpMessageHandlerWrapper> {
                CallBase = true
            };
            var httpClient    = new HttpClient(mockHandler.Object);
            var url           = "http://test";
            var graphQlClient = new GraphQLClient(httpClient, url);

            mockHandler
            .Setup(mock => mock.Send(It.IsAny <HttpRequestMessage>()))
            .Returns(new HttpResponseMessage());

            //Act
            await graphQlClient.QueryAsync("query", new { x = 1, y = 2 });

            //Assert
            mockHandler
            .Verify(mock => mock.Send(It.Is <HttpRequestMessage>(value => value.Method == HttpMethod.Post)));
        }
Esempio n. 10
0
        public async Task SendRequestsWithProvidedHeaders()
        {
            //Arrange
            var mockHandler = new Mock <HttpMessageHandlerWrapper> {
                CallBase = true
            };
            var httpClient = new HttpClient(mockHandler.Object);
            var url        = "http://test";


            var headerDictionary = new Dictionary <string, IEnumerable <string> >();

            headerDictionary.Add("X-Header1", new List <string> {
                "Header1Value"
            });
            headerDictionary.Add("Authorization", new List <string> {
                "Bearer 324234234"
            });

            var requestHeaders = new NameValueCollection();

            foreach (var headerKvp in headerDictionary)
            {
                requestHeaders.Add(headerKvp.Key, headerKvp.Value.First());
            }

            var graphQlClient = new GraphQLClient(httpClient, url, requestHeaders);

            mockHandler
            .Setup(mock => mock.Send(It.IsAny <HttpRequestMessage>()))
            .Returns(new HttpResponseMessage());

            //Act
            await graphQlClient.QueryAsync("query", new { x = 1, y = 2 });

            //Assert
            mockHandler
            .Verify(mock => mock.Send(It.Is <HttpRequestMessage>(value => TestHelpers.AreEqual(value.Headers.ToList(), headerDictionary.ToList()))));
        }
Esempio n. 11
0
        public async Task <string> GraphqlConexionString(string query, bool requiredToken)
        {
            try
            {
                var GraphQLApiUrl = Environment.GetEnvironmentVariable("GRAPHQL_URI");

                var requestHeaders = new NameValueCollection();
                if (!requiredToken)
                {
                    var JWToken = _identityHelper.GetCurrentToken();
                    requestHeaders.Add("Authorization", $"Bearer {JWToken}");
                }

                IGraphQLClient graphQLClient      = new GraphQLClient(new HttpClient(), GraphQLApiUrl, requestHeaders);
                var            responseBodySTring = await graphQLClient.QueryAsync(query);

                return(responseBodySTring);
            }
            catch (Exception)
            {
                return(null);
            }
        }
Esempio n. 12
0
        public async Task GetCountryInvalidQuery()
        {
            var query     = @"query($id:String){
                          Country{
                            name}
                          Timezone{
                            _id
                            countries(_id:$id)
                          }
                        }";
            var variables = new { id = "51" };

            try
            {
                var responseObject = await GraphQLClient.QueryAsync(query, variables);

                var countryList = responseObject.GetParsedData <CountryList>();
            }
            catch (GraphQLException ex)
            {
                //ReportEvent.Fail(Constants.currentTest, "Bad Response from Server: " + ex.StatusCode);
                ReportHelper.LogFail(currentTest, "Exception Occured: Message: " + ex.Error.ToString());
            }
        }
Esempio n. 13
0
        public async Task SendsRequestAndDeserialesRepsonseWithEdges()
        {
            //Arrange
            var mockHandler = new Mock <HttpMessageHandlerWrapper> {
                CallBase = true
            };
            var httpClient   = new HttpClient(mockHandler.Object);
            var url          = "http://test";
            var returnString = @"
            {
              ""data"": {
                ""organization"": {
                  ""teams"": {
                    ""nodes"": [
                      {
                        ""name"": ""Team1"",
                        ""repositoryEdges"": {
                          ""edges"": [
                            {
                              ""permission"": ""WRITE"",
                              ""repository"": {
                                ""name"": ""Repo1""
                              }
                            }
                          ]
                        }
                      },
                      {
                        ""name"": ""Team2"",
                        ""repositoryEdges"": {
                          ""edges"": [
                            {
                              ""permission"": ""ADMIN"",
                              ""repository"": {
                                ""name"": ""Repo2""
                              }
                            }
                          ]
                        }
                      }
                    ],
                    ""pageInfo"": {
                        ""hasNextPage"": true,
                        ""hasPreviousPage"": true,
                        ""endCursor"": ""ImDaEndCursor"",
                        ""startCursor"": ""ImDaStartCursor""
                    }
                  }
                }
              }
            }
            ";

            var graphQlClient = new GraphQLClient(httpClient, url);

            mockHandler
            .Setup(mock => mock.Send(It.IsAny <HttpRequestMessage>()))
            .Returns(new HttpResponseMessage
            {
                Content = new StringContent(returnString)
            });

            var expectedOrganization = new Organization
            {
                Teams = new GraphQlNodesParent <Team>
                {
                    Nodes = new List <Team>
                    {
                        new Team
                        {
                            Name            = "Team1",
                            RepositoryEdges = new GraphQLEdgesParent <TeamToRepositoryEdge>
                            {
                                Edges = new List <TeamToRepositoryEdge>
                                {
                                    new TeamToRepositoryEdge
                                    {
                                        Permission = "WRITE",
                                        Repository = new Repository
                                        {
                                            Name = "Repo1"
                                        }
                                    }
                                }
                            }
                        },
                        new Team
                        {
                            Name            = "Team2",
                            RepositoryEdges = new GraphQLEdgesParent <TeamToRepositoryEdge>
                            {
                                Edges = new List <TeamToRepositoryEdge>
                                {
                                    new TeamToRepositoryEdge
                                    {
                                        Permission = "ADMIN",
                                        Repository = new Repository
                                        {
                                            Name = "Repo2"
                                        }
                                    }
                                }
                            }
                        }
                    },
                    PageInfo = new GraphQlPageInfo
                    {
                        HasNextPage     = true,
                        HasPreviousPage = true,
                        EndCursor       = "ImDaEndCursor",
                        StartCursor     = "ImDaStartCursor"
                    }
                }
            };

            //Act
            var responseOrganization = await graphQlClient.QueryAsync <Organization>(null);

            //Assert
            responseOrganization.ShouldBeEquivalentTo(expectedOrganization);
        }
Esempio n. 14
0
        public async Task SendsRequestAndDeserialesRepsonseWithNodes()
        {
            //Arrange
            var mockHandler = new Mock <HttpMessageHandlerWrapper> {
                CallBase = true
            };
            var httpClient   = new HttpClient(mockHandler.Object);
            var url          = "http://test";
            var returnString = @"
            {
              ""data"": {
                ""organization"": {
                  ""repository"": {
                    ""pullRequests"": {
                      ""nodes"": [
                        {
                          ""baseRefName"": ""master"",
                          ""headRefName"": ""development"",
                          ""reviews"": {
                            ""totalCount"": 100,
                            ""nodes"": [
                              {
                                ""state"": ""APPROVED"",
                                ""author"": {
                                  ""login"": ""bob""
                                }
                              }
                            ],
                            ""pageInfo"": {
                              ""hasNextPage"": true,
                              ""hasPreviousPage"": true,
                              ""endCursor"": ""ImDaEndCursor"",
                              ""startCursor"": ""ImDaStartCursor""
                            }
                          }
                        }
                      ]
                    }
                  }
                }
              }
            }
            ";

            var graphQlClient = new GraphQLClient(httpClient, url);

            mockHandler
            .Setup(mock => mock.Send(It.IsAny <HttpRequestMessage>()))
            .Returns(new HttpResponseMessage
            {
                Content = new StringContent(returnString)
            });

            var expectedOrganization = new Organization
            {
                Repository = new Repository
                {
                    PullRequests = new GraphQlNodesParent <PullRequest>
                    {
                        Nodes = new List <PullRequest>
                        {
                            new PullRequest
                            {
                                BaseRefName = "master",
                                HeadRefName = "development",
                                Reviews     = new GraphQlNodesParent <Review>
                                {
                                    TotalCount = 100,
                                    Nodes      = new List <Review>
                                    {
                                        new Review
                                        {
                                            State  = "APPROVED",
                                            Author = new Author
                                            {
                                                Login = "******"
                                            }
                                        }
                                    },
                                    PageInfo = new GraphQlPageInfo
                                    {
                                        HasNextPage     = true,
                                        HasPreviousPage = true,
                                        EndCursor       = "ImDaEndCursor",
                                        StartCursor     = "ImDaStartCursor"
                                    }
                                }
                            }
                        }
                    }
                }
            };

            //Act
            var responseOrganization = await graphQlClient.QueryAsync <Organization>(null);

            //Assert
            responseOrganization.ShouldBeEquivalentTo(expectedOrganization);
        }
Esempio n. 15
0
 /// <summary>
 /// Asynchronously searches and returns the first anime
 /// </summary>
 /// <param name="name">The name of the anime</param>
 /// <returns>The first anime or null if nothing found.</returns>
 public async Task <IMedia> GetMediaAsync(string name, params MediaFormat[] filter)
 => (await graph.QueryAsync <MediaQuery>("query($p0: String, $p1: [MediaFormat]) { Media(search: $p0, format_not_in: $p1) { averageScore, coverImage { large }, title { romaji english native userPreferred }, description, duration, status, episodes, siteUrl, status, genres } }",
                                         new GraphQLParameter(name),
                                         new GraphQLParameter(filter, "[MediaFormat]")))?.Media ?? null;
Esempio n. 16
0
 public async Task <TResult> ExecuteAsync <TResult>(params ValueTuple <string, object>[] parameters)
 => await _client.QueryAsync <TResult>(_rawQuery, parameters);