Beispiel #1
1
        public void CanRead_ReturnsTrueForAnySupportedContentType(string requestContentType, bool expectedCanRead)
        {
            // Arrange
            var loggerMock = GetLogger();

            var formatter =
                new JsonInputFormatter(loggerMock, _serializerSettings, ArrayPool<char>.Shared, _objectPoolProvider);
            var contentBytes = Encoding.UTF8.GetBytes("content");

            var httpContext = GetHttpContext(contentBytes, contentType: requestContentType);
            var provider = new EmptyModelMetadataProvider();
            var metadata = provider.GetMetadataForType(typeof(string));
            var formatterContext = new InputFormatterContext(
                httpContext,
                modelName: string.Empty,
                modelState: new ModelStateDictionary(),
                metadata: metadata,
                readerFactory: new TestHttpRequestStreamReaderFactory().CreateReader);

            // Act
            var result = formatter.CanRead(formatterContext);

            // Assert
            Assert.Equal(expectedCanRead, result);
        }
        public void OnActionExecuting_ChangesActionResult_IfUnsupportedContentTypeExceptionIsFoundOnModelState()
        {
            // Arrange
            var context = new ActionExecutingContext(
                new ActionContext
                {
                    HttpContext = new DefaultHttpContext(),
                    RouteData = new RouteData(),
                    ActionDescriptor = new ActionDescriptor()
                },
                new List<IFilterMetadata>(),
                new Dictionary<string, object>(),
                new object());

            var modelMetadata = new EmptyModelMetadataProvider()
                .GetMetadataForType(typeof(int));

            context.ModelState.AddModelError(
                "person.body",
                new UnsupportedContentTypeException("error"),
                modelMetadata);

            var filter = new UnsupportedContentTypeFilter();

            // Act
            filter.OnActionExecuting(context);

            // Assert
            Assert.NotNull(context.Result);
            var status = Assert.IsType<UnsupportedMediaTypeResult>(context.Result);
        }
        public void AddModelError_WithErrorString_AddsTooManyModelErrors_WhenMaxErrorsIsReached()
        {
            // Arrange
            var expected = "The maximum number of allowed model errors has been reached.";
            var dictionary = new ModelStateDictionary
            {
                MaxAllowedErrors = 5
            };
            var provider = new EmptyModelMetadataProvider();
            var metadata = provider.GetMetadataForProperty(typeof(string), nameof(string.Length));
            dictionary.AddModelError("key1", "error1");
            dictionary.AddModelError("key2", new Exception(), metadata);
            dictionary.AddModelError("key3", new Exception(), metadata);
            dictionary.AddModelError("key4", "error4");
            dictionary.AddModelError("key5", "error5");

            // Act and Assert
            Assert.True(dictionary.HasReachedMaxErrors);
            Assert.Equal(5, dictionary.ErrorCount);
            var error = Assert.Single(dictionary[string.Empty].Errors);
            Assert.IsType<TooManyModelErrorsException>(error.Exception);
            Assert.Equal(expected, error.Exception.Message);

            // TooManyModelErrorsException added instead of key5 error.
            Assert.DoesNotContain("key5", dictionary.Keys);
        }
        public async Task JsonPatchInputFormatter_ReadsMultipleOperations_Successfully()
        {
            // Arrange
            var logger = GetLogger();
            var formatter = new JsonPatchInputFormatter(logger);
            var content = "[{\"op\": \"add\", \"path\" : \"Customer/Name\", \"value\":\"John\"}," +
                "{\"op\": \"remove\", \"path\" : \"Customer/Name\"}]";
            var contentBytes = Encoding.UTF8.GetBytes(content);

            var modelState = new ModelStateDictionary();
            var httpContext = GetHttpContext(contentBytes);
            var provider = new EmptyModelMetadataProvider();
            var metadata = provider.GetMetadataForType(typeof(JsonPatchDocument<Customer>));
            var context = new InputFormatterContext(
                httpContext,
                modelName: string.Empty,
                modelState: modelState,
                metadata: metadata,
                readerFactory: new TestHttpRequestStreamReaderFactory().CreateReader);

            // Act
            var result = await formatter.ReadAsync(context);

            // Assert
            Assert.False(result.HasError);
            var patchDoc = Assert.IsType<JsonPatchDocument<Customer>>(result.Model);
            Assert.Equal("add", patchDoc.Operations[0].op);
            Assert.Equal("Customer/Name", patchDoc.Operations[0].path);
            Assert.Equal("John", patchDoc.Operations[0].value);
            Assert.Equal("remove", patchDoc.Operations[1].op);
            Assert.Equal("Customer/Name", patchDoc.Operations[1].path);
        }
        public StringLengthAdapterTests()
        {
            adapter = new StringLengthAdapter(new StringLengthAttribute(128));
            IModelMetadataProvider provider = new EmptyModelMetadataProvider();
            ModelMetadata metadata = provider.GetMetadataForProperty(typeof(AdaptersModel), "StringLength");

            context = new ModelValidationContextBase(new ActionContext(), metadata, provider);
        }
 public EqualToAdapterTests()
 {
     attributes = new Dictionary<String, String>();
     adapter = new EqualToAdapter(new EqualToAttribute("StringLength"));
     IModelMetadataProvider provider = new EmptyModelMetadataProvider();
     ModelMetadata metadata = provider.GetMetadataForProperty(typeof(AdaptersModel), "EqualTo");
     context = new ClientModelValidationContext(new ActionContext(), metadata, provider, attributes);
 }
 public FileSizeAdapterTests()
 {
     attributes = new Dictionary<String, String>();
     adapter = new FileSizeAdapter(new FileSizeAttribute(12.25));
     IModelMetadataProvider provider = new EmptyModelMetadataProvider();
     ModelMetadata metadata = provider.GetMetadataForProperty(typeof(AdaptersModel), "FileSize");
     context = new ClientModelValidationContext(new ActionContext(), metadata, provider, attributes);
 }
        public void GetBinder_ForNotStringReturnsNull()
        {
            IModelMetadataProvider provider = new EmptyModelMetadataProvider();
            ModelBinderProviderContext context = Substitute.For<ModelBinderProviderContext>();
            context.Metadata.Returns(provider.GetMetadataForProperty(typeof(ProviderModel), "Date"));

            Assert.Null(new TrimmingModelBinderProvider().GetBinder(context));
        }
        public void CreateValidators_DoesNotCreate()
        {
            ModelMetadata metadata = new EmptyModelMetadataProvider().GetMetadataForType(typeof(String));
            ClientValidatorProviderContext context = new ClientValidatorProviderContext(metadata, new List<ClientValidatorItem>());

            new DateValidatorProvider().CreateValidators(context);

            Assert.Empty(context.Results);
        }
Beispiel #10
0
        public void ModelType_UsesDeclaredType_WhenModelIsNull()
        {
            // Arrange
            var provider = new EmptyModelMetadataProvider();
            var modelExplorer = provider.GetModelExplorerForType(typeof(BaseClass), model: null);

            // Act
            var modelType = modelExplorer.ModelType;

            // Assert
            Assert.Equal(typeof(BaseClass), modelType);
        }
        public void CreateValidators_ForDate(Type type)
        {
            ModelMetadata metadata = new EmptyModelMetadataProvider().GetMetadataForType(type);
            ClientValidatorProviderContext context = new ClientValidatorProviderContext(metadata, new List<ClientValidatorItem>());

            new DateValidatorProvider().CreateValidators(context);

            ClientValidatorItem actual = context.Results.Single();

            Assert.IsType<DateValidator>(actual.Validator);
            Assert.Null(actual.ValidatorMetadata);
            Assert.True(actual.IsReusable);
        }
        public void AddValidation_Date()
        {
            IModelMetadataProvider provider = new EmptyModelMetadataProvider();
            ModelMetadata metadata = provider.GetMetadataForType(typeof(DateTime));
            Dictionary<String, String> attributes = new Dictionary<String, String>();
            ClientModelValidationContext context = new ClientModelValidationContext(new ActionContext(), metadata, provider, attributes);

            new DateValidator().AddValidation(context);

            Assert.Equal(2, attributes.Count);
            Assert.Equal("true", attributes["data-val"]);
            Assert.Equal(String.Format(Validations.Date, "DateTime"), attributes["data-val-date"]);
        }
        public async Task BindModelAsync_NoValue()
        {
            ModelMetadata metadata = new EmptyModelMetadataProvider().GetMetadataForType(typeof(String));
            context.ValueProvider.GetValue(context.ModelName).Returns(ValueProviderResult.None);
            context.ModelMetadata = metadata;

            await binder.BindModelAsync(context);

            ModelBindingResult expected = new ModelBindingResult();
            ModelBindingResult actual = context.Result;

            Assert.Equal(expected, actual);
        }
        public void GetErrorMessage_Range()
        {
            IModelMetadataProvider provider = new EmptyModelMetadataProvider();
            RangeAdapter adapter = new RangeAdapter(new RangeAttribute(4, 128));
            ModelMetadata metadata = provider.GetMetadataForProperty(typeof(AdaptersModel), "Range");
            ModelValidationContextBase context = new ModelValidationContextBase(new ActionContext(), metadata, provider);

            String expected = String.Format(Validations.Range, "Range", 4, 128);
            String actual = adapter.GetErrorMessage(context);

            Assert.Equal(Validations.Range, adapter.Attribute.ErrorMessage);
            Assert.Equal(expected, actual);
        }
Beispiel #15
0
        public void GetPropertyExplorer_DeferredModelAccess_ContainerModelIsNull()
        {
            // Arrange
            var provider = new EmptyModelMetadataProvider();
            var modelExplorer = provider.GetModelExplorerForType(typeof(BaseClass), model: null);

            var propertyExplorer = modelExplorer.GetExplorerForProperty("Base1");

            // Act
            var propertyValue = propertyExplorer.Model;

            // Assert
            Assert.Null(propertyValue);
        }
        private static ViewContext MakeViewContext(HttpContext httpContext)
        {
            var actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor());
            var metadataProvider = new EmptyModelMetadataProvider();
            var viewData = new ViewDataDictionary(metadataProvider);
            var viewContext = new ViewContext(
                actionContext,
                Mock.Of<IView>(),
                viewData,
                Mock.Of<ITempDataDictionary>(),
                TextWriter.Null,
                new HtmlHelperOptions());

            return viewContext;
        }
        public void GetSimpleDisplayText_WithoutSimpleDisplayProperty(
            object model,
            Type modelType,
            string expectedResult)
        {
            // Arrange
            var provider = new EmptyModelMetadataProvider();
            var modelExplorer = provider.GetModelExplorerForType(modelType, model);

            // Act
            var result = modelExplorer.GetSimpleDisplayText();

            // Assert
            Assert.Equal(expectedResult, result);
        }
        public async Task BindModelAsync_Trimmed()
        {
            ModelMetadata metadata = new EmptyModelMetadataProvider().GetMetadataForProperty(typeof(AllTypesView), "StringField");
            context.ValueProvider.GetValue("StringField").Returns(new ValueProviderResult(" Value "));
            context.ModelName = "StringField";
            context.ModelMetadata = metadata;

            await binder.BindModelAsync(context);

            ModelBindingResult expected = ModelBindingResult.Success("Value");
            ModelBindingResult actual = context.Result;

            Assert.Equal(expected.IsModelSet, actual.IsModelSet);
            Assert.Equal(expected.Model, actual.Model);
        }
        public JsTreeTagHelperTests()
        {
            JsTree tree = new JsTree();
            tree.SelectedIds.Add(4567);
            tree.SelectedIds.Add(12345);
            tree.Nodes.Add(new JsTreeNode("Test"));
            tree.Nodes[0].Nodes.Add(new JsTreeNode(12345, "Test1"));
            tree.Nodes[0].Nodes.Add(new JsTreeNode(23456, "Test2"));

            EmptyModelMetadataProvider provider = new EmptyModelMetadataProvider();
            ModelExplorer explorer = new ModelExplorer(provider, provider.GetMetadataForProperty(typeof(JsTreeView), "JsTree"), tree);

            helper = new JsTreeTagHelper();
            helper.For = new ModelExpression("JsTree", explorer);
            output = new TagHelperOutput("div", new TagHelperAttributeList(), (useCachedResult, encoder) => null);
        }
        public void TextBoxFor_UsesSpecifiedHtmlAttributes()
        {
            // Arrange
            var metadataProvider = new EmptyModelMetadataProvider();
            var helper = DefaultTemplatesUtilities.GetHtmlHelper(new ViewDataDictionary<TestModel>(metadataProvider));
            helper.ViewContext.ClientValidationEnabled = false;
            helper.ViewData.Model = new TestModel { Property1 = "propValue" };

            // Act
            var textBoxForResult = helper.TextBoxFor(m => m.Property1, htmlAttributes: new { attr = "value" });

            // Assert
            Assert.Equal(
                "<input attr=\"HtmlEncode[[value]]\" id=\"HtmlEncode[[Property1]]\" name=\"HtmlEncode[[Property1]]\" type=\"HtmlEncode[[text]]\" value=\"HtmlEncode[[propValue]]\" />",
                HtmlContentUtilities.HtmlContentToString(textBoxForResult));
        }
        public void RadioButtonFor_CheckedWhenValueMatchesSpecifiedExpression(string value)
        {
            // Arrange
            var metadataProvider = new EmptyModelMetadataProvider();
            var helper = DefaultTemplatesUtilities.GetHtmlHelper(new ViewDataDictionary<TestModel>(metadataProvider));
            helper.ViewContext.ClientValidationEnabled = false;
            helper.ViewData.Model = new TestModel { Property1 = value };

            // Act
            var radioButtonForResult = helper.RadioButtonFor(m => m.Property1, value: "myvalue");

            // Assert
            Assert.Equal(
                "<input checked=\"HtmlEncode[[checked]]\" id=\"HtmlEncode[[Property1]]\" name=\"HtmlEncode[[Property1]]\" type=\"HtmlEncode[[radio]]\" value=\"HtmlEncode[[myvalue]]\" />",
                HtmlContentUtilities.HtmlContentToString(radioButtonForResult));
        }
        public void TextBox_UsesSpecifiedFormat()
        {
            // Arrange
            var metadataProvider = new EmptyModelMetadataProvider();
            var helper = DefaultTemplatesUtilities.GetHtmlHelper(new ViewDataDictionary<TestModel>(metadataProvider));
            helper.ViewContext.ClientValidationEnabled = false;
            helper.ViewData.Model = new TestModel { Property1 = "propValue" };

            // Act
            var textBoxResult = helper.TextBox("Property1", value: null, format: "prefix: {0}");

            // Assert
            Assert.Equal(
                "<input id=\"HtmlEncode[[Property1]]\" name=\"HtmlEncode[[Property1]]\" type=\"HtmlEncode[[text]]\" value=\"HtmlEncode[[prefix: propValue]]\" />",
                HtmlContentUtilities.HtmlContentToString(textBoxResult));
        }
        public void FromLambdaExpression_GetsExpectedMetadata_ForIndexerExpression()
        {
            // Arrange
            var provider = new EmptyModelMetadataProvider();
            var viewData = new ViewDataDictionary<TestModel[]>(provider);

            // Act
            var explorer = ExpressionMetadataProvider.FromLambdaExpression(m => m[23], viewData, provider);

            // Assert
            Assert.NotNull(explorer);
            Assert.NotNull(explorer.Metadata);
            Assert.Equal(ModelMetadataKind.Type, explorer.Metadata.MetadataKind);
            Assert.Equal(typeof(TestModel), explorer.ModelType);
            Assert.Null(explorer.Model);
        }
        public void Constructor_InitalizesMembers()
        {
            // Arrange
            var metadataProvider = new EmptyModelMetadataProvider();
            var modelState = new ModelStateDictionary();

            // Act
            var viewData = new ViewDataDictionary<string>(metadataProvider, modelState);

            // Assert
            Assert.Same(modelState, viewData.ModelState);
            Assert.NotNull(viewData.TemplateInfo);
            Assert.Null(viewData.Model);
            Assert.NotNull(viewData.ModelMetadata);
            Assert.Equal(0, viewData.Count);
        }
Beispiel #25
0
        public void GetPropertyExplorer_ReturnsNull_ForPropertyNotFound()
        {
            // Arrange
            var model = new DerivedClass()
            {
                Base1 = 5,
            };

            var provider = new EmptyModelMetadataProvider();
            var modelExplorer = provider.GetModelExplorerForType(typeof(BaseClass), model);

            // Act
            var propertyExplorer = modelExplorer.GetExplorerForProperty("BadName");

            // Assert
            Assert.Null(propertyExplorer);
        }
        public void FromLambaExpression_SetsContainerAsExpected()
        {
            // Arrange
            var myModel = new TestModel { SelectedCategory = new Category() };
            var provider = new EmptyModelMetadataProvider();
            var viewData = new ViewDataDictionary<TestModel>(provider);
            viewData.Model = myModel;

            // Act
            var metadata = ExpressionMetadataProvider.FromLambdaExpression<TestModel, Category>(
                model => model.SelectedCategory,
                viewData,
                provider);

            // Assert
            Assert.Same(myModel, metadata.Container.Model);
        }
        private static DefaultModelBindingContext GetBindingContext(Type modelType)
        {
            var metadataProvider = new EmptyModelMetadataProvider();
            DefaultModelBindingContext bindingContext = new DefaultModelBindingContext
            {
                ActionContext = new ActionContext()
                {
                    HttpContext = new DefaultHttpContext(),
                },
                ModelMetadata = metadataProvider.GetMetadataForType(modelType),
                ModelName = "someName",
                ValidationState = new ValidationStateDictionary(),
            };

            bindingContext.HttpContext.Request.Method = "GET";

            return bindingContext;
        }
        public void FromLambdaExpression_GetsExpectedMetadata_ForLongerExpression()
        {
            // Arrange
            var provider = new EmptyModelMetadataProvider();
            var viewData = new ViewDataDictionary<TestModel[]>(provider);
            var index = 42;

            // Act
            var explorer = ExpressionMetadataProvider.FromLambdaExpression(
                m => m[index].SelectedCategory.CategoryId,
                viewData,
                provider);

            // Assert
            Assert.NotNull(explorer);
            Assert.NotNull(explorer.Metadata);
            Assert.Equal(ModelMetadataKind.Property, explorer.Metadata.MetadataKind);
            Assert.Equal(typeof(int), explorer.ModelType);
            Assert.Null(explorer.Model);
        }
        public void ListBoxFor_NullSelectListFindsListFromViewData()
        {
            // Arrange
            var expectedHtml = "<select id=\"HtmlEncode[[Property1]]\" multiple=\"HtmlEncode[[multiple]]\" name=\"HtmlEncode[[Property1]]\">" +
                "<option value=\"HtmlEncode[[0]]\">HtmlEncode[[Zero]]</option>" + Environment.NewLine +
                "<option value=\"HtmlEncode[[1]]\">HtmlEncode[[One]]</option>" + Environment.NewLine +
                "<option value=\"HtmlEncode[[2]]\">HtmlEncode[[Two]]</option>" + Environment.NewLine +
                "<option value=\"HtmlEncode[[3]]\">HtmlEncode[[Three]]</option>" + Environment.NewLine +
                "</select>";
            var metadataProvider = new EmptyModelMetadataProvider();
            var helper = DefaultTemplatesUtilities.GetHtmlHelper(new ViewDataDictionary<TestModel>(metadataProvider));
            helper.ViewContext.ClientValidationEnabled = false;
            helper.ViewData["Property1"] = BasicSelectList;

            // Act
            var listBoxForResult = helper.ListBoxFor(m => m.Property1, null);

            // Assert
            Assert.Equal(expectedHtml, HtmlContentUtilities.HtmlContentToString(listBoxForResult));
        }
        public void CopyConstructors_InitalizeModelAndModelMetadataBasedOnSource()
        {
            // Arrange
            var metadataProvider = new EmptyModelMetadataProvider();
            var model = new TestModel();
            var source = new ViewDataDictionary<object>(metadataProvider)
            {
                Model = model
            };
            source["foo"] = "bar";
            source.TemplateInfo.HtmlFieldPrefix = "prefix";

            // Act
            var viewData1 = new ViewDataDictionary<object>(source);
            var viewData2 = new ViewDataDictionary(source);

            // Assert
            Assert.NotNull(viewData1.ModelState);
            Assert.NotNull(viewData1.TemplateInfo);
            Assert.Equal("prefix", viewData1.TemplateInfo.HtmlFieldPrefix);
            Assert.NotSame(source.TemplateInfo, viewData1.TemplateInfo);
            Assert.Same(model, viewData1.Model);
            Assert.NotNull(viewData1.ModelMetadata);
            Assert.Equal(typeof(TestModel), viewData1.ModelMetadata.ModelType);
            Assert.Same(source.ModelMetadata, viewData1.ModelMetadata);
            Assert.Equal(source.Count, viewData1.Count);
            Assert.Equal("bar", viewData1["foo"]);
            Assert.IsType<CopyOnWriteDictionary<string, object>>(viewData1.Data);

            Assert.NotNull(viewData2.ModelState);
            Assert.NotNull(viewData2.TemplateInfo);
            Assert.Equal("prefix", viewData2.TemplateInfo.HtmlFieldPrefix);
            Assert.NotSame(source.TemplateInfo, viewData2.TemplateInfo);
            Assert.Same(model, viewData2.Model);
            Assert.NotNull(viewData2.ModelMetadata);
            Assert.Equal(typeof(TestModel), viewData2.ModelMetadata.ModelType);
            Assert.Same(source.ModelMetadata, viewData2.ModelMetadata);
            Assert.Equal(source.Count, viewData2.Count);
            Assert.Equal("bar", viewData2["foo"]);
            Assert.IsType<CopyOnWriteDictionary<string, object>>(viewData2.Data);
        }