public void MatchAcceptHeader_ReturnsMatch(string[] acceptHeaders, string[] supportedMediaTypes, string expectedMediaType, double expectedQuality, int ranking)
        {
            // Arrange
            MockContentNegotiator negotiator = new MockContentNegotiator();

            List <MediaTypeWithQualityHeaderValue>        unsortedAcceptHeaders = acceptHeaders.Select(a => MediaTypeWithQualityHeaderValue.Parse(a)).ToList();
            IEnumerable <MediaTypeWithQualityHeaderValue> sortedAcceptHeaders   = negotiator.SortMediaTypeWithQualityHeaderValuesByQFactor(unsortedAcceptHeaders);

            MockMediaTypeFormatter formatter = new MockMediaTypeFormatter();

            foreach (string supportedMediaType in supportedMediaTypes)
            {
                formatter.SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse(supportedMediaType));
            }

            // Act
            MediaTypeFormatterMatch match = negotiator.MatchAcceptHeader(sortedAcceptHeaders, formatter);

            // Assert
            if (expectedMediaType == null)
            {
                Assert.Null(match);
            }
            else
            {
                Assert.Same(formatter, match.Formatter);
                Assert.Equal(MediaTypeHeaderValue.Parse(expectedMediaType), match.MediaType);
                Assert.Equal(expectedQuality, match.Quality);
                Assert.Equal(ranking, (int)match.Ranking);
            }
        }
Example #2
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);
                }
            }
        }
        public void MatchType_ReturnsMatch(bool excludeMatchOnTypeOnly, string[] supportedMediaTypes, string expectedMediaType)
        {
            // Arrange
            MockContentNegotiator negotiator = new MockContentNegotiator(excludeMatchOnTypeOnly);

            MockMediaTypeFormatter formatter = new MockMediaTypeFormatter();

            foreach (string supportedMediaType in supportedMediaTypes)
            {
                formatter.SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse(supportedMediaType));
            }

            // Act
            MediaTypeFormatterMatch match = negotiator.MatchType(typeof(object), formatter);

            // Assert
            if (expectedMediaType == null)
            {
                Assert.Null(match);
            }
            else
            {
                Assert.Same(formatter, match.Formatter);
                Assert.Equal(MediaTypeHeaderValue.Parse(expectedMediaType), match.MediaType);
                Assert.Equal(1.0, match.Quality);
                Assert.Equal(MediaTypeFormatterMatchRanking.MatchOnCanWriteType, match.Ranking);
            }
        }
        public void MatchRequestMediaType_ReturnsMatch(string requestMediaType, string[] supportedMediaTypes, string expectedMediaType)
        {
            // Arrange
            MockContentNegotiator negotiator = new MockContentNegotiator();

            HttpRequestMessage request = new HttpRequestMessage();

            request.Content = new StringContent(String.Empty);
            request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse(requestMediaType);

            MockMediaTypeFormatter formatter = new MockMediaTypeFormatter();

            foreach (string supportedMediaType in supportedMediaTypes)
            {
                formatter.SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse(supportedMediaType));
            }

            // Act
            MediaTypeFormatterMatch match = negotiator.MatchRequestMediaType(request, formatter);

            // Assert
            if (expectedMediaType == null)
            {
                Assert.Null(match);
            }
            else
            {
                Assert.Same(formatter, match.Formatter);
                Assert.Equal(MediaTypeHeaderValue.Parse(expectedMediaType), match.MediaType);
                Assert.Equal(1.0, match.Quality);
                Assert.Equal(MediaTypeFormatterMatchRanking.MatchOnRequestMediaType, match.Ranking);
            }
        }
Example #5
0
        public Task SendAsync_SetsGenericPrincipalWhenThreadPrincipalIsNullAndCleansUpAfterward()
        {
            // Arrange
            var        config            = new HttpConfiguration();
            var        request           = new HttpRequestMessage();
            var        dispatcherMock    = new Mock <HttpControllerDispatcher>(config);
            var        server            = new HttpServer(config, dispatcherMock.Object);
            var        invoker           = new HttpMessageInvoker(server);
            IPrincipal callbackPrincipal = null;

            Thread.CurrentPrincipal = null;
            dispatcherMock.Protected()
            .Setup <Task <HttpResponseMessage> >("SendAsync", request, CancellationToken.None)
            .Callback(() => callbackPrincipal = Thread.CurrentPrincipal)
            .Returns(TaskHelpers.FromResult <HttpResponseMessage>(request.CreateResponse()));

            // Act
            return(invoker.SendAsync(request, CancellationToken.None)
                   .ContinueWith(req =>
            {
                // Assert
                Assert.NotNull(callbackPrincipal);
                Assert.False(callbackPrincipal.Identity.IsAuthenticated);
                Assert.Empty(callbackPrincipal.Identity.Name);
                Assert.Null(Thread.CurrentPrincipal);
            }));
        }
Example #6
0
        public void OnAuthorization_IfUserIsAuthenticated_DoesNotShortCircuitRequest()
        {
            _principalMock.Setup(p => p.Identity.IsAuthenticated).Returns(true);

            _attribute.OnAuthorization(_actionContext);

            Assert.Null(_actionContext.Response);
        }
        public void DisplayFormatAttributetSetsNullDisplayText()
        {
            // Arrange
            var provider = new CachedDataAnnotationsModelMetadataProvider();

            // Act & Assert
            Assert.Null(provider.GetMetadataForProperty(null, typeof(DisplayFormatModel), "NoAttribute").NullDisplayText);
            Assert.Equal("(null value)", provider.GetMetadataForProperty(null, typeof(DisplayFormatModel), "NullDisplayText").NullDisplayText);
        }
Example #8
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 FirstDispositionTypeOrDefaultNoMatch()
        {
            IEnumerable <HttpContent> content = HttpContentCollectionExtensionsTests.CreateContent();

            Assert.Null(content.FirstDispositionTypeOrDefault(noMatchDispositionType));

            ClearHeaders(content);
            Assert.Null(content.FirstDispositionTypeOrDefault(noMatchDispositionType));
        }
        public void FirstDispositionNameNoMatch()
        {
            IEnumerable <HttpContent> content = HttpContentCollectionExtensionsTests.CreateContent();

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

            ClearHeaders(content);
            Assert.Throws <InvalidOperationException>(() => content.FirstDispositionName(noMatchDispositionName));
        }
Example #11
0
        public void RemoveSetsJsonFormatter()
        {
            MediaTypeFormatterCollection collection = new MediaTypeFormatterCollection();
            int count = collection.Count;

            collection.Remove(collection.JsonFormatter);
            Assert.Null(collection.JsonFormatter);
            Assert.Equal(count - 1, collection.Count);
        }
        public void DisplayFormatAttributeSetEditFormatString()
        {
            // Arrange
            var provider = new CachedDataAnnotationsModelMetadataProvider();

            // Act & Assert
            Assert.Null(provider.GetMetadataForProperty(null, typeof(DisplayFormatModel), "NoAttribute").EditFormatString);
            Assert.Null(provider.GetMetadataForProperty(null, typeof(DisplayFormatModel), "DisplayFormatString").EditFormatString);
            Assert.Equal("Data {0} format", provider.GetMetadataForProperty(null, typeof(DisplayFormatModel), "DisplayAndEditFormatString").EditFormatString);
        }
        public void WatermarkTests()
        {
            // Arrange
            var provider = new CachedDataAnnotationsModelMetadataProvider();

            // Act & Assert
            Assert.Null(provider.GetMetadataForProperty(null, typeof(DisplayModel), "NoAttribute").Watermark);
            Assert.Null(provider.GetMetadataForProperty(null, typeof(DisplayModel), "PromptNotSet").Watermark);
            Assert.Equal("Enter stuff here", provider.GetMetadataForProperty(null, typeof(DisplayModel), "PromptSet").Watermark);
        }
        public void DataTypeAttributeSetsDataTypeName()
        {
            // Arrange
            var provider = new CachedDataAnnotationsModelMetadataProvider();

            // Act & Assert
            Assert.Null(provider.GetMetadataForProperty(null, typeof(DataTypeModel), "NoAttribute").DataTypeName);
            Assert.Equal("EmailAddress", provider.GetMetadataForProperty(null, typeof(DataTypeModel), "EmailAddressProperty").DataTypeName);
            Assert.Equal("CustomDataType", provider.GetMetadataForProperty(null, typeof(DataTypeModel), "CustomDataTypeProperty").DataTypeName);
        }
        public void ShortDisplayNameTests()
        {
            // Arrange
            var provider = new CachedDataAnnotationsModelMetadataProvider();

            // Act & Assert
            Assert.Null(provider.GetMetadataForProperty(null, typeof(DisplayModel), "NoAttribute").ShortDisplayName);
            Assert.Null(provider.GetMetadataForProperty(null, typeof(DisplayModel), "ShortNameNotSet").ShortDisplayName);
            Assert.Equal("Short name", provider.GetMetadataForProperty(null, typeof(DisplayModel), "ShortNameSet").ShortDisplayName);
        }
        public void DescriptionTests()
        {
            // Arrange
            var provider = new CachedDataAnnotationsModelMetadataProvider();

            // Act & Assert
            Assert.Null(provider.GetMetadataForProperty(null, typeof(DisplayModel), "NoAttribute").Description);
            Assert.Null(provider.GetMetadataForProperty(null, typeof(DisplayModel), "DescriptionNotSet").Description);
            Assert.Equal("Description text", provider.GetMetadataForProperty(null, typeof(DisplayModel), "DescriptionSet").Description);
        }
Example #17
0
        public void OnAuthorization_IfUserIsInUsersCollection_DoesNotShortCircuitRequest()
        {
            _attribute.Users = " John , Mary ";
            _principalMock.Setup(p => p.Identity.IsAuthenticated).Returns(true).Verifiable();
            _principalMock.Setup(p => p.Identity.Name).Returns("Mary").Verifiable();

            _attribute.OnAuthorization(_actionContext);

            Assert.Null(_actionContext.Response);
            _principalMock.Verify();
        }
        public void DataTypeInfluencedByDisplayFormatAttributeHtmlEncode()
        {
            // Arrange
            var provider = new CachedDataAnnotationsModelMetadataProvider();

            // Act & Assert
            Assert.Null(provider.GetMetadataForProperty(null, typeof(DisplayFormatModel), "NoAttribute").DataTypeName);
            Assert.Null(provider.GetMetadataForProperty(null, typeof(DisplayFormatModel), "HtmlEncodeTrue").DataTypeName);
            Assert.Equal("Html", provider.GetMetadataForProperty(null, typeof(DisplayFormatModel), "HtmlEncodeFalse").DataTypeName);
            Assert.Equal("Currency", provider.GetMetadataForProperty(null, typeof(DisplayFormatModel), "HtmlEncodeFalseWithDataType").DataTypeName);
        }
        public void UrlEncodeToBytesThrowsOnInvalidArgs()
        {
            Assert.Null(UriQueryUtility.UrlEncodeToBytes(null, 0, 0));
            Assert.ThrowsArgumentNull(() => UriQueryUtility.UrlEncodeToBytes(null, 0, 2), "bytes");

            Assert.ThrowsArgumentOutOfRange(() => UriQueryUtility.UrlEncodeToBytes(new byte[0], -1, 0), "offset", null);
            Assert.ThrowsArgumentOutOfRange(() => UriQueryUtility.UrlEncodeToBytes(new byte[0], 2, 0), "offset", null);

            Assert.ThrowsArgumentOutOfRange(() => UriQueryUtility.UrlEncodeToBytes(new byte[0], 0, -1), "count", null);
            Assert.ThrowsArgumentOutOfRange(() => UriQueryUtility.UrlEncodeToBytes(new byte[0], 0, 2), "count", null);
        }
Example #20
0
        public void ConvertToReturnsNullIfValueIsNull()
        {
            // Arrange
            ValueProviderResult vpr = new ValueProviderResult(null /* rawValue */, null /* attemptedValue */, CultureInfo.InvariantCulture);

            // Act
            object outValue = vpr.ConvertTo(typeof(int[]));

            // Assert
            Assert.Null(outValue);
        }
Example #21
0
        public void ConvertToReturnsNullIfTrimmedValueIsEmptyString()
        {
            // Arrange
            ValueProviderResult vpr = new ValueProviderResult(" \t \r\n ", null, CultureInfo.InvariantCulture);

            // Act
            object outValue = vpr.ConvertTo(typeof(int));

            // Assert
            Assert.Null(outValue);
        }
Example #22
0
        public void ConvertToReturnsNullIfTryingToConvertEmptyArrayToSingleElement()
        {
            // Arrange
            ValueProviderResult vpr = new ValueProviderResult(new int[0], "", CultureInfo.InvariantCulture);

            // Act
            object outValue = vpr.ConvertTo(typeof(int));

            // Assert
            Assert.Null(outValue);
        }
Example #23
0
        public void ConvertToReturnsNullIfArrayElementValueIsNull()
        {
            // Arrange
            ValueProviderResult vpr = new ValueProviderResult(new string[] { null }, null, CultureInfo.InvariantCulture);

            // Act
            object outValue = vpr.ConvertTo(typeof(int));

            // Assert
            Assert.Null(outValue);
        }
        public void GetMetadataForTypeSetsTypeWithNullPropertyName()
        {
            // Arrange
            var provider = new CachedDataAnnotationsModelMetadataProvider();

            // Act
            ModelMetadata result = provider.GetMetadataForType(null, typeof(string));

            // Assert
            Assert.Equal(typeof(string), result.ModelType);
            Assert.Null(result.PropertyName);
        }
Example #25
0
        public void ConstructorWithUserNullDependencyResolver()
        {
            // Arrange
            HttpConfiguration  config   = new HttpConfiguration();
            DependencyResolver resolver = new DependencyResolver(config, null);

            // Act
            object service = resolver.GetService(typeof(IHttpActionSelector));

            // Assert
            Assert.Null(service);
        }
        public void DisplayNameTests()
        {
            // Arrange
            var provider = new CachedDataAnnotationsModelMetadataProvider();

            // Act & Assert
            Assert.Null(provider.GetMetadataForProperty(null, typeof(DisplayModel), "NoAttribute").DisplayName);
            Assert.Equal("Value from DisplayName", provider.GetMetadataForProperty(null, typeof(DisplayModel), "DisplayNameAttributeNoDisplayAttribute").DisplayName);
            Assert.Null(provider.GetMetadataForProperty(null, typeof(DisplayModel), "DisplayAttributeNameNotSet").DisplayName);
            Assert.Equal("Non empty name", provider.GetMetadataForProperty(null, typeof(DisplayModel), "DisplayAttributeNonEmptyName").DisplayName);
            Assert.Equal("Value from DisplayName", provider.GetMetadataForProperty(null, typeof(DisplayModel), "BothAttributesNameNotSet").DisplayName);
            Assert.Equal("Value from Display", provider.GetMetadataForProperty(null, typeof(DisplayModel), "BothAttributes").DisplayName);
        }
        public void TryGetValueReturnsFalse()
        {
            // Arrange
            IDictionary <string, object> dict = new Dictionary <string, object>();

            // Act
            string resultValue = null;
            bool   result      = dict.TryGetValue("notfound", out resultValue);

            // Assert
            Assert.False(result);
            Assert.Null(resultValue);
        }
Example #28
0
        public void SelectResponseMediaTypeMatchesType()
        {
            MockMediaTypeFormatter formatter = new MockMediaTypeFormatter()
            {
                CallBase = true
            };
            HttpRequestMessage     request = new HttpRequestMessage();
            ResponseMediaTypeMatch match   = formatter.SelectResponseMediaType(typeof(string), request);

            Assert.NotNull(match);
            Assert.Equal(ResponseFormatterSelectionResult.MatchOnCanWriteType, match.ResponseFormatterSelectionResult);
            Assert.Null(match.MediaTypeMatch.MediaType);
        }
        public void UIHintAttributeSetsTemplateHint()
        {
            // Arrange
            var provider = new CachedDataAnnotationsModelMetadataProvider();

            // Act & Assert
            Assert.Null(provider.GetMetadataForProperty(null, typeof(UIHintModel), "NoAttribute").TemplateHint);
            Assert.Equal("MyCustomTemplate", provider.GetMetadataForProperty(null, typeof(UIHintModel), "DefaultUIHint").TemplateHint);
            Assert.Equal("MyMvcTemplate", provider.GetMetadataForProperty(null, typeof(UIHintModel), "MvcUIHint").TemplateHint);
            Assert.Null(provider.GetMetadataForProperty(null, typeof(UIHintModel), "NoMvcUIHint").TemplateHint);

            Assert.Equal("MyMvcTemplate", provider.GetMetadataForProperty(null, typeof(UIHintModel), "MultipleUIHint").TemplateHint);
        }
Example #30
0
        public void GetServiceDoesntEagerlyCreate()
        {
            // Arrange
            HttpConfiguration  config   = new HttpConfiguration();
            DependencyResolver resolver = new DependencyResolver(config);

            // Act
            object result = resolver.GetService(typeof(SomeClass));

            // Assert
            // Service resolver should not have created an instance or arbitrary class.
            Assert.Null(result);
        }