Exemplo n.º 1
0
            public Task <IWebResponseData> GetResponseAsync(System.Threading.CancellationToken cancellationToken)
            {
                if (this.GetResponseAction != null)
                {
                    this.GetResponseAction();
                }

                return(Task.FromResult <IWebResponseData>(new HttpWebRequestResponseData(
                                                              MockWebResponse.CreateFromResource(this.RequestUri.Host)
                                                              as HttpWebResponse)));
            }
Exemplo n.º 2
0
            public Amazon.Runtime.Internal.Transform.IWebResponseData EndGetResponse(IAsyncResult asyncResult)
            {
                if (this.GetResponseAction != null)
                {
                    this.GetResponseAction();
                }

                return(new HttpWebRequestResponseData(
                           MockWebResponse.CreateFromResource(this.RequestUri.Host)
                           as HttpWebResponse));
            }
Exemplo n.º 3
0
            public Amazon.Runtime.Internal.Transform.IWebResponseData GetResponse()
            {
                if (this.GetResponseAction != null)
                {
                    this.GetResponseAction();
                }

                // Extract the last segment of the URI, this is the custom URI
                // sent by the unit tests.
                var resourceName = this.RequestUri.Host.Split('.').Last();

                return(new HttpWebRequestResponseData(
                           MockWebResponse.CreateFromResource(resourceName)
                           as HttpWebResponse));
            }
Exemplo n.º 4
0
            protected override void CustomizeRuntimePipeline(RuntimePipeline pipeline)
            {
                base.CustomizeRuntimePipeline(pipeline);

                this.MockFactory = new Mock <IHttpRequestFactory <Stream> >();
                this.MockFactory.Setup(foo => foo.CreateHttpRequest(It.IsAny <Uri>()))
                .Returns((Uri uri) =>
                {
                    var request = new Mock <IHttpRequest <Stream> >();
                    request.Setup(foo => foo.GetResponse())
                    .Returns(new HttpWebRequestResponseData(MockWebResponse.CreateFromResource("ListObjectsResponse.txt")));
                    return(request.Object);
                })
                .Callback((Uri uri) => this.LastRequestUri = uri);
                pipeline.ReplaceHandler <HttpHandler <Stream> >(new HttpHandler <Stream>(this.MockFactory.Object, this));
            }
Exemplo n.º 5
0
            private HttpWebResponse CreateResponse(MockHttpRequest request)
            {
                // Extract the last segment of the URI, this is the custom URI
                // sent by the unit tests.
                var resourceName = request.RequestUri.Host.Split('.').Last();
                var response     = MockWebResponse.CreateFromResource(resourceName);

                if (response.StatusCode >= HttpStatusCode.OK && response.StatusCode <= (HttpStatusCode)299)
                {
                    return(response);
                }
                else
                {
                    throw new HttpErrorResponseException(new HttpWebRequestResponseData(response));
                }
            }
Exemplo n.º 6
0
        public void Test404Async()
        {
            Tester.Reset();
            Tester.Action = (int callCount) =>
            {
                var errorResponse = (HttpWebResponse)MockWebResponse.CreateFromResource("404Response.txt");
                throw new HttpErrorResponseException(new HttpWebRequestResponseData(errorResponse));
            };

            var context = CreateAsyncTestContext();

            var asyncResult = RuntimePipeline.InvokeAsync(context);

            asyncResult.AsyncWaitHandle.WaitOne();
            Assert.IsTrue(((RuntimeAsyncResult)asyncResult).Exception.GetType()
                          == typeof(AmazonS3Exception));
            Assert.AreEqual(1, Tester.CallCount);
        }
Exemplo n.º 7
0
        public async Task Test404Async()
        {
            Tester.Reset();
            Tester.Action = (int callCount) =>
            {
                var errorResponse = (HttpWebResponse)MockWebResponse.CreateFromResource("404Response.txt");
                throw new HttpErrorResponseException(new HttpWebRequestResponseData(errorResponse));
            };

            var context = CreateTestContext();

            await Utils.AssertExceptionExpectedAsync(() =>
            {
                return(RuntimePipeline.InvokeAsync <AmazonWebServiceResponse>(context));
            },
                                                     typeof(AmazonS3Exception));

            Assert.AreEqual(1, Tester.CallCount);
        }
Exemplo n.º 8
0
        private static HttpWebResponse GetListBucketsResponse()
        {
            var body    = @"<?xml version=""1.0"" encoding=""UTF-8""?>
<ListAllMyBucketsResult xmlns=""http://s3.amazonaws.com/doc/2006-03-01/"">
    <Owner>
        <ID>123456789</ID>
        <DisplayName>test-account</DisplayName>
    </Owner>
    <Buckets>
        <Bucket>
            <Name>Bucket1</Name>
            <CreationDate>2014-04-18T17:56:06.000Z</CreationDate>
        </Bucket>
        <Bucket>
            <Name>Bucket2</Name>
            <CreationDate>2014-06-05T23:18:53.000Z</CreationDate>
        </Bucket>
        <Bucket>
            <Name>Bucket3</Name>
            <CreationDate>2014-06-05T23:18:53.000Z</CreationDate>
        </Bucket>
        <Bucket>
            <Name>Bucket4</Name>
            <CreationDate>2014-06-05T23:18:53.000Z</CreationDate>
        </Bucket>
    </Buckets>
</ListAllMyBucketsResult>";
            var headers = new Dictionary <string, string>();

            headers["x-amz-request-id"]  = "357B62B8E32948B9";
            headers["x-amz-id-2"]        = "TFD+oMfRT5nVXm81tex2+Uh8R/VZRaztjPALzXknR7IC3RGfVPhpuiiHMtL0fFKF";
            headers["Content-Type"]      = "application/xml";
            headers["Transfer-Encoding"] = "chunked";
            headers["Date"]   = "Mon, 23 Jun 2014 03:31:12 GMT";
            headers["Server"] = "AmazonS3";

            var response = MockWebResponse.Create(HttpStatusCode.OK, headers, body)
                           as HttpWebResponse;

            return(response);
        }
Exemplo n.º 9
0
        public void Test404()
        {
            Tester.Reset();
            Tester.Action = (int callCount) =>
            {
                var errorResponse = (HttpWebResponse)MockWebResponse.CreateFromResource("404Response.txt");
                throw new HttpErrorResponseException(new HttpWebRequestResponseData(errorResponse));
            };

            var context = CreateTestContext();

            var exception = Utils.AssertExceptionExpected(() =>
            {
                RuntimePipeline.InvokeSync(context);
            },
                                                          typeof(AmazonS3Exception));

            Assert.AreEqual("NoSuchBucket", ((AmazonS3Exception)exception).ErrorCode);
            Assert.AreEqual(HttpStatusCode.NotFound, ((AmazonS3Exception)exception).StatusCode);
            Assert.AreEqual(1, Tester.CallCount);
        }
Exemplo n.º 10
0
        public void TestGetObjectResponseValidChecksum(string header, string checksumValue, CoreChecksumAlgorithm expectedAlgorithm)
        {
            Tester.Reset();

            var context = CreateTestContext();
            var request = new GetObjectRequest
            {
                BucketName   = "foo",
                Key          = "bar",
                ChecksumMode = ChecksumMode.ENABLED
            };

            ((RequestContext)context.RequestContext).OriginalRequest = request;
            ((RequestContext)context.RequestContext).Request         = new GetObjectRequestMarshaller().Marshall(request);
            ((RequestContext)context.RequestContext).Unmarshaller    = GetObjectResponseUnmarshaller.Instance;

            var expectedResponseBody = "Hello world";
            var response             = MockWebResponse.Create(HttpStatusCode.OK, new Dictionary <string, string>(), expectedResponseBody);

            response.Headers.Add("Content-Length", "11");
            response.Headers.Add(header, checksumValue);

            context.ResponseContext.HttpResponse = new HttpWebRequestResponseData(response);

            RuntimePipeline.InvokeSync(context);

            Assert.AreEqual(1, Tester.CallCount);
            Assert.IsInstanceOfType(context.ResponseContext.Response, typeof(GetObjectResponse));

            var getObjectResponse = context.ResponseContext.Response as GetObjectResponse;

            Assert.AreEqual(expectedAlgorithm, getObjectResponse.ResponseMetadata.ChecksumAlgorithm);
            Assert.AreEqual(ChecksumValidationStatus.PENDING_RESPONSE_READ, getObjectResponse.ResponseMetadata.ChecksumValidationStatus);

            // Read the stream to the end to finish checksum calcuation and validation
            // This implicitly asserts that the checksum is valid because an exception would be thrown otherwise
            var responseBody = new StreamReader(getObjectResponse.ResponseStream).ReadToEnd();

            Assert.AreEqual(expectedResponseBody, responseBody);
        }
Exemplo n.º 11
0
        public async Task TestListBucketsResponseUnmarshallingAsync()
        {
            Tester.Reset();

            var context = CreateTestContext();
            var request = new ListBucketsRequest();

            ((RequestContext)context.RequestContext).OriginalRequest = request;
            ((RequestContext)context.RequestContext).Request         = new ListBucketsRequestMarshaller().Marshall(request);
            ((RequestContext)context.RequestContext).Unmarshaller    = ListBucketsResponseUnmarshaller.Instance;

            var response = MockWebResponse.CreateFromResource("ListBucketsResponse.txt")
                           as HttpWebResponse;

            context.ResponseContext.HttpResponse = new HttpWebRequestResponseData(response);

            var listBucketsResponse = await RuntimePipeline.InvokeAsync <ListBucketsResponse>(context);

            Assert.AreEqual(1, Tester.CallCount);
            Assert.IsInstanceOfType(context.ResponseContext.Response, typeof(ListBucketsResponse));
            Assert.AreEqual(4, listBucketsResponse.Buckets.Count);
        }
Exemplo n.º 12
0
        public void TestSuppressed404()
        {
            Tester.Reset();
            Tester.Action = (int callCount) =>
            {
                var errorResponse = (HttpWebResponse)MockWebResponse.CreateFromResource("404Response.txt");
                throw new HttpErrorResponseException(new HttpWebRequestResponseData(errorResponse));
            };

            var context = CreateTestContext();
            var request = new GetBucketPolicyRequest
            {
                BucketName = "nonexistentbucket"
            };

            ((RequestContext)context.RequestContext).OriginalRequest = request;
            ((RequestContext)context.RequestContext).Request         = new GetBucketPolicyRequestMarshaller().Marshall(request);
            ((RequestContext)context.RequestContext).Unmarshaller    = GetBucketPolicyResponseUnmarshaller.Instance;

            RuntimePipeline.InvokeSync(context);
            Assert.AreEqual(1, Tester.CallCount);
        }
Exemplo n.º 13
0
        private static Func <HttpHandlerTests.MockHttpRequest, HttpWebResponse> Create(
            string content, string requestId, bool isOK)
        {
            var status = isOK ? HttpStatusCode.OK : HttpStatusCode.NotFound;

            return((request) =>
            {
                Dictionary <string, string> headers = new Dictionary <string, string>(StringComparer.Ordinal);
                if (!string.IsNullOrEmpty(requestId))
                {
                    headers.Add(HeaderKeys.RequestIdHeader, requestId);
                }

                var response = MockWebResponse.Create(status, headers, content);
                if (isOK)
                {
                    return response;
                }

                throw new HttpErrorResponseException(new HttpWebRequestResponseData(response));
            });
        }
Exemplo n.º 14
0
        public void Test400WithErrorTypeHeader()
        {
            Tester.Reset();
            Tester.Action = (int callCount) =>
            {
                var errorResponse = (HttpWebResponse)MockWebResponse.CreateFromResource("400WithErrorTypeHeader.txt");
                throw new HttpErrorResponseException(new HttpWebRequestResponseData(errorResponse));
            };

            var context = CreateTestContext();

            ((RequestContext)context.RequestContext).Unmarshaller =
                Amazon.IotData.Model.Internal.MarshallTransformations.UpdateThingShadowResponseUnmarshaller.Instance;

            var exception = Utils.AssertExceptionExpected <Amazon.IotData.Model.InvalidRequestException>(() =>
            {
                RuntimePipeline.InvokeSync(context);
            });

            Assert.AreEqual("InvalidRequestException", exception.ErrorCode);
            Assert.AreEqual(HttpStatusCode.BadRequest, exception.StatusCode);
            Assert.AreEqual(1, Tester.CallCount);
        }
        protected virtual IExecutionContext CreateTestContext(AbstractAWSSigner signer, ResponseUnmarshaller responseUnmarshaller, ClientConfig config)
        {
            var putObjectRequest = new PutObjectRequest
            {
                Key         = "TestKey",
                BucketName  = "TestBucket",
                ContentBody = "Test Content"
            };

            if (responseUnmarshaller == null)
            {
                responseUnmarshaller = PutObjectResponseUnmarshaller.Instance;
            }

            var requestContext = new RequestContext(true, signer == null ? new NullSigner() : signer)
            {
                OriginalRequest = putObjectRequest,
                Request         = new PutObjectRequestMarshaller().Marshall(putObjectRequest),
                Unmarshaller    = responseUnmarshaller,
                ClientConfig    = config ?? new AmazonS3Config
                {
                    RegionEndpoint = RegionEndpoint.USEast1
                }
            };

            requestContext.Request.Endpoint = new Uri("https://s3.amazonaws.com");

            var putObjectResponse = MockWebResponse.CreateFromResource("PutObjectResponse.txt")
                                    as HttpWebResponse;

            return(new Amazon.Runtime.Internal.ExecutionContext(requestContext,
                                                                new ResponseContext
            {
                HttpResponse = new HttpWebRequestResponseData(putObjectResponse)
            }));
        }
Exemplo n.º 16
0
        public void Test404()
        {
            Tester.Reset();
            Tester.Action = (int callCount) =>
            {
                var body    = @"<?xml version=""1.0"" encoding=""UTF-8""?>
<Error>
    <Code>NoSuchBucket</Code>
    <Message>The specified bucket does not exist</Message>
    <BucketName>nonexistentbucket</BucketName>
    <RequestId>749945D6E23AFF48</RequestId>
    <HostId>xN4fcAA90mhYmTC8o/SX2jBBunBSrD45cMwLYwAu0LZhcn9HIU/KXwtieQO05beD</HostId>
</Error>";
                var headers = new Dictionary <string, string>();
                headers["x-amz-request-id"]  = "749945D6E23AFF48";
                headers["x-amz-id-2"]        = "xN4fcAA90mhYmTC8o/SX2jBBunBSrD45cMwLYwAu0LZhcn9HIU/KXwtieQO05beD";
                headers["Content-Type"]      = "application/xml";
                headers["Transfer-Encoding"] = "chunked";
                headers["Date"]   = "Mon, 16 Jun 2014 17:34:56 GMT";
                headers["Server"] = "AmazonS3";
                var errorResponse = (HttpWebResponse)MockWebResponse.Create(HttpStatusCode.NotFound, headers, body);
                throw new HttpErrorResponseException(new HttpWebRequestResponseData(errorResponse));
            };

            var context = CreateTestContext();

            var exception = Utils.AssertExceptionExpected(() =>
            {
                RuntimePipeline.InvokeSync(context);
            },
                                                          typeof(AmazonS3Exception));

            Assert.AreEqual("NoSuchBucket", ((AmazonS3Exception)exception).ErrorCode);
            Assert.AreEqual(HttpStatusCode.NotFound, ((AmazonS3Exception)exception).StatusCode);
            Assert.AreEqual(1, Tester.CallCount);
        }