public void InvokeActionWithExceptionFilters_IfActionTaskIsFaulted_ExecutesFiltersAndReturnsResultIfHandled()
        {
            // Arrange
            List <string>       log                      = new List <string>();
            var                 exception                = new Exception();
            var                 actionTask               = TaskHelpers.FromError <HttpResponseMessage>(exception);
            HttpResponseMessage globalFilterResponse     = new HttpResponseMessage();
            HttpResponseMessage actionFilterResponse     = new HttpResponseMessage();
            HttpResponseMessage resultSeenByGlobalFilter = null;
            var                 globalFilterMock         = CreateExceptionFilterMock((ec, ct) =>
            {
                log.Add("globalFilter");
                resultSeenByGlobalFilter = ec.Response;
                ec.Response = globalFilterResponse;
                return(Task.Factory.StartNew(() => { }));
            });
            var actionFilterMock = CreateExceptionFilterMock((ec, ct) =>
            {
                log.Add("actionFilter");
                ec.Response = actionFilterResponse;
                return(Task.Factory.StartNew(() => { }));
            });
            var filters = new[] { globalFilterMock.Object, actionFilterMock.Object };

            // Act
            var result = ApiController.InvokeActionWithExceptionFilters(actionTask, _actionContextInstance, CancellationToken.None, filters);

            // Assert
            Assert.NotNull(result);
            result.WaitUntilCompleted();
            Assert.Equal(TaskStatus.RanToCompletion, result.Status);
            Assert.Same(globalFilterResponse, result.Result);
            Assert.Same(actionFilterResponse, resultSeenByGlobalFilter);
            Assert.Equal(new string[] { "actionFilter", "globalFilter" }, log.ToArray());
        }
示例#2
0
        public void HeaderParserSpecializedHeaders()
        {
            Dictionary <string, string> headerData = new Dictionary <string, string>
            {
                { @"JsonProperties0", @"{ ""SessionId"": ""{27729E1-B37B-4D29-AA0A-E367906C206E}"", ""MessageId"": ""{701332E1-B37B-4D29-AA0A-E367906C206E}"", ""TimeToLive"" : 90, ""CorrelationId"": ""{701332F3-B37B-4D29-AA0A-E367906C206E}"", ""SequenceNumber"" : 12345, ""DeliveryCount"" : 2, ""To"" : ""http://contoso.com/path1"", ""ReplyTo"" : ""http://fabrikam.com/path1"",  ""SentTimeUtc"" : ""Sun, 06 Nov 1994 08:49:37 GMT"", ""ScheduledEnqueueTimeUtc"" : ""Sun, 06 Nov 1994 08:49:37 GMT""}" },
                { @"JsonProperties1", @"{ ""SessionId"": ""{2813D4D2-46A9-4F4D-8904-E9BDE3712B70}"", ""MessageId"": ""{24AE31D6-63B8-46F3-9975-A3DAF1B6D3F4}"", ""TimeToLive"" : 80, ""CorrelationId"": ""{896DD5BD-1645-44D7-9E7C-D7F70958ECD6}"", ""SequenceNumber"" : 54321, ""DeliveryCount"" : 4, ""To"" : ""http://contoso.com/path2"", ""ReplyTo"" : ""http://fabrikam.com/path2"",  ""SentTimeUtc"" : ""Sun, 06 Nov 1994 10:49:37 GMT"", ""ScheduledEnqueueTimeUtc"" : ""Sun, 06 Nov 1994 10:49:37 GMT""}" },
                { @"P3P", @"CP=""ALL IND DSP COR ADM CONo CUR CUSo IVAo IVDo PSA PSD TAI TELo OUR SAMo CNT COM INT NAV ONL PHY PRE PUR UNI""" },
                { @"Cookie", @"omniID=1297715979621_9f45_1519_3f8a_f22f85346ac6; WT_FPC=id=65.55.227.138-2323234032.30136233:lv=1309374389020:ss=1309374389020; A=I&I=AxUFAAAAAACNCAAADYEZ7CFPss7Swnujy4PXZA!!&M=1&CS=126mAa0002ZB51a02gZB51a; MC1=GUID=568428660ad44d4ab8f46133f4b03738&HASH=6628&LV=20113&V=3; WT_NVR_RU=0=msdn:1=:2=; MUID=A44DE185EA1B4E8088CCF7B348C5D65F; MSID=Microsoft.CreationDate=03/04/2011 23:38:15&Microsoft.LastVisitDate=06/20/2011 04:15:08&Microsoft.VisitStartDate=06/20/2011 04:15:08&Microsoft.CookieId=f658f3f2-e6d6-42ab-b86b-96791b942b6f&Microsoft.TokenId=ffffffff-ffff-ffff-ffff-ffffffffffff&Microsoft.NumberOfVisits=106&Microsoft.CookieFirstVisit=1&Microsoft.IdentityToken=AA==&Microsoft.MicrosoftId=0441-6141-1523-9969; msresearch=%7B%22version%22%3A%224.6%22%2C%22state%22%3A%7B%22name%22%3A%22IDLE%22%2C%22url%22%3Aundefined%2C%22timestamp%22%3A1299281911415%7D%2C%22lastinvited%22%3A1299281911415%2C%22userid%22%3A%2212992819114151265672533023080%22%2C%22vendorid%22%3A1%2C%22surveys%22%3A%5Bundefined%5D%7D; CodeSnippetContainerLang=C#; msdn=L=1033; ADS=SN=175A21EF; s_cc=true; s_sq=%5B%5BB%5D%5D; TocHashCookie=ms310241(n)/aa187916(n)/aa187917(n)/dd273952(n)/dd295083(n)/ff472634(n)/ee667046(n)/ee667070(n)/gg259047(n)/gg618436(n)/; WT_NVR=0=/:1=query|library|en-us:2=en-us/vcsharp|en-us/library" },
                { @"Set-Cookie", @"A=I&I=AxUFAAAAAADsBgAA1sWZz4FGun/kOeyV4LGZVg!!&M=1; domain=.microsoft.com; expires=Sun, 30-Jun-2041 00:14:40 GMT; path=/" },
            };

            byte[] data = InternetMessageFormatHeaderParserTests.CreateBuffer(headerData.Select((kv) => { return(String.Format("{0}: {1}", kv.Key, kv.Value)); }).ToArray());
            for (var cnt = 1; cnt <= data.Length; cnt++)
            {
                HttpHeaders headers;
                InternetMessageFormatHeaderParser parser = InternetMessageFormatHeaderParserTests.CreateHeaderParser(data.Length, out headers);
                Assert.NotNull(parser);

                int         totalBytesConsumed = 0;
                ParserState state = InternetMessageFormatHeaderParserTests.ParseBufferInSteps(parser, data, cnt, out totalBytesConsumed);
                Assert.Equal(ParserState.Done, state);
                Assert.Equal(data.Length, totalBytesConsumed);

                Assert.Equal(headerData.Count, headers.Count());
                for (int hCnt = 0; hCnt < headerData.Count; hCnt++)
                {
                    Assert.Equal(headerData.Keys.ElementAt(hCnt), headers.ElementAt(hCnt).Key);
                    Assert.Equal(headerData.Values.ElementAt(hCnt), headers.ElementAt(hCnt).Value.ElementAt(0));
                }
            }
        }
示例#3
0
        public void Constructor1SetsProperties()
        {
            // All combination of formatters presented to ctor should still set XmlFormatter
            foreach (IEnumerable <MediaTypeFormatter> formatterCollection in HttpUnitTestDataSets.AllFormatterCollections)
            {
                MediaTypeFormatterCollection collection = new MediaTypeFormatterCollection(formatterCollection);
                if (collection.OfType <XmlMediaTypeFormatter>().Any())
                {
                    Assert.NotNull(collection.XmlFormatter);
                }
                else
                {
                    Assert.Null(collection.XmlFormatter);
                }

                if (collection.OfType <JsonMediaTypeFormatter>().Any())
                {
                    Assert.NotNull(collection.JsonFormatter);
                }
                else
                {
                    Assert.Null(collection.JsonFormatter);
                }
            }
        }
示例#4
0
        public void HeaderParserLwsHeader()
        {
            byte[] data = InternetMessageFormatHeaderParserTests.CreateBuffer("N1:V1", "N2: V2", "N3:\tV3");

            for (var cnt = 1; cnt <= data.Length; cnt++)
            {
                HttpHeaders headers;
                InternetMessageFormatHeaderParser parser = InternetMessageFormatHeaderParserTests.CreateHeaderParser(data.Length, out headers);
                Assert.NotNull(parser);

                int         totalBytesConsumed = 0;
                ParserState state = InternetMessageFormatHeaderParserTests.ParseBufferInSteps(parser, data, cnt, out totalBytesConsumed);
                Assert.Equal(ParserState.Done, state);
                Assert.Equal(data.Length, totalBytesConsumed);

                Assert.Equal(3, headers.Count());

                IEnumerable <string> parsedValues = headers.GetValues("N1");
                Assert.Equal(1, parsedValues.Count());
                Assert.Equal("V1", parsedValues.ElementAt(0));

                parsedValues = headers.GetValues("N2");
                Assert.Equal(1, parsedValues.Count());
                Assert.Equal("V2", parsedValues.ElementAt(0));

                parsedValues = headers.GetValues("N3");
                Assert.Equal(1, parsedValues.Count());
                Assert.Equal("V3", parsedValues.ElementAt(0));
            }
        }
        public void MultipartParserMultipleShortBodyPartsWithLws(string boundary)
        {
            string[] text = new string[] { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };

            byte[] data = CreateBuffer(boundary, true, text);

            for (var cnt = 1; cnt <= data.Length; cnt++)
            {
                MimeMultipartParser parser = CreateMimeMultipartParser(data.Length, boundary);
                Assert.NotNull(parser);

                int                       totalBytesConsumed;
                List <string>             bodyParts;
                MimeMultipartParser.State state = ParseBufferInSteps(parser, data, cnt, out bodyParts, out totalBytesConsumed);
                Assert.Equal(MimeMultipartParser.State.BodyPartCompleted, state);
                Assert.Equal(data.Length, totalBytesConsumed);

                Assert.Equal(text.Length + 1, bodyParts.Count);
                Assert.Equal(0, bodyParts[0].Length);

                for (var check = 0; check < text.Length; check++)
                {
                    Assert.Equal(1, bodyParts[check + 1].Length);
                    Assert.Equal(text[check], bodyParts[check + 1]);
                }
            }
        }
示例#6
0
        public void Completed_ReturnsCompletedTask()
        {
            Task result = TaskHelpers.Completed();

            Assert.NotNull(result);
            Assert.Equal(TaskStatus.RanToCompletion, result.Status);
        }
示例#7
0
        public void DefaultMediaType_ReturnsApplicationJson()
        {
            MediaTypeHeaderValue mediaType = JsonMediaTypeFormatter.DefaultMediaType;

            Assert.NotNull(mediaType);
            Assert.Equal("application/json", mediaType.MediaType);
        }
示例#8
0
        public void Canceled_ReturnsCanceledTask()
        {
            Task result = TaskHelpers.Canceled();

            Assert.NotNull(result);
            Assert.True(result.IsCanceled);
        }
        public void Negotiate_MediaTypeMappingTakesPrecedenceOverAcceptHeader()
        {
            // Prepare the request message
            _request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
            _request.Headers.Add("Browser", "IE");
            _request.Headers.Add("Cookie", "ABC");

            // Prepare the formatters
            List <MediaTypeFormatter> formatters = new List <MediaTypeFormatter>();

            formatters.Add(new JsonMediaTypeFormatter());
            formatters.Add(new XmlMediaTypeFormatter());
            PlainTextFormatter frmtr = new PlainTextFormatter();

            frmtr.SupportedMediaTypes.Clear();
            frmtr.MediaTypeMappings.Clear();
            frmtr.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/xml"));
            frmtr.MediaTypeMappings.Add(new MyMediaTypeMapping(new MediaTypeHeaderValue(("application/xml"))));
            formatters.Add(frmtr);

            // Act
            var result = _negotiator.Negotiate(typeof(string), _request, formatters);

            // Assert
            Assert.NotNull(result);
            Assert.Equal("application/xml", result.MediaType.MediaType);
            Assert.IsType <PlainTextFormatter>(result.Formatter);
        }
示例#10
0
        public void Canceled_Generic_ReturnsCanceledTask()
        {
            Task <string> result = TaskHelpers.Canceled <string>();

            Assert.NotNull(result);
            Assert.True(result.IsCanceled);
        }
        public void MimeMultipartParserTestMultipartContent(string boundary)
        {
            MultipartContent content = new MultipartContent("mixed", boundary);

            content.Add(new StringContent("A"));
            content.Add(new StringContent("B"));
            content.Add(new StringContent("C"));

            MemoryStream memStream = new MemoryStream();

            content.CopyToAsync(memStream).Wait();
            memStream.Position = 0;
            byte[] data = memStream.ToArray();

            for (var cnt = 1; cnt <= data.Length; cnt++)
            {
                MimeMultipartParser parser = CreateMimeMultipartParser(data.Length, boundary);
                Assert.NotNull(parser);

                int                       totalBytesConsumed;
                List <string>             bodyParts;
                MimeMultipartParser.State state = ParseBufferInSteps(parser, data, cnt, out bodyParts, out totalBytesConsumed);
                Assert.Equal(MimeMultipartParser.State.BodyPartCompleted, state);
                Assert.Equal(data.Length, totalBytesConsumed);

                Assert.Equal(4, bodyParts.Count);
                Assert.Empty(bodyParts[0]);

                Assert.True(bodyParts[1].EndsWith("A"));
                Assert.True(bodyParts[2].EndsWith("B"));
                Assert.True(bodyParts[3].EndsWith("C"));
            }
        }
        public void UrlDecodeParsesEmptySegmentsCorrectly()
        {
            int           iterations = 16;
            List <string> segments   = new List <string>();

            for (int index = 1; index < iterations; index++)
            {
                segments.Add("&");
                string query = string.Join("", segments);
                NameValueCollection result = ParseQueryString(query);
                Assert.NotNull(result);

                // Because this is a NameValueCollection, the same name appears only once
                Assert.Equal(1, result.Count);

                // Values should be a comma separated list of empty strings
                string[] values = result[""].Split(new char[] { ',' });

                // We expect length+1 segment as the final '&' counts as a segment
                Assert.Equal(index + 1, values.Length);
                foreach (var value in values)
                {
                    Assert.Equal("", value);
                }
            }
        }
        public void MultipartParserNesting(string boundary)
        {
            for (var nesting = 0; nesting < 16; nesting++)
            {
                string nested = CreateNestedBuffer(nesting);

                byte[] data = CreateBuffer(boundary, nested);

                for (var cnt = 1; cnt <= data.Length; cnt++)
                {
                    MimeMultipartParser parser = CreateMimeMultipartParser(data.Length, boundary);
                    Assert.NotNull(parser);

                    int                       totalBytesConsumed;
                    List <string>             bodyParts;
                    MimeMultipartParser.State state = ParseBufferInSteps(parser, data, cnt, out bodyParts, out totalBytesConsumed);
                    Assert.Equal(MimeMultipartParser.State.BodyPartCompleted, state);
                    Assert.Equal(data.Length, totalBytesConsumed);

                    Assert.Equal(2, bodyParts.Count);
                    Assert.Equal(0, bodyParts[0].Length);
                    Assert.Equal(nested.Length, bodyParts[1].Length);
                }
            }
        }
        public void InvokeActionWithExceptionFilters_IfActionTaskIsFaulted_ExecutesFiltersAndReturnsFaultedTaskIfNotHandled()
        {
            // Arrange
            List <string> log                   = new List <string>();
            var           exception             = new Exception();
            var           actionTask            = TaskHelpers.FromError <HttpResponseMessage>(exception);
            Exception     exceptionSeenByFilter = null;
            var           exceptionFilterMock   = CreateExceptionFilterMock((ec, ct) =>
            {
                exceptionSeenByFilter = ec.Exception;
                log.Add("exceptionFilter");
                return(Task.Factory.StartNew(() => { }));
            });
            var filters = new[] { exceptionFilterMock.Object };

            // Act
            var result = ApiController.InvokeActionWithExceptionFilters(actionTask, _actionContextInstance, CancellationToken.None, filters);

            // Assert
            Assert.NotNull(result);
            result.WaitUntilCompleted();
            Assert.Equal(TaskStatus.Faulted, result.Status);
            Assert.Same(exception, result.Exception.InnerException);
            Assert.Same(exception, exceptionSeenByFilter);
            Assert.Equal(new string[] { "exceptionFilter" }, log.ToArray());
        }
        public void ParseBufferCorrectly(string segment, string name, string value)
        {
            for (int index = 1; index < Iterations; index++)
            {
                List <string> segments = new List <string>();
                for (int cnt = 0; cnt < index; cnt++)
                {
                    segments.Add(segment);
                }

                byte[] data = CreateBuffer(segments.ToArray());
                for (var cnt = 1; cnt <= data.Length; cnt++)
                {
                    ICollection <KeyValuePair <string, string> > collection;
                    FormUrlEncodedParser parser = CreateParser(data.Length + 1, out collection);
                    Assert.NotNull(parser);

                    int         totalBytesConsumed;
                    ParserState state = ParseBufferInSteps(parser, data, cnt, out totalBytesConsumed);
                    Assert.Equal(ParserState.Done, state);
                    Assert.Equal(data.Length, totalBytesConsumed);

                    Assert.Equal(index, collection.Count());
                    foreach (KeyValuePair <string, string> element in collection)
                    {
                        Assert.Equal(name, element.Key);
                        Assert.Equal(value, element.Value);
                    }
                }
            }
        }
示例#16
0
        public void TryReadQueryAsTSucceeds()
        {
            UriBuilder address = new UriBuilder("http://some.host");

            address.Query = "a=2";
            SimpleObject1 so1;

            Assert.True(address.Uri.TryReadQueryAs <SimpleObject1>(out so1), "Expected 'true' reading valid data");
            Assert.NotNull(so1);
            Assert.Equal(2, so1.a);

            address.Query = "b=true";
            SimpleObject2 so2;

            Assert.True(address.Uri.TryReadQueryAs <SimpleObject2>(out so2), "Expected 'true' reading valid data");
            Assert.NotNull(so2);
            Assert.True(so2.b, "Value should have been true");

            address.Query = "c=hello";
            SimpleObject3 so3;

            Assert.True(address.Uri.TryReadQueryAs <SimpleObject3>(out so3), "Expected 'true' reading valid data");
            Assert.NotNull(so3);
            Assert.Equal("hello", so3.c);

            address.Query = "c=";
            Assert.True(address.Uri.TryReadQueryAs <SimpleObject3>(out so3), "Expected 'true' reading valid data");
            Assert.NotNull(so3);
            Assert.Equal("", so3.c);

            address.Query = "c=null";
            Assert.True(address.Uri.TryReadQueryAs <SimpleObject3>(out so3), "Expected 'true' reading valid data");
            Assert.NotNull(so3);
            Assert.Equal("null", so3.c);
        }
示例#17
0
        public void Initializer_Default_Set_By_Ctor()
        {
            // Arrange
            var config = new HttpConfiguration();

            // Assert
            Assert.NotNull(config.Initializer);
        }
示例#18
0
        public void ReadAsMultipartAsync_ThrowsOnWriteError()
        {
            HttpContent content   = CreateContent(ValidBoundary, "A", "B", "C");
            IOException exception = Assert.Throws <IOException>(() => content.ReadAsMultipartAsync(new WriteErrorStreamProvider()).Result);

            Assert.NotNull(exception.InnerException);
            Assert.Equal(ExceptionAsyncStreamMessage, exception.InnerException.Message);
        }
        public void ControllerContext_HasUrlHelperWithValidContext()
        {
            HttpControllerContext cc = new HttpControllerContext();

            Assert.NotNull(cc.Url);
            Assert.IsType <UrlHelper>(cc.Url);
            Assert.Same(cc, cc.Url.ControllerContext);
        }
示例#20
0
        public void ReadAsMultipartAsync_ThrowsOnBadStreamProvider()
        {
            HttpContent content = CreateContent(ValidBoundary, "A", "B", "C");
            InvalidOperationException exception = Assert.Throws <InvalidOperationException>(() => content.ReadAsMultipartAsync(new BadStreamProvider()).Result);

            Assert.NotNull(exception.InnerException);
            Assert.Equal(ExceptionStreamProviderMessage, exception.InnerException.Message);
        }
        private static void ValidateEntity(HttpContent content)
        {
            Assert.NotNull(content);
            Assert.Equal(ParserData.TextContentType, content.Headers.ContentType.ToString());
            string entity = content.ReadAsStringAsync().Result;

            Assert.Equal(ParserData.HttpMessageEntity, entity);
        }
示例#22
0
        public void TryReadQueryAsJsonSucceeds(Uri address)
        {
            JObject value;

            Assert.True(address.TryReadQueryAsJson(out value), "Expected 'true' as result");
            Assert.NotNull(value);
            Assert.IsType <JObject>(value);
        }
示例#23
0
        public void HandleUnauthorizedRequest_SetsResponseWithUnauthorizedStatusCode()
        {
            _attribute.HandleUnauthorizedRequestPublic(_actionContext);

            Assert.NotNull(_actionContext.Response);
            Assert.Equal(HttpStatusCode.Unauthorized, _actionContext.Response.StatusCode);
            Assert.Same(_request, _actionContext.Response.RequestMessage);
        }
        public void StaticComparer_Returns_SameInstance()
        {
            MediaTypeWithQualityHeaderValueComparer comparer1 = MediaTypeWithQualityHeaderValueComparer.QualityComparer;
            MediaTypeWithQualityHeaderValueComparer comparer2 = MediaTypeWithQualityHeaderValueComparer.QualityComparer;

            Assert.NotNull(comparer1);
            Assert.Same(comparer1, comparer2);
        }
示例#25
0
        public void StaticComparerReturnsSameInstance()
        {
            StringWithQualityHeaderValueComparer comparer1 = StringWithQualityHeaderValueComparer.QualityComparer;
            StringWithQualityHeaderValueComparer comparer2 = StringWithQualityHeaderValueComparer.QualityComparer;

            Assert.NotNull(comparer1);
            Assert.Same(comparer1, comparer2);
        }
        public void EqualityComparerReturnsMediaTypeHeadeValueEqualityComparer()
        {
            MediaTypeHeaderValueEqualityComparer comparer1 = MediaTypeHeaderValueEqualityComparer.EqualityComparer;
            MediaTypeHeaderValueEqualityComparer comparer2 = MediaTypeHeaderValueEqualityComparer.EqualityComparer;

            Assert.NotNull(comparer1);
            Assert.Same(comparer1, comparer2);
        }
示例#27
0
        public void Constructor()
        {
            MediaTypeFormatterCollection collection = new MediaTypeFormatterCollection();

            Assert.Equal(3, collection.Count);
            Assert.NotNull(collection.XmlFormatter);
            Assert.NotNull(collection.JsonFormatter);
            Assert.NotNull(collection.FormUrlEncodedFormatter);
        }
示例#28
0
        public void ResponseConstructor()
        {
            HttpResponseMessage response = new HttpResponseMessage();
            HttpMessageContent  instance = new HttpMessageContent(response);

            Assert.NotNull(instance);
            Assert.Same(response, instance.HttpResponseMessage);
            Assert.Null(instance.HttpRequestMessage);
        }
        public void Iterate_Generic_ExecutesNextTaskOnlyAfterPreviousTaskSucceeded()
        {
            Task <IEnumerable <int> > result = TaskHelpers.Iterate(SuccessTaskEnumerable_Generic());

            Assert.NotNull(result);
            result.WaitUntilCompleted();
            Assert.Equal(TaskStatus.RanToCompletion, result.Status);
            Assert.Equal(new[] { 42, 2112 }, result.Result);
        }
 private static void ValidateClones(MediaTypeHeaderValue clone1, MediaTypeHeaderValue clone2, string charset)
 {
     Assert.NotNull(clone1);
     Assert.NotNull(clone2);
     Assert.NotSame(clone1, clone2);
     Assert.Equal(clone1.MediaType, clone2.MediaType);
     Assert.Equal(charset, clone1.CharSet);
     Assert.Equal(charset, clone2.CharSet);
 }