示例#1
0
        public async Task <HttpResponseMessage> SendAsync(
            HttpRequestMessage request,
            CancellationToken cancellationToken)
        {
            PreProcess(request, cancellationToken);
            HttpResponseMessage response =
                await ProduceResultAsync(request, cancellationToken).ConfigureAwait(false);

            // Pass it along down the line if we didn't create a result already.
            if (null == response)
            {
                if (DeferToDefault)
                {
                    response = await DefaultAsync(request, cancellationToken).ConfigureAwait(false);
                }
                else
                {
                    // Create a dummy successful response so HttpClient doesn't just throw always.
                    response = await HttpTests.CreateJsonStringResponseAsync(new { dummy = "" })
                               .ConfigureAwait(false);
                }
            }

            PostProcess(request, response);

            return(response);
        }
示例#2
0
        FuncHandler CreateQueryRequestHandler(QueryParameters queryParameters, object response)
        {
            // Create a NameValueCollection with all expected query string parameters
            var expectedQueryStringCollection = new NameValueCollection();

            foreach (var parameter in queryParameters.GetQueryParameters())
            {
                if (null != parameter.Value)
                {
                    expectedQueryStringCollection[parameter.Key] = parameter.Value;
                }
            }

            return(new FuncHandler()
            {
                ProduceResultAsync = (request, ct) =>
                {
                    var expectedPath =
                        $"{HttpTests.GetUriForResource(SettingsEnv, KeenConstants.QueriesResource)}/" +
                        $"{queryParameters.GetResourceName()}";

                    string actualPath =
                        $"{request.RequestUri.Scheme}{Uri.SchemeDelimiter}" +
                        $"{request.RequestUri.Authority}{request.RequestUri.AbsolutePath}";

                    Assert.AreEqual(expectedPath, actualPath);

                    var actualQueryStringCollection = HttpUtility.ParseQueryString(request.RequestUri.Query);

                    Assert.That(actualQueryStringCollection, Is.EquivalentTo(expectedQueryStringCollection));

                    return HttpTests.CreateJsonStringResponseAsync(response);
                }
            });
        }
示例#3
0
        public async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            HttpResponseMessage response = null;
            IHttpMessageHandler handler  = null;

            // First check for a perfect match, or if there's a key that's a base url of the request
            // url, match it if client code chooses to accept that.
            if (_urlsToHandlers.TryGetValue(request.RequestUri, out handler) ||
                (MatchBaseUrls && null != (handler = _urlsToHandlers.FirstOrDefault(
                                               entry => entry.Key.IsBaseOf(request.RequestUri)).Value)))
            {
                response =
                    await handler.SendAsync(request, cancellationToken).ConfigureAwait(false);
            }
            else if (DeferToDefault)
            {
                response = await DefaultAsync(request, cancellationToken).ConfigureAwait(false);
            }
            else
            {
                Console.WriteLine(string.Format("WARNING: No validator found for absolute URI: {0}",
                                                request.RequestUri.AbsoluteUri));

                // No handler found, so return 404
                response = await HttpTests.CreateJsonStringResponseAsync(
                    HttpStatusCode.NotFound, "Resource not found.", "ResourceNotFoundError")
                           .ConfigureAwait(false);
            }

            return(response);
        }
示例#4
0
        public async Task QueryFilter_NotContains_Success()
        {
            var queriesUrl = HttpTests.GetUriForResource(SettingsEnv,
                                                         KeenConstants.QueriesResource);

            var handler = new FuncHandler()
            {
                PreProcess = (req, ct) =>
                {
                    var queryStr = req.RequestUri.Query;

                    // Make sure our filter properties are in the query string
                    Assert.IsTrue(queryStr.Contains("propertyName") &&
                                  queryStr.Contains("four") &&
                                  queryStr.Contains(QueryFilter.FilterOperator.NotContains()));
                },
                ProduceResultAsync = (req, ct) =>
                {
                    return(HttpTests.CreateJsonStringResponseAsync(new { result = 2 }));
                },
                DeferToDefault = false
            };

            // NOTE : This example shows use of UrlToMessageHandler, but since we only make one
            // request to a single endpoint, we could just directly use the FuncHandler here.
            var urlHandler = new UrlToMessageHandler(
                new Dictionary <Uri, IHttpMessageHandler>
            {
                { queriesUrl, handler }
            })
            {
                DeferToDefault = false
            };

            var client = new KeenClient(SettingsEnv, new TestKeenHttpClientProvider()
            {
                ProvideKeenHttpClient =
                    (url) => KeenHttpClientFactory.Create(url,
                                                          new HttpClientCache(),
                                                          null,
                                                          new DelegatingHandlerMock(urlHandler))
            });

            var filters = new List <QueryFilter>
            {
                new QueryFilter("propertyName", QueryFilter.FilterOperator.NotContains(), "four")
            };

            var count = await client.QueryAsync(
                QueryType.Count(),
                "testCollection",
                "",
                QueryRelativeTimeframe.ThisMonth(),
                filters);

            Assert.IsNotNull(count);
            Assert.AreEqual("2", count);
        }
示例#5
0
        public async Task QueryFilter_NullPropertyValue_Success()
        {
            // TODO : Consolidate this FuncHandler/KeenClient setup into a helper method.

            var handler = new FuncHandler()
            {
                PreProcess = (req, ct) =>
                {
                    var queryStr = req.RequestUri.Query;

                    // Make sure our filter properties are in the query string
                    Assert.IsTrue(queryStr.Contains("propertyName") &&
                                  queryStr.Contains("null") &&
                                  queryStr.Contains(QueryFilter.FilterOperator.Equals()));
                },
                ProduceResultAsync = (req, ct) =>
                {
                    return(HttpTests.CreateJsonStringResponseAsync(new { result = 2 }));
                },
                DeferToDefault = false
            };

            var client = new KeenClient(SettingsEnv, new TestKeenHttpClientProvider()
            {
                ProvideKeenHttpClient =
                    (url) => KeenHttpClientFactory.Create(url,
                                                          new HttpClientCache(),
                                                          null,
                                                          new DelegatingHandlerMock(handler))
            });

            var filters = new List <QueryFilter>
            {
                new QueryFilter("propertyName", QueryFilter.FilterOperator.Equals(), null)
            };

            var count = await client.QueryAsync(
                QueryType.Count(),
                "testCollection",
                "",
                QueryRelativeTimeframe.ThisMonth(),
                filters);

            Assert.IsNotNull(count);
            Assert.AreEqual("2", count);
        }
示例#6
0
        public async Task Query_AvailableQueries_Success()
        {
            var queriesResource = HttpTests.GetUriForResource(SettingsEnv, KeenConstants.QueriesResource);

            var expectedQueries = new Dictionary <string, string>()
            {
                { "select_unique_url", $"{queriesResource.AbsolutePath}/select_unique" },
                { "minimum", $"{queriesResource.AbsolutePath}/minimum" },
                { "extraction_url", $"{queriesResource.AbsolutePath}/extraction" },
                { "percentile", $"{queriesResource.AbsolutePath}/percentile" },
                { "funnel_url", $"{queriesResource.AbsolutePath}/funnel" },
                { "average", $"{queriesResource.AbsolutePath}/average" },
                { "median", $"{queriesResource.AbsolutePath}/median" },
                { "maximum", $"{queriesResource.AbsolutePath}/maximum" },
                { "count_url", $"{queriesResource.AbsolutePath}/count" },
                { "count_unique_url", $"{queriesResource.AbsolutePath}/count_unique" },
                { "sum", $"{queriesResource.AbsolutePath}/sum" }
            };

            FuncHandler handler = new FuncHandler()
            {
                ProduceResultAsync = (request, ct) =>
                {
                    return(HttpTests.CreateJsonStringResponseAsync(expectedQueries));
                }
            };

            var client = new KeenClient(SettingsEnv, new TestKeenHttpClientProvider()
            {
                ProvideKeenHttpClient =
                    (url) => KeenHttpClientFactory.Create(url,
                                                          new HttpClientCache(),
                                                          null,
                                                          new DelegatingHandlerMock(handler))
            });

            var actualQueries = await client.GetQueriesAsync();

            Assert.That(actualQueries, Is.EquivalentTo(expectedQueries));
        }
示例#7
0
 internal static Task <HttpResponseMessage> CreateJsonStringResponseAsync(object data)
 {
     return(HttpTests.CreateJsonStringResponseAsync(data, HttpStatusCode.OK));
 }
示例#8
0
 internal static Task ValidateRequest(HttpRequestMessage request, string expectedRequestBody)
 {
     return(HttpTests.ValidateRequest(request, JObject.Parse(expectedRequestBody)));
 }