public void DeflatedStreamIsStoredUncompressed()
        {
            // ARRANGE
            var content = "Hello World";

            var compressed = new MemoryStream();

            using (var deflate = new DeflateStream(compressed, CompressionMode.Compress, leaveOpen: true))
            {
                new MemoryStream(Encoding.UTF8.GetBytes(content)).CopyTo(deflate);
            }

            var recordedStream = new RecordedStream(
                compressed.ToArray(),
                HttpWebResponseCreator.Create(
                    new Uri("http://fakeSite.fake"),
                    "POST",
                    HttpStatusCode.OK,
                    compressed,
                    new WebHeaderCollection
            {
                { HttpRequestHeader.ContentEncoding, "deflate" }
            }));

            // ACT
            var toString = recordedStream.ToString();

            // ASSERT
            recordedStream.IsEncoded.ShouldBeFalse();
            recordedStream.IsDeflateCompressed.ShouldBeTrue();

            toString.ShouldEqual(content);
        }
        public void CanGetFunky()
        {
            // ARRANGE
            var responseCreator = new Func <InterceptedRequest, HttpWebResponse>(req =>
                                                                                 HttpWebResponseCreator.Create(
                                                                                     new Uri("https://unreleatedFake.site"),
                                                                                     "HEAD",
                                                                                     HttpStatusCode.Ambiguous,
                                                                                     new MemoryStream(Encoding.UTF8.GetBytes("Funky Response")),
                                                                                     new WebHeaderCollection
            {
                { HttpResponseHeader.Date, DateTime.Now.ToShortDateString() }
            },
                                                                                     DecompressionMethods.None,
                                                                                     mediaType: "application/sql",
                                                                                     contentLength: 128,
                                                                                     statusDescription: "status",
                                                                                     isVersionHttp11: false,
                                                                                     usesProxySemantics: true,
                                                                                     isWebSocket: true,
                                                                                     connectionGroupName: "Testing Group"));

            IWebRequestCreate creator = new HttpWebRequestWrapperInterceptorCreator(responseCreator);
            var request = creator.Create(new Uri("http://fakeSite.fake"));

            // ACT
            var response = (HttpWebResponse)request.GetResponse();

            // ASSERT
            response.ShouldNotBeNull();
            response.Method.ToUpper().ShouldNotEqual("GET");
            response.StatusCode.ShouldNotEqual(HttpStatusCode.Accepted);
            response.Headers.AllKeys.ShouldNotBeEmpty();
            response.ProtocolVersion.Minor.ShouldEqual(0);
        }
        public void SessionSupportsFullMockThatReturnsText()
        {
            // ARRANGE
            var fakeResponseBody = "Fake Response";
            var mockWebRequest   = new Mock <HttpWebRequestWrapper>(new Uri("http://www.github.com"));

            mockWebRequest
            .Setup(x => x.GetResponse())
            .Returns(HttpWebResponseCreator.Create(new Uri("http://www.github.com"), "GET", HttpStatusCode.Accepted, fakeResponseBody));

            var mockCreator = new Mock <IWebRequestCreate>();

            mockCreator
            .Setup(x => x.Create(It.IsAny <Uri>()))
            .Returns(mockWebRequest.Object);

            // ACT
            HttpWebRequest request;

            using (new HttpWebRequestWrapperSession(mockCreator.Object))
            {
                request = (HttpWebRequest)WebRequest.Create("http://www.github.com");
            }

            // ASSERT
            using (var sr = new StreamReader(request.GetResponse().GetResponseStream()))
                Assert.Equal(sr.ReadToEnd(), fakeResponseBody);

            mockWebRequest.Verify(x => x.GetResponse());
        }
        public void CanSpoofWebRequestException()
        {
            // ARRANGE
            var fakeUrl = new Uri("http://fakeSite.fake");

            var fakeResponse =
                HttpWebResponseCreator.Create(
                    fakeUrl,
                    "GET",
                    HttpStatusCode.BadRequest,
                    "Test Response Body",
                    new WebHeaderCollection
            {
                { HttpResponseHeader.ETag, "testHeaders" }
            });

            var fakeException = new WebException(
                "Bad Request",
                innerException: null,
                status: WebExceptionStatus.SendFailure,
                response: fakeResponse);

            var responseCreator = new Func <InterceptedRequest, HttpWebResponse>(req => throw fakeException);

            IWebRequestCreate creator = new HttpWebRequestWrapperInterceptorCreator(responseCreator);
            var request = creator.Create(fakeUrl);

            // ACT
            var exception    = Record.Exception(() => request.GetResponse());
            var webException = exception as WebException;

            // ASSERT
            webException.ShouldNotBeNull();
            webException.ShouldEqual(fakeException);
        }
        /// <summary>
        /// Examines <paramref name="request"/> and if <see cref="RecordedRequest.ResponseException"/>
        /// is populated, creates a new strongly typed exception based on the data in <paramref name="request"/>
        /// and sets <paramref name="recordedException"/>.
        /// <para />
        /// If <see cref="RecordedRequest.ResponseException"/> is null, then <paramref name="recordedException"/>
        /// is set to null and this returns <c>false</c>.
        /// <para />
        /// This method can activate any exception type as long as it has a constructor that takes a single
        /// string parameter.
        /// <para />
        /// However, there is special handling for <see cref="WebException"/>s.  If <see cref="RecordedRequest.ResponseBody"/>
        /// and the other Response properties are set, then this data will be used to set <see cref="WebException.Response"/>.
        /// </summary>
        /// <returns>
        /// <c>true</c> if <paramref name="request"/> has a <see cref="RecordedRequest.ResponseException"/>,
        /// indicating <paramref name="recordedException"/> has been populated.  <c>false</c> otherwise.
        /// </returns>
        public static bool TryGetResponseException(this RecordedRequest request, out Exception recordedException)
        {
            recordedException = null;

            if (request?.ResponseException == null)
            {
                return(false);
            }

            if (request.ResponseException.Type != typeof(WebException))
            {
                // use reflection to create the exception.  really
                // hope whatever it is, the exception has a Exception(string message)
                // constructor, other we are in trouble.  However, all of the documented
                // exceptions that HttpWebRequest.GetResponse() can throw do, so we should be ok
                recordedException =
                    (Exception)
                    Activator.CreateInstance(
                        request.ResponseException.Type,
                        args: request.ResponseException.Message);

                return(true);
            }

            // if we're here - we're building a WebException

            if (null == request.ResponseException.WebExceptionStatus)
            {
                recordedException = new WebException(request.ResponseException.Message);
                return(true);
            }

            // can we return a WebException without a Response?
            if (string.IsNullOrEmpty(request?.ResponseBody?.SerializedStream) &&
                // always need to return a response if WebExceptionStatus is ProtocolError
                //https://msdn.microsoft.com/en-us/library/system.net.webexception.response(v=vs.110).aspx
                request.ResponseException.WebExceptionStatus != WebExceptionStatus.ProtocolError)
            {
                recordedException = new WebException(
                    request.ResponseException.Message,
                    request.ResponseException.WebExceptionStatus.Value);

                return(true);
            }

            // if we have a response body, then we need to build a complicated Web Exception

            recordedException =
                new WebException(
                    request.ResponseException.Message,
                    innerException: null,
                    status: request.ResponseException.WebExceptionStatus.Value,
                    response: HttpWebResponseCreator.Create(
                        new Uri(request.Url),
                        request.Method,
                        request.ResponseStatusCode,
                        request.ResponseBody?.ToStream() ?? new MemoryStream(),
                        request.ResponseHeaders));

            return(true);
        }