public void Given_Null_Parameters_When_SendAsync_Invoked_Then_It_Should_Throw_Exception(string verb)
        {
            var requestUri = "http://localhost";
            var validator  = new Mock <ISchemaValidator>();

            var func = default(Func <Task>);

            using (var httpClient = this._fixture.CreateHttpClient())
                using (var request = this._fixture.CreateHttpRequestMessage(verb, requestUri))
                {
                    func = async() => await HttpClientExtensions.SendAsync(null, null, null, null).ConfigureAwait(false);

                    func.Should().Throw <ArgumentNullException>();

                    func = async() => await HttpClientExtensions.SendAsync(httpClient, null, null, null).ConfigureAwait(false);

                    func.Should().Throw <ArgumentNullException>();

                    func = async() => await HttpClientExtensions.SendAsync(httpClient, request, null, null).ConfigureAwait(false);

                    func.Should().Throw <ArgumentNullException>();

                    func = async() => await HttpClientExtensions.SendAsync(httpClient, request, validator.Object, null).ConfigureAwait(false);

                    func.Should().Throw <ArgumentNullException>();
                }
        }
        public async Task HttpClientExtensions_SendAsync_Headers_SetsHeaders()
        {
            var method = HttpMethod.Get;
            var uri    = new Uri("http://example.com");

            var customHeaders = new Dictionary <string, IEnumerable <string> >
            {
                ["header0"] = new string[0],
                ["header1"] = new [] { "first-value" },
                ["header2"] = new [] { "first-value", "second-value" },
                ["header3"] = new [] { "first-value", "second-value", "third-value" },
            };

            var httpHandler = new TestHttpMessageHandler {
                ThrowOnUnexpectedRequest = true
            };

            httpHandler.Setup(method, uri, request =>
            {
                Assert.False(request.Headers.Contains("header0"));
                Assert.True(request.Headers.Contains("header1"));
                Assert.True(request.Headers.Contains("header2"));
                Assert.True(request.Headers.Contains("header3"));
                Assert.Equal(customHeaders["header1"], request.Headers.GetValues("header1"));
                Assert.Equal(customHeaders["header2"], request.Headers.GetValues("header2"));
                Assert.Equal(customHeaders["header3"], request.Headers.GetValues("header3"));

                return(new HttpResponseMessage());
            });

            var httpClient = new HttpClient(httpHandler);

            await HttpClientExtensions.SendAsync(httpClient, method, uri, customHeaders);
        }
        public void Given_Error_Response_With_HttpCompletionOption_And_CancellationToken_When_SendAsync_Invoked_Then_It_Should_Throw_Exception(string verb, HttpStatusCode statusCode, HttpCompletionOption option)
        {
            var requestUri = "http://localhost";
            var payload    = "{ \"hello\": \"world\" }";

            var exception = new SchemaValidationException();
            var validator = new Mock <ISchemaValidator>();

            validator.Setup(p => p.ValidateAsync(It.IsAny <string>(), It.IsAny <string>())).ReturnsAsync(true);

            var path = "default.json";

            var func = default(Func <Task>);

            using (var response = this._fixture.CreateHttpResponseMessage(statusCode, payload))
                using (var handler = this._fixture.CreateFakeHttpMessageHandler(response))
                    using (var httpClient = this._fixture.CreateHttpClient(handler))
                        using (var source = this._fixture.CreateCancellationTokenSource())
                            using (var request = this._fixture.CreateHttpRequestMessage(verb, requestUri, payload))
                            {
                                func = async() => await HttpClientExtensions.SendAsync(httpClient, request, option, validator.Object, path, source.Token).ConfigureAwait(false);

                                func.Should().Throw <HttpRequestException>();
                            }
        }
        public void Given_Null_Parameters_With_HttpCompletionOption_And_CancellationToken_When_SendAsync_Invoked_Then_It_Should_Throw_Exception(string verb, HttpCompletionOption option)
        {
            var requestUri = "http://localhost";
            var validator  = new Mock <ISchemaValidator>();
            var token      = default(CancellationToken);

            var path = "default.json";

            var func = default(Func <Task>);

            using (var httpClient = this._fixture.CreateHttpClient())
                using (var request = this._fixture.CreateHttpRequestMessage(verb, requestUri))
                {
                    func = async() => await HttpClientExtensions.SendAsync(null, null, option, null, null, token).ConfigureAwait(false);

                    func.Should().Throw <ArgumentNullException>();

                    func = async() => await HttpClientExtensions.SendAsync(httpClient, null, option, null, null, token).ConfigureAwait(false);

                    func.Should().Throw <ArgumentNullException>();

                    func = async() => await HttpClientExtensions.SendAsync(httpClient, request, option, null, null, token).ConfigureAwait(false);

                    func.Should().Throw <ArgumentNullException>();

                    func = async() => await HttpClientExtensions.SendAsync(httpClient, request, option, validator.Object, null, token).ConfigureAwait(false);

                    func.Should().Throw <ArgumentNullException>();

                    func = async() => await HttpClientExtensions.SendAsync(httpClient, request, option, validator.Object, path, token).ConfigureAwait(false);

                    func.Should().Throw <ArgumentNullException>();
                }
        }
        public async Task Given_Unsupported_Method_When_SendAsync_Invoked_Then_It_Should_Return_405(string verb, HttpStatusCode statusCode, HttpStatusCode expected)
        {
            var requestUri = "http://localhost";
            var payload    = "{ \"hello\": \"world\" }";
            var validator  = new Mock <ISchemaValidator>();

            var path = "default.json";

            using (var handler = this._fixture.CreateFakeHttpMessageHandler(statusCode, payload))
                using (var httpClient = this._fixture.CreateHttpClient(handler))
                    using (var request = this._fixture.CreateHttpRequestMessage(verb, requestUri, payload))
                        using (var response = await HttpClientExtensions.SendAsync(httpClient, request, validator.Object, path).ConfigureAwait(false))
                        {
                            response.StatusCode.Should().Be(expected);
                        }
        }
        public async Task HttpClientExtensions_SendAsync_SendsRequestMessage()
        {
            var method = HttpMethod.Get;
            var uri    = new Uri("http://example.com");

            var httpHandler = new TestHttpMessageHandler {
                ThrowOnUnexpectedRequest = true
            };

            httpHandler.Setup(method, uri, request =>
            {
                Assert.Equal(method, request.Method);
                Assert.Equal(uri, request.RequestUri);

                return(new HttpResponseMessage());
            });

            var httpClient = new HttpClient(httpHandler);

            await HttpClientExtensions.SendAsync(httpClient, method, uri);
        }
        public async Task HttpClientExtensions_SendAsync_Content_SetsContent()
        {
            var method = HttpMethod.Get;
            var uri    = new Uri("http://example.com");

            var expectedContent = new StringContent("foobar");

            var httpHandler = new TestHttpMessageHandler {
                ThrowOnUnexpectedRequest = true
            };

            httpHandler.Setup(method, uri, request =>
            {
                Assert.Same(expectedContent, request.Content);

                return(new HttpResponseMessage());
            });

            var httpClient = new HttpClient(httpHandler);

            await HttpClientExtensions.SendAsync(httpClient, method, uri, null, expectedContent);
        }
        public async Task Given_Validation_Result_With_HttpCompletionOption_When_SendAsync_Invoked_Then_It_Should_Return_Result(string verb, HttpStatusCode statusCode, HttpCompletionOption option)
        {
            var requestUri = "http://localhost";
            var payload    = "{ \"hello\": \"world\" }";

            var exception = new SchemaValidationException();
            var validator = new Mock <ISchemaValidator>();

            validator.Setup(p => p.ValidateAsync(It.IsAny <string>(), It.IsAny <string>())).ReturnsAsync(true);

            var path = "default.json";

            using (var response = this._fixture.CreateHttpResponseMessage(statusCode, payload))
                using (var handler = this._fixture.CreateFakeHttpMessageHandler(response))
                    using (var httpClient = this._fixture.CreateHttpClient(handler))
                        using (var request = this._fixture.CreateHttpRequestMessage(verb, requestUri, payload))
                        {
                            var result = await HttpClientExtensions.SendAsync(httpClient, request, option, validator.Object, path).ConfigureAwait(false);

                            result.Should().Be(response);
                        }
        }
Esempio n. 9
0
        public virtual async Task <ContentType> DetectContentTypeAsync(Uri url, ContentKind contentKind, CancellationToken cancellationToken, IWebReader parent = null)
        {
            ContentType contentType = EnumerableExtensions.SingleOrDefaultSafe <ContentType>((IEnumerable <ContentType>) this._contentTypeDetector.GetContentType(url, (string)null, (string)null));
            ContentType contentType1;

            if ((ContentType)null != contentType)
            {
                Debug.WriteLine("HttpClientWebReaderManager.DetectContentTypeAsync() url ext \"{0}\" type {1}", (object)url, (object)contentType);
                contentType1 = contentType;
            }
            else
            {
                Uri referrer = HttpClientWebReaderManager.GetReferrer(parent);
                using (HttpClient client = this._httpClientFactory.CreateClient(url, referrer, ContentKind.Unknown, (ContentType)null))
                {
                    try
                    {
                        using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Head, url))
                        {
                            using (HttpResponseMessage httpResponseMessage = await HttpClientExtensions.SendAsync(client, request, HttpCompletionOption.ResponseHeadersRead, cancellationToken, referrer, new long?(), new long?()).ConfigureAwait(false))
                            {
                                if (httpResponseMessage.IsSuccessStatusCode)
                                {
                                    contentType = EnumerableExtensions.SingleOrDefaultSafe <ContentType>((IEnumerable <ContentType>)HttpClientContentTypeDetectorExtensions.GetContentType(this._contentTypeDetector, request.RequestUri, httpResponseMessage.Content.Headers, HttpContentExtensions.FileName(httpResponseMessage.Content)));
                                    if ((ContentType)null != contentType)
                                    {
                                        Debug.WriteLine("HttpClientWebReaderManager.DetectContentTypeAsync() url HEAD \"{0}\" type {1}", (object)url, (object)contentType);
                                        contentType1 = contentType;
                                        goto label_49;
                                    }
                                }
                            }
                        }
                    }
                    catch (HttpRequestException ex)
                    {
                    }
                    try
                    {
                        using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, url))
                        {
                            using (HttpResponseMessage httpResponseMessage = await HttpClientExtensions.SendAsync(client, request, HttpCompletionOption.ResponseHeadersRead, cancellationToken, referrer, new long?(0L), new long?(0L)).ConfigureAwait(false))
                            {
                                if (httpResponseMessage.IsSuccessStatusCode)
                                {
                                    contentType = EnumerableExtensions.SingleOrDefaultSafe <ContentType>((IEnumerable <ContentType>)HttpClientContentTypeDetectorExtensions.GetContentType(this._contentTypeDetector, request.RequestUri, httpResponseMessage.Content.Headers, HttpContentExtensions.FileName(httpResponseMessage.Content)));
                                    if ((ContentType)null != contentType)
                                    {
                                        Debug.WriteLine("HttpClientWebReaderManager.DetectContentTypeAsync() url range GET \"{0}\" type {1}", (object)url, (object)contentType);
                                        contentType1 = contentType;
                                        goto label_49;
                                    }
                                }
                            }
                        }
                    }
                    catch (HttpRequestException ex)
                    {
                    }
                    try
                    {
                        using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, url))
                        {
                            using (HttpResponseMessage httpResponseMessage = await HttpClientExtensions.SendAsync(client, request, HttpCompletionOption.ResponseHeadersRead, cancellationToken, referrer, new long?(), new long?()).ConfigureAwait(false))
                            {
                                if (httpResponseMessage.IsSuccessStatusCode)
                                {
                                    contentType = EnumerableExtensions.SingleOrDefaultSafe <ContentType>((IEnumerable <ContentType>)HttpClientContentTypeDetectorExtensions.GetContentType(this._contentTypeDetector, request.RequestUri, httpResponseMessage.Content.Headers, HttpContentExtensions.FileName(httpResponseMessage.Content)));
                                    if ((ContentType)null != contentType)
                                    {
                                        Debug.WriteLine("HttpClientWebReaderManager.DetectContentTypeAsync() url GET \"{0}\" type {1}", (object)url, (object)contentType);
                                        contentType1 = contentType;
                                        goto label_49;
                                    }
                                }
                            }
                        }
                    }
                    catch (HttpRequestException ex)
                    {
                    }
                }
                Debug.WriteLine("HttpClientWebReaderManager.DetectContentTypeAsync() url header \"{0}\" unknown type", (object)url);
                contentType1 = (ContentType)null;
            }
label_49:
            return(contentType1);
        }