public async Task TryUpdateModel_ReturnsFalse_IfBinderReturnsNull()
        {
            // Arrange
            var metadataProvider = new EmptyModelMetadataProvider();

            var binder = new Mock<IModelBinder>();
            binder.Setup(b => b.BindModelAsync(It.IsAny<ModelBindingContext>()))
                  .Returns(Task.FromResult<ModelBindingResult>(null));
            var model = new MyModel();

            // Act
            var result = await ModelBindingHelper.TryUpdateModelAsync(
                model,
                null,
                Mock.Of<HttpContext>(),
                new ModelStateDictionary(),
                metadataProvider,
                GetCompositeBinder(binder.Object),
                Mock.Of<IValueProvider>(),
                new List<IInputFormatter>(),
                new DefaultObjectValidator(new IExcludeTypeValidationFilter[0], metadataProvider),
                Mock.Of<IModelValidatorProvider>());

            // Assert
            Assert.False(result);
            Assert.Null(model.MyProperty);
        }
        public async Task JsonPatchInputFormatter_ReadsMultipleOperations_Successfully()
        {
            // Arrange
            var formatter = new JsonPatchInputFormatter();
            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);

            // 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);
        }
Ejemplo n.º 3
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);
        }
Ejemplo n.º 4
0
        public void ModelType_UsesRuntimeType()
        {
            // Arrange
            var provider = new EmptyModelMetadataProvider();
            var modelExplorer = provider.GetModelExplorerForType(typeof(BaseClass), new DerivedClass());

            // Act
            var modelType = modelExplorer.ModelType;

            // Assert
            Assert.Equal(typeof(DerivedClass), modelType);
        }
        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);
        }
Ejemplo n.º 6
0
        public void ConstructorWithOneParameterInitalizesMembers()
        {
            // Arrange
            var metadataProvider = new EmptyModelMetadataProvider();

            // Act
            var viewData = new ViewDataDictionary(metadataProvider);

            // Assert
            Assert.NotNull(viewData.ModelState);
            Assert.NotNull(viewData.TemplateInfo);
            Assert.Null(viewData.Model);
            Assert.NotNull(viewData.ModelMetadata);
            Assert.Equal(0, viewData.Count);
        }
        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);
        }
        public void FromStringExpression_SetsContainerAsExpected()
        {
            // Arrange
            var myModel = new TestModel { SelectedCategory = new Category() };
            var provider = new EmptyModelMetadataProvider();
            var viewData = new ViewDataDictionary<TestModel>(provider);
            viewData["Object"] = myModel;

            // Act
            var metadata = ExpressionMetadataProvider.FromStringExpression("Object.SelectedCategory",
                                                                           viewData,
                                                                           provider);

            // Assert
            Assert.Same(myModel, metadata.Container.Model);
        }
Ejemplo n.º 9
0
        public void ObjectTemplateDisplaysNullDisplayTextWhenObjectIsNull()
        {
            // Arrange
            var html = DefaultTemplatesUtilities.GetHtmlHelper();
            var metadata =
                new EmptyModelMetadataProvider()
                    .GetMetadataForType(null, typeof(DefaultTemplatesUtilities.ObjectTemplateModel));
            metadata.NullDisplayText = "(null value)";
            html.ViewData.ModelMetadata = metadata;

            // Act
            var result = DefaultDisplayTemplates.ObjectTemplate(html);

            // Assert
            Assert.Equal(metadata.NullDisplayText, result);
        }
Ejemplo n.º 10
0
        public async Task JsonFormatterReadsSimpleTypes(string content, Type type, object expected)
        {
            // Arrange
            var formatter = new JsonInputFormatter();
            var contentBytes = Encoding.UTF8.GetBytes(content);

            var httpContext = GetHttpContext(contentBytes);
            var modelState = new ModelStateDictionary();
            var metadata = new EmptyModelMetadataProvider().GetMetadataForType(null, type);
            var context = new InputFormatterContext(httpContext, metadata, modelState);

            // Act
            await formatter.ReadAsync(context);

            // Assert
            Assert.Equal(expected, context.Model);
        }
Ejemplo n.º 11
0
        public void Properties_UsesDeclaredType_WhenModelIsNull()
        {
            // Arrange
            var provider = new EmptyModelMetadataProvider();
            var modelExplorer = provider.GetModelExplorerForType(typeof(BaseClass), model: null);

            // Act
            var properties = modelExplorer.Properties.ToArray();

            // Assert
            Assert.Equal(1, properties.Length);

            var baseProperty = Assert.Single(properties, p => p.Metadata.PropertyName == "Base1");
            Assert.Equal(typeof(int), baseProperty.Metadata.ModelType);
            Assert.Equal(typeof(BaseClass), baseProperty.Metadata.ContainerType);
            Assert.Same(modelExplorer, baseProperty.Container);
        }
        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 ModelBindingContext GetBindingContext(Type modelType)
        {
            var metadataProvider = new EmptyModelMetadataProvider();
            ModelBindingContext bindingContext = new ModelBindingContext
            {
                ModelMetadata = metadataProvider.GetMetadataForType(modelType),
                ModelName = "someName",
                OperationBindingContext = new OperationBindingContext
                {
                    HttpContext = new DefaultHttpContext(),
                    MetadataProvider = metadataProvider,
                }
            };

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

            return bindingContext;
        }
Ejemplo n.º 14
0
        public void ObjectTemplateDisplaysSimpleDisplayTextWhenTemplateDepthGreaterThanOne()
        {
            // Arrange
            var model = new DefaultTemplatesUtilities.ObjectTemplateModel();
            var html = DefaultTemplatesUtilities.GetHtmlHelper(model);
            var metadata =
                new EmptyModelMetadataProvider()
                    .GetMetadataForType(() => model, typeof(DefaultTemplatesUtilities.ObjectTemplateModel));
            metadata.SimpleDisplayText = "Simple Display Text";
            html.ViewData.ModelMetadata = metadata;
            html.ViewData.TemplateInfo.AddVisited("foo");
            html.ViewData.TemplateInfo.AddVisited("bar");

            // Act
            var result = DefaultDisplayTemplates.ObjectTemplate(html);

            // Assert
            Assert.Equal(metadata.SimpleDisplayText, result);
        }
Ejemplo n.º 15
0
        public async Task JsonFormatterReadsComplexTypes()
        {
            // Arrange
            var content = "{name: 'Person Name', Age: '30'}";
            var formatter = new JsonInputFormatter();
            var contentBytes = Encoding.UTF8.GetBytes(content);

            var httpContext = GetHttpContext(contentBytes);
            var modelState = new ModelStateDictionary();
            var metadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(User));
            var context = new InputFormatterContext(httpContext, metadata, modelState);

            // Act
            await formatter.ReadAsync(context);

            // Assert
            var model = Assert.IsType<User>(context.Model);
            Assert.Equal("Person Name", model.Name);
            Assert.Equal(30, model.Age);
        }
        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);
        }
Ejemplo n.º 17
0
        public void MultipartFormatter_CanRead_ReturnsTrueForSupportedMediaTypes(string requestContentType)
        {
            // Arrange
            var formatter = new MultipartFormatter();
            var httpContext = new DefaultHttpContext();
            httpContext.Request.ContentType = requestContentType;

            var provider = new EmptyModelMetadataProvider();
            var metadata = provider.GetMetadataForType(typeof(void));
            var context = new InputFormatterContext(
                httpContext,
                modelName: string.Empty,
                modelState: new ModelStateDictionary(),
                metadata: metadata);

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

            // Assert
            Assert.True(result);
        }
Ejemplo n.º 18
0
        public void CanRead_ReturnsTrueForAnySupportedContentType(string requestContentType, bool expectedCanRead)
        {
            // Arrange
            var formatter = new JsonInputFormatter();
            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);

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

            // Assert
            Assert.Equal(expectedCanRead, result);
        }
Ejemplo n.º 19
0
        public void Properties_UsesRuntimeType()
        {
            // Arrange
            var provider = new EmptyModelMetadataProvider();
            var modelExplorer = provider.GetModelExplorerForType(typeof(BaseClass), new DerivedClass());

            // Act
            var properties = modelExplorer.Properties.ToArray();

            // Assert
            Assert.Equal(2, properties.Length);

            var baseProperty = Assert.Single(properties, p => p.Metadata.PropertyName == "Base1");
            Assert.Equal(typeof(int), baseProperty.Metadata.ModelType);
            Assert.Equal(typeof(DerivedClass), baseProperty.Metadata.ContainerType);
            Assert.Same(modelExplorer, baseProperty.Container);

            var derivedProperty = Assert.Single(properties, p => p.Metadata.PropertyName == "Derived1");
            Assert.Equal(typeof(string), derivedProperty.Metadata.ModelType);
            Assert.Equal(typeof(DerivedClass), derivedProperty.Metadata.ContainerType);
            Assert.Same(modelExplorer, derivedProperty.Container);
        }
Ejemplo n.º 20
0
        public void LabelHelpers_DisplayMetadataPropertyNameForProperty()
        {
            // Arrange
            var propertyName = "Property1";

            var provider = new EmptyModelMetadataProvider();

            var modelExplorer = provider
                .GetModelExplorerForType(typeof(DefaultTemplatesUtilities.ObjectTemplateModel), model: null)
                .GetExplorerForProperty(propertyName);

            var helper = DefaultTemplatesUtilities.GetHtmlHelper();
            helper.ViewData.ModelExplorer = modelExplorer;

            // Act
            var labelResult = helper.Label(expression: string.Empty);
            var labelForResult = helper.LabelFor(m => m);
            var labelForModelResult = helper.LabelForModel();

            // Assert
            Assert.Equal("<label for=\"\">HtmlEncode[[" + propertyName + "]]</label>", labelResult.ToString());
            Assert.Equal("<label for=\"\">HtmlEncode[[" + propertyName + "]]</label>", labelForResult.ToString());
            Assert.Equal("<label for=\"\">HtmlEncode[[" + propertyName + "]]</label>", labelForModelResult.ToString());
        }
Ejemplo n.º 21
0
        public void Properties_UsesRuntimeType()
        {
            // Arrange
            var provider      = new EmptyModelMetadataProvider();
            var modelExplorer = provider.GetModelExplorerForType(typeof(BaseClass), new DerivedClass());

            // Act
            var properties = modelExplorer.Properties.ToArray();

            // Assert
            Assert.Equal(2, properties.Length);

            var baseProperty = Assert.Single(properties, p => p.Metadata.PropertyName == "Base1");

            Assert.Equal(typeof(int), baseProperty.Metadata.ModelType);
            Assert.Equal(typeof(DerivedClass), baseProperty.Metadata.ContainerType);
            Assert.Same(modelExplorer, baseProperty.Container);

            var derivedProperty = Assert.Single(properties, p => p.Metadata.PropertyName == "Derived1");

            Assert.Equal(typeof(string), derivedProperty.Metadata.ModelType);
            Assert.Equal(typeof(DerivedClass), derivedProperty.Metadata.ContainerType);
            Assert.Same(modelExplorer, derivedProperty.Container);
        }
Ejemplo n.º 22
0
        public void ModelStateConstructorWithDetail_AddsCorrectDictionaryItems()
        {
            // Arrange
            ModelStateDictionary modelState = new ModelStateDictionary();
            var provider = new EmptyModelMetadataProvider();
            var metadata = provider.GetMetadataForProperty(typeof(string), nameof(string.Length));
            modelState.AddModelError("[0].Name", "error1");
            modelState.AddModelError("[0].Name", "error2");
            modelState.AddModelError("[0].Address", "error");
            modelState.AddModelError("[2].Name", new Exception("OH NO"), metadata);

            // Act
            HttpError error = new HttpError(modelState, true);

            // Assert
            HttpError modelStateError = error["ModelState"] as HttpError;

            Assert.Contains(new KeyValuePair<string, object>("Message", "The request is invalid."), error);
            Assert.Contains("error1", modelStateError["[0].Name"] as IEnumerable<string>);
            Assert.Contains("error2", modelStateError["[0].Name"] as IEnumerable<string>);
            Assert.Contains("error", modelStateError["[0].Address"] as IEnumerable<string>);
            Assert.True(modelStateError.ContainsKey("[2].Name"));
            Assert.Contains("OH NO", modelStateError["[2].Name"] as IEnumerable<string>);
        }
Ejemplo n.º 23
0
        private ModelValidationContext GetModelValidationContext(
            object model, Type type, List <Type> excludedTypes = null)
        {
            var modelStateDictionary = new ModelStateDictionary();
            var providers            = new IModelValidatorProvider[]
            {
                new DataAnnotationsModelValidatorProvider(),
                new DataMemberModelValidatorProvider()
            };
            var modelMetadataProvider            = new EmptyModelMetadataProvider();
            var excludedValidationTypesPredicate =
                new List <IExcludeTypeValidationFilter>();

            if (excludedTypes != null)
            {
                var mockExcludeTypeFilter = new Mock <IExcludeTypeValidationFilter>();
                mockExcludeTypeFilter.Setup(o => o.IsTypeExcluded(It.IsAny <Type>()))
                .Returns <Type>(excludedType =>
                                excludedTypes.Any(t => t.IsAssignableFrom(excludedType)));

                excludedValidationTypesPredicate.Add(mockExcludeTypeFilter.Object);
            }

            return(new ModelValidationContext(
                       modelMetadataProvider,
                       new CompositeModelValidatorProvider(providers),
                       modelStateDictionary,
                       new ModelMetadata(
                           provider: modelMetadataProvider,
                           containerType: typeof(object),
                           modelAccessor: () => model,
                           modelType: type,
                           propertyName: null),
                       containerMetadata: null,
                       excludeFromValidationFilters: excludedValidationTypesPredicate));
        }
Ejemplo n.º 24
0
        public async Task ProcessAsync_GeneratesExpectedOutput(
            string originalContent,
            string selected,
            string value,
            IEnumerable<string> selectedValues,
            TagHelperOutput expectedTagHelperOutput)
        {
            // Arrange
            var originalAttributes = new TagHelperAttributeList
            {
                { "label", "my-label" },
            };
            if (selected != null)
            {
                originalAttributes.Add("selected", selected);
            }

            var contextAttributes = new TagHelperAttributeList(originalAttributes);
            if (value != null)
            {
                contextAttributes.Add("value", value);
            }

            var tagHelperContext = new TagHelperContext(
                contextAttributes,
                items: new Dictionary<object, object>(),
                uniqueId: "test",
                getChildContentAsync: () =>
                {
                    // GetChildContentAsync should not be invoked since we are setting the content below.
                    Assert.True(false);
                    return Task.FromResult<TagHelperContent>(null);
                });

            var output = new TagHelperOutput(expectedTagHelperOutput.TagName, originalAttributes)
            {
                SelfClosing = false,
            };

            output.Content.SetContent(originalContent);

            var metadataProvider = new EmptyModelMetadataProvider();
            var htmlGenerator = new TestableHtmlGenerator(metadataProvider);
            var viewContext = TestableHtmlGenerator.GetViewContext(
                model: null,
                htmlGenerator: htmlGenerator,
                metadataProvider: metadataProvider);
            viewContext.FormContext.FormData[SelectTagHelper.SelectedValuesFormDataKey] = selectedValues;
            var tagHelper = new OptionTagHelper(htmlGenerator)
            {
                Value = value,
                ViewContext = viewContext,
            };

            // Act
            await tagHelper.ProcessAsync(tagHelperContext, output);

            // Assert
            Assert.Equal(expectedTagHelperOutput.TagName, output.TagName);
            Assert.Equal(expectedTagHelperOutput.Content.GetContent(), output.Content.GetContent());
            Assert.Equal(expectedTagHelperOutput.Attributes.Count, output.Attributes.Count);
            foreach (var attribute in output.Attributes)
            {
                Assert.Contains(attribute, expectedTagHelperOutput.Attributes);
            }
        }
Ejemplo n.º 25
0
        public async Task ProcessAsync_DoesNotUseViewContext_IfSelectedNotNull(
            string originalContent,
            string selected,
            string value,
            IEnumerable<string> ignoredValues,
            TagHelperOutput ignoredOutput)
        {
            // Arrange
            var originalAttributes = new TagHelperAttributeList
            {
                { "label", "my-label" },
                { "selected", selected },
            };
            var originalTagName = "not-option";

            var contextAttributes = new TagHelperAttributeList
            {
                { "label", "my-label" },
                { "selected", selected },
                { "value", value },
            };
            var originalPreContent = "original pre-content";
            var originalPostContent = "original post-content";
            var tagHelperContext = new TagHelperContext(
                contextAttributes,
                items: new Dictionary<object, object>(),
                uniqueId: "test",
                getChildContentAsync: () =>
                {
                    var tagHelperContent = new DefaultTagHelperContent();
                    tagHelperContent.SetContent(originalContent);
                    return Task.FromResult<TagHelperContent>(tagHelperContent);
                });

            var output = new TagHelperOutput(originalTagName, originalAttributes)
            {
                SelfClosing = false,
            };
            output.PreContent.SetContent(originalPreContent);
            output.Content.SetContent(originalContent);
            output.PostContent.SetContent(originalPostContent);

            var metadataProvider = new EmptyModelMetadataProvider();
            var htmlGenerator = new TestableHtmlGenerator(metadataProvider);

            var tagHelper = new OptionTagHelper(htmlGenerator)
            {
                Value = value,
            };

            // Act & Assert (does not throw)
            // Tag helper would throw an NRE if it used ViewContext or Generator values.
            await tagHelper.ProcessAsync(tagHelperContext, output);
        }
Ejemplo n.º 26
0
        private static ModelBindingContext GetBindingContext(Type modelType, HttpContext httpContext)
        {
            var metadataProvider = new EmptyModelMetadataProvider();
            var bindingContext = new ModelBindingContext
            {
                ModelMetadata = metadataProvider.GetMetadataForType(modelType),
                ModelName = "file",
                ModelState = new ModelStateDictionary(),
                OperationBindingContext = new OperationBindingContext
                {
                    ModelBinder = new FormFileModelBinder(),
                    MetadataProvider = metadataProvider,
                    HttpContext = httpContext,
                },
                ValidationState = new ValidationStateDictionary(),
            };

            return bindingContext;
        }
Ejemplo n.º 27
0
        private static ViewContext MakeViewContext(string requestPathBase = null)
        {
            var actionContext = new ActionContext(new DefaultHttpContext(), new RouteData(), new ActionDescriptor());
            if (requestPathBase != null)
            {
                actionContext.HttpContext.Request.PathBase = new Http.PathString(requestPathBase);
            }

            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;
        }
Ejemplo n.º 28
0
        private static ModelBindingContext GetBindingContext(
            Type modelType,
            IEnumerable<IInputFormatter> inputFormatters = null,
            HttpContext httpContext = null,
            IModelMetadataProvider metadataProvider = null)
        {
            if (httpContext == null)
            {
                httpContext = new DefaultHttpContext();
            }

            if (inputFormatters == null)
            {
                inputFormatters = Enumerable.Empty<IInputFormatter>();
            }

            if (metadataProvider == null)
            {
                metadataProvider = new EmptyModelMetadataProvider();
            }

            var operationBindingContext = new OperationBindingContext
            {
                InputFormatters = inputFormatters.ToList(),
                ModelBinder = new BodyModelBinder(),
                MetadataProvider = metadataProvider,
                HttpContext = httpContext,
            };

            var bindingContext = new ModelBindingContext
            {
                ModelMetadata = metadataProvider.GetMetadataForType(modelType),
                ModelName = "someName",
                ValueProvider = Mock.Of<IValueProvider>(),
                ModelState = new ModelStateDictionary(),
                OperationBindingContext = operationBindingContext,
                BindingSource = BindingSource.Body,
            };

            return bindingContext;
        }
 private static ModelExpression CreateModelExpression(string name)
 {
     var modelMetadataProvider = new EmptyModelMetadataProvider();
     return new ModelExpression(
         name,
         modelMetadataProvider.GetModelExplorerForType(typeof(object), model: null));
 }
Ejemplo n.º 30
0
        public async Task ProcessAsync_DoesNotUseGenerator_IfSelectedNullOrNoSelectedValues(
            string originalContent,
            string selected,
            string value,
            IEnumerable<string> selectedValues,
            TagHelperOutput ignored)
        {
            // Arrange
            var originalAttributes = new TagHelperAttributeList
            {
                { "label", "my-label" },
                { "selected", selected },
            };
            var originalTagName = "not-option";

            var contextAttributes = new TagHelperAttributeList
            {
                { "label", "my-label" },
                { "selected", selected },
                { "value", value },
            };
            var originalPreContent = "original pre-content";
            var originalPostContent = "original post-content";
            var tagHelperContext = new TagHelperContext(
                contextAttributes,
                items: new Dictionary<object, object>(),
                uniqueId: "test",
                getChildContentAsync: useCachedResult =>
                {
                    var tagHelperContent = new DefaultTagHelperContent();
                    tagHelperContent.SetContent(originalContent);
                    return Task.FromResult<TagHelperContent>(tagHelperContent);
                });
            var output = new TagHelperOutput(originalTagName, originalAttributes)
            {
                TagMode = TagMode.StartTagAndEndTag,
            };
            output.PreContent.SetContent(originalPreContent);
            output.Content.SetContent(originalContent);
            output.PostContent.SetContent(originalPostContent);

            var metadataProvider = new EmptyModelMetadataProvider();
            var htmlGenerator = new TestableHtmlGenerator(metadataProvider);
            var viewContext = TestableHtmlGenerator.GetViewContext(
                model: null,
                htmlGenerator: htmlGenerator,
                metadataProvider: metadataProvider);
            viewContext.FormContext.FormData[SelectTagHelper.SelectedValuesFormDataKey] = selectedValues;
            var tagHelper = new OptionTagHelper(htmlGenerator)
            {
                Value = value,
                ViewContext = viewContext,
            };

            // Act & Assert (does not throw)
            // Tag helper would throw an NRE if it used Generator value.
            await tagHelper.ProcessAsync(tagHelperContext, output);
        }
        public async Task Invoke_UsesDefaultValuesIfNotBound()
        {
            // Arrange
            var actionDescriptor = new ControllerActionDescriptor
            {
                ControllerTypeInfo = typeof(TestController).GetTypeInfo(),
                BoundProperties = new List<ParameterDescriptor>(),
                MethodInfo = typeof(TestController).GetTypeInfo()
                    .DeclaredMethods
                    .First(m => m.Name.Equals("ActionMethodWithDefaultValues", StringComparison.Ordinal)),

                Parameters = new List<ParameterDescriptor>
                {
                    new ParameterDescriptor
                    {
                        Name = "value",
                        ParameterType = typeof(int),
                        BindingInfo = new BindingInfo(),
                    }
                },
                FilterDescriptors = new List<FilterDescriptor>()
            };

            var binder = new Mock<IModelBinder>();
            binder.Setup(b => b.BindModelAsync(It.IsAny<ModelBindingContext>()))
                  .Returns(ModelBindingResult.NoResultAsync);
            var context = new Mock<HttpContext>();
            context.SetupGet(c => c.Items)
                   .Returns(new Dictionary<object, object>());
            context.Setup(c => c.RequestServices.GetService(typeof(ILoggerFactory)))
                       .Returns(new NullLoggerFactory());

            var actionContext = new ActionContext(context.Object, new RouteData(), actionDescriptor);

            var controllerFactory = new Mock<IControllerFactory>();
            controllerFactory.Setup(c => c.CreateController(It.IsAny<ControllerContext>()))
                             .Returns(new TestController());

            var metadataProvider = new EmptyModelMetadataProvider();

            var invoker = new ControllerActionInvoker(
                actionContext,
                new List<IFilterProvider>(),
                controllerFactory.Object,
                actionDescriptor,
                new IInputFormatter[0],
                new DefaultControllerActionArgumentBinder(
                    metadataProvider,
                    new DefaultObjectValidator(metadataProvider)),
                new IModelBinder[] { binder.Object },
                new IModelValidatorProvider[0],
                new IValueProviderFactory[0],
                new NullLoggerFactory().CreateLogger<ControllerActionInvoker>(),
                new DiagnosticListener("Microsoft.AspNet"),
                200);

            // Act
            await invoker.InvokeAsync();

            // Assert
            Assert.Equal(5, context.Object.Items["Result"]);
        }
Ejemplo n.º 32
0
        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;
        }