Beispiel #1
0
        public void TryMatchMediaTypeThrowsWithNullUriInHttpRequestMessage(string uriPathExtension, string mediaType)
        {
            UriPathExtensionMapping mapping = new UriPathExtensionMapping(uriPathExtension, mediaType);
            string errorMessage             = RS.Format(Properties.Resources.NonNullUriRequiredForMediaTypeMapping, typeof(UriPathExtensionMapping).Name);

            Assert.Throws <InvalidOperationException>(() => mapping.TryMatchMediaType(new HttpRequestMessage()), errorMessage);
        }
        public void InvalidTypeCreationExpression()
        {
            // underminated string literal
            Assert.Throws <ParseException>(delegate
            {
                VerifyQueryDeserialization <DataTypes>("$filter=TimeSpanProp ge time'13:20:00", String.Empty);
            },
                                           "Parse error in $filter. Unterminated string literal (at index 29)");

            // use of parens rather than quotes
            Assert.Throws <ParseException>(delegate
            {
                VerifyQueryDeserialization <DataTypes>("$filter=TimeSpanProp ge time(13:20:00)", String.Empty);
            },
                                           "Parse error in $filter. Invalid 'time' type creation expression. (at index 16)");

            // verify the exception returned when type expression that isn't
            // one of the supported keyword types is used. In this case it falls
            // through as a member expression
            Assert.Throws <ParseException>(delegate
            {
                VerifyQueryDeserialization("$filter=math'123' eq true", String.Empty);
            },
                                           "Parse error in $filter. No property or field 'math' exists in type 'Product' (at index 0)");
        }
Beispiel #3
0
 public void Constructor_WhenValueIsNullAndTypeIsNotCompatible_ThrowsException()
 {
     Assert.Throws <InvalidOperationException>(() =>
     {
         new ObjectContent(typeof(int), null, new JsonMediaTypeFormatter());
     }, "The 'ObjectContent' type cannot accept a null value for the value type 'Int32'.");
 }
        public void GetStreamThrowsOnNoContentDisposition()
        {
            MultipartFormDataStreamProvider instance = new MultipartFormDataStreamProvider(Path.GetTempPath());
            HttpContent content = new StringContent("text");

            Assert.Throws <IOException>(() => { instance.GetStream(content.Headers); }, RS.Format(Properties.Resources.MultipartFormDataStreamProviderNoContentDisposition, "Content-Disposition"));
        }
Beispiel #5
0
        public void Invalid_Action_In_Route()
        {
            // Arrange
            ApiController api        = new UsersController();
            HttpRouteData route      = new HttpRouteData(new HttpRoute());
            string        actionName = "invalidOp";

            route.Values.Add("action", actionName);
            HttpControllerContext controllerContext = ContextUtil.CreateControllerContext(instance: api, routeData: route, request: new HttpRequestMessage()
            {
                Method = HttpMethod.Get
            });
            Type controllerType = typeof(UsersController);

            controllerContext.ControllerDescriptor = new HttpControllerDescriptor(controllerContext.Configuration, controllerType.Name, controllerType);
            controllerContext.Configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;

            // Act & Assert
            var exception = Assert.Throws <HttpResponseException>(() =>
            {
                HttpResponseMessage message = api.ExecuteAsync(controllerContext, CancellationToken.None).Result;
            });

            Assert.Equal(HttpStatusCode.NotFound, exception.Response.StatusCode);
            var content = Assert.IsType <ObjectContent <HttpError> >(exception.Response.Content);

            Assert.Equal("No action was found on the controller 'UsersController' that matches the name 'invalidOp'.",
                         ((HttpError)content.Value)["MessageDetail"]);
        }
 public void CreateResponse_OnNullConfiguration_ThrowsException()
 {
     Assert.Throws <InvalidOperationException>(() =>
     {
         HttpRequestMessageExtensions.CreateResponse(_request, HttpStatusCode.OK, _value, configuration: null);
     }, "The request does not have an associated configuration object or the provided configuration was null.");
 }
Beispiel #7
0
        public void TryMatchMediaTypeThrowsWithNullUriInHttpRequestMessage(string queryStringParameterName, string queryStringParameterValue, string mediaType)
        {
            QueryStringMapping mapping      = new QueryStringMapping(queryStringParameterName, queryStringParameterValue, mediaType);
            string             errorMessage = RS.Format(Properties.Resources.NonNullUriRequiredForMediaTypeMapping, typeof(QueryStringMapping).Name);

            Assert.Throws <InvalidOperationException>(() => mapping.TryMatchMediaType(new HttpRequestMessage()), errorMessage);
        }
Beispiel #8
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);
        }
Beispiel #9
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);
        }
Beispiel #10
0
        public void ReadAsMultipartAsync_ThrowsOnPrematureEndOfStream()
        {
            HttpContent content   = new StreamContent(Stream.Null);
            string      mediaType = String.Format("multipart/form-data; boundary=\"{0}\"", ValidBoundary);

            content.Headers.ContentType = MediaTypeHeaderValue.Parse(mediaType);
            Assert.Throws <IOException>(() => content.ReadAsMultipartAsync().Result);
        }
Beispiel #11
0
        public void WriteToStreamAsyncThrowsNotImplemented()
        {
            FormUrlEncodedMediaTypeFormatter formatter = new FormUrlEncodedMediaTypeFormatter();

            Assert.Throws <NotSupportedException>(
                () => formatter.WriteToStreamAsync(typeof(object), new object(), Stream.Null, null, null),
                "The media type formatter of type 'FormUrlEncodedMediaTypeFormatter' does not support writing because it does not implement the WriteToStreamAsync method.");
        }
Beispiel #12
0
        public void WriteToStreamAsync_ThrowsNotSupportedException()
        {
            var formatter = new Mock <MediaTypeFormatter> {
                CallBase = true
            }.Object;

            Assert.Throws <NotSupportedException>(() => formatter.WriteToStreamAsync(null, null, null, null, null),
                                                  "The media type formatter of type 'MediaTypeFormatterProxy' does not support writing because it does not implement the WriteToStreamAsync method.");
        }
 public void InvalidCharactersInQuery_TokenizerFails(char ch)
 {
     Assert.Throws <ParseException>(delegate
     {
         string filter = String.Format("2 {0} 3", ch);
         VerifyQueryDeserialization <DataTypes>("$filter=" + Uri.EscapeDataString(filter), String.Empty);
     },
                                    String.Format("Parse error in $filter. Syntax error '{0}' (at index 2)", ch));
 }
        public void CreateResponse_WhenNoContentNegotiatorInstanceRegistered_Throws()
        {
            // Arrange
            _config.ServiceResolver.SetServices(typeof(IContentNegotiator), new object[] { null });

            // Act & Assert
            Assert.Throws <InvalidOperationException>(() => HttpRequestMessageExtensions.CreateResponse(_request, HttpStatusCode.OK, _value, _config),
                                                      "The provided configuration does not have an instance of the 'System.Net.Http.Formatting.IContentNegotiator' service registered.");
        }
        public void FirstDispositionNameNoMatch()
        {
            IEnumerable <HttpContent> content = HttpContentCollectionExtensionsTests.CreateContent();

            Assert.Null(content.FirstDispositionNameOrDefault(noMatchDispositionName));

            ClearHeaders(content);
            Assert.Throws <InvalidOperationException>(() => content.FirstDispositionName(noMatchDispositionName));
        }
Beispiel #16
0
        public void ReadAsMultipartAsync_ReadOnlyStream_Throws()
        {
            HttpContent content = CreateContent("--", "A", "B", "C");

            Assert.Throws <InvalidOperationException>(
                () => content.ReadAsMultipartAsync(new ReadOnlyStreamProvider()).Result,
                "The stream provider of type 'ReadOnlyStreamProvider' returned a read-only stream. It must return a writable 'Stream' instance."
                );
        }
        public void ReadAsHttpRequestMessageAsync_NoHostHeader_ThrowsIOException()
        {
            string[] request = new[] {
                @"GET / HTTP/1.1",
            };

            HttpContent content = CreateContent(true, request, null);

            Assert.Throws <IOException>(() => content.ReadAsHttpRequestMessageAsync().Result);
        }
        public void RunSynchronously_Cancels()
        {
            CancellationTokenSource cts = new CancellationTokenSource();

            cts.Cancel();

            Task t = TaskHelpers.RunSynchronously(() => { throw new InvalidOperationException(); }, cts.Token);

            Assert.Throws <TaskCanceledException>(() => t.Wait());
        }
        public void SimpleDisplayNameWithUnknownDisplayColumnThrows()
        {
            // Arrange
            var provider = new CachedDataAnnotationsModelMetadataProvider();

            // Act & Assert
            Assert.Throws <InvalidOperationException>(
                () => provider.GetMetadataForType(() => new UnknownDisplayColumnModel(), typeof(UnknownDisplayColumnModel)).SimpleDisplayText,
                typeof(UnknownDisplayColumnModel).FullName + " has a DisplayColumn attribute for NoPropertyWithThisName, but property NoPropertyWithThisName does not exist.");
        }
Beispiel #20
0
        public void ReadAsMultipartAsync_ThrowsOnReadError()
        {
            HttpContent content   = new StreamContent(new ReadErrorStream());
            string      mediaType = String.Format("multipart/form-data; boundary=\"{0}\"", ValidBoundary);

            content.Headers.ContentType = MediaTypeHeaderValue.Parse(mediaType);
            IOException exception = Assert.Throws <IOException>(() => content.ReadAsMultipartAsync().Result);

            Assert.NotNull(exception.InnerException);
            Assert.Equal(ExceptionAsyncStreamMessage, exception.InnerException.Message);
        }
Beispiel #21
0
        public void ConvertToThrowsIfNoConverterExists()
        {
            // Arrange
            ValueProviderResult vpr = new ValueProviderResult("x", null, CultureInfo.InvariantCulture);
            Type destinationType    = typeof(MyClassWithoutConverter);

            // Act & Assert
            Assert.Throws <InvalidOperationException>(
                delegate { vpr.ConvertTo(destinationType); },
                "The parameter conversion from type 'System.String' to type 'System.Web.Mvc.Test.ValueProviderResultTest+MyClassWithoutConverter' failed because no type converter can convert between these types.");
        }
Beispiel #22
0
        public void SelectCharacterEncoding_ThrowsIfNoSupportedEncodings()
        {
            // Arrange
            MockMediaTypeFormatter formatter = new MockMediaTypeFormatter {
                CallBase = true
            };
            HttpContent content = new StringContent("Hello World", Encoding.UTF8, "text/plain");

            // Act
            Assert.Throws <InvalidOperationException>(() => formatter.SelectCharacterEncoding(content.Headers));
        }
Beispiel #23
0
        public void ReadAsHttpRequestMessageAsync_TwoHostHeaders_Throws()
        {
            string[] request = new[] {
                @"GET / HTTP/1.1",
                @"Host: somehost.com",
                @"Host: otherhost.com",
            };

            HttpContent content = CreateContent(true, request, null);

            Assert.Throws <InvalidOperationException>(() => content.ReadAsHttpRequestMessageAsync().Result);
        }
Beispiel #24
0
        public void ReadAsMultipartAsync_WriteErrorOnStream_Throws()
        {
            HttpContent content = CreateContent("--", "A", "B", "C");

            var ioException = Assert.Throws <IOException>(
                () => content.ReadAsMultipartAsync(new WriteErrorStreamProvider()).Result,
                "Error writing MIME multipart body part to output stream."
                );

            Assert.NotNull(ioException.InnerException);
            Assert.Equal(ExceptionAsyncStreamMessage, ioException.InnerException.Message);
        }
Beispiel #25
0
        public void ReadAsMultipartAsync_WithBadStreamProvider_Throws()
        {
            HttpContent content = CreateContent("--", "A", "B", "C");

            var invalidOperationException = Assert.Throws <InvalidOperationException>(
                () => content.ReadAsMultipartAsync(new BadStreamProvider()).Result,
                "The stream provider of type 'BadStreamProvider' threw an exception."
                );

            Assert.NotNull(invalidOperationException.InnerException);
            Assert.Equal(ExceptionStreamProviderMessage, invalidOperationException.InnerException.Message);
        }
        public void UseDataContractJsonSerializer_True_Indent_Throws()
        {
            DataContractJsonMediaTypeFormatter jsonFormatter = new DataContractJsonMediaTypeFormatter {
                Indent = true
            };
            MemoryStream memoryStream = new MemoryStream();
            HttpContent  content      = new StringContent(String.Empty);

            Assert.Throws <NotSupportedException>(
                () => jsonFormatter.WriteToStreamAsync(typeof(XmlMediaTypeFormatterTests.SampleType),
                                                       new XmlMediaTypeFormatterTests.SampleType(),
                                                       memoryStream, content, transportContext: null));
        }
Beispiel #27
0
        public void ReadAsHttpResponseMessageAsync_Throws_TheHeaderSizeExceededTheDefaultLimit()
        {
            string[] response = new[] {
                @"HTTP/1.1 200 OK",
                String.Format("Set-Cookie: {0}={1}", new String('a', 16 * 1024), new String('b', 16 * 1024))
            };

            Assert.Throws <InvalidOperationException>(() =>
            {
                HttpContent content = CreateContent(false, response, "sample body");
                HttpResponseMessage httpResponse = content.ReadAsHttpResponseMessageAsync().Result;
            });
        }
Beispiel #28
0
        public void Constructor_WhenValueIsNotSupportedByFormatter_ThrowsException()
        {
            Mock <MediaTypeFormatter> formatterMock = new Mock <MediaTypeFormatter>();

            formatterMock.Setup(f => f.CanWriteType(typeof(List <string>))).Returns(false).Verifiable();

            Assert.Throws <InvalidOperationException>(() =>
            {
                new ObjectContent(typeof(List <string>), new List <string>(), formatterMock.Object);
            }, "The configured formatter 'Castle.Proxies.MediaTypeFormatterProxy' cannot write an object of type 'List`1'.");

            formatterMock.Verify();
        }
        public void GetFacebookCookieInfoThrowsIfCookieIsNotValid()
        {
            // Arrange

            var context = CreateHttpContext(new Dictionary <string, string>
            {
                { "fbs_myapp'", "sig=malformed-signature&name=foo&val=bar&uid=MyFacebookName" },
                { "fbs_uid", "MyFacebookName" },
            });

            // Act and Assert
            Assert.Throws <InvalidOperationException>(() => Facebook.GetFacebookCookieInfo(context, "uid"), "Invalid Facebook cookie.");
        }
Beispiel #30
0
        public void ReadAsMultipartAsync_PrematureEndOfStream_Throws()
        {
            HttpContent content     = new StreamContent(Stream.Null);
            var         contentType = new MediaTypeHeaderValue("multipart/form-data");

            contentType.Parameters.Add(new NameValueHeaderValue("boundary", "\"{--\""));
            content.Headers.ContentType = contentType;

            Assert.Throws <IOException>(
                () => content.ReadAsMultipartAsync().Result,
                "Unexpected end of MIME multipart stream. MIME multipart message is not complete."
                );
        }