本文整理汇总了C#中TestModelMetadataProvider类的典型用法代码示例。如果您正苦于以下问题:C# TestModelMetadataProvider类的具体用法?C# TestModelMetadataProvider怎么用?C# TestModelMetadataProvider使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
TestModelMetadataProvider类属于命名空间,在下文中一共展示了TestModelMetadataProvider类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: GetValidators_CachesAllValidators
public void GetValidators_CachesAllValidators()
{
// Arrange
var cache = new ValidatorCache();
var metadata = new TestModelMetadataProvider().GetMetadataForProperty(typeof(TypeWithProperty), "Property1");
var validatorProvider = TestModelValidatorProvider.CreateDefaultProvider();
// Act - 1
var validators1 = cache.GetValidators(metadata, validatorProvider);
// Assert - 1
var attribute1 = Assert.IsType<DataAnnotationsModelValidator>(validators1[0]).Attribute;
var attribute2 = Assert.IsType<DataAnnotationsModelValidator>(validators1[1]).Attribute;
Assert.Contains(attribute1, metadata.ValidatorMetadata); // Copied by provider
Assert.Contains(attribute2, metadata.ValidatorMetadata); // Copied by provider
// Act - 2
var validators2 = cache.GetValidators(metadata, validatorProvider);
// Assert - 2
Assert.Same(validators1, validators2);
Assert.Contains(validators1[0], validators2); // Cached
Assert.Contains(validators1[1], validators2); // Cached
}
示例2: GetValidators_DoesNotCacheValidatorsWithIsReusableFalse
public void GetValidators_DoesNotCacheValidatorsWithIsReusableFalse()
{
// Arrange
var cache = new ValidatorCache();
var metadata = new TestModelMetadataProvider().GetMetadataForProperty(typeof(TypeWithProperty), "Property1");
var validatorProvider = new ProviderWithNonReusableValidators();
// Act - 1
var validators1 = cache.GetValidators(metadata, validatorProvider);
// Assert - 1
var validator1 = Assert.IsType<DataAnnotationsModelValidator>(validators1[0]);
var validator2 = Assert.IsType<DataAnnotationsModelValidator>(validators1[1]);
Assert.Contains(validator1.Attribute, metadata.ValidatorMetadata); // Copied by provider
Assert.Contains(validator2.Attribute, metadata.ValidatorMetadata); // Copied by provider
// Act - 2
var validators2 = cache.GetValidators(metadata, validatorProvider);
// Assert - 2
Assert.NotSame(validators1, validators2);
var requiredValidator = Assert.Single(validators2.Where(v => (v as DataAnnotationsModelValidator).Attribute is RequiredAttribute));
Assert.Contains(requiredValidator, validators1); // cached
var stringLengthValidator = Assert.Single(validators2.Where(v => (v as DataAnnotationsModelValidator).Attribute is StringLengthAttribute));
Assert.DoesNotContain(stringLengthValidator, validators1); // not cached
}
示例3: GetValidators_CachesAllValidators
public void GetValidators_CachesAllValidators()
{
// Arrange
var cache = new ClientValidatorCache();
var metadata = new TestModelMetadataProvider().GetMetadataForProperty(typeof(TypeWithProperty), "Property1");
var validatorProvider = TestClientModelValidatorProvider.CreateDefaultProvider();
// Act - 1
var validators1 = cache.GetValidators(metadata, validatorProvider);
// Assert - 1
var attribute1 = Assert.Single(validators1.OfType<RequiredAttributeAdapter>()).Attribute;
var attribute2 = Assert.Single(validators1.OfType<StringLengthAttributeAdapter>()).Attribute;
Assert.Contains(attribute1, metadata.ValidatorMetadata); // Copied by provider
Assert.Contains(attribute2, metadata.ValidatorMetadata); // Copied by provider
// Act - 2
var validators2 = cache.GetValidators(metadata, validatorProvider);
// Assert - 2
Assert.Same(validators1, validators2);
Assert.Contains(validators1[0], validators2); // Cached
Assert.Contains(validators1[1], validators2); // Cached
}
示例4: GetValidators_DoesNotCacheValidatorsWithIsReusableFalse
public void GetValidators_DoesNotCacheValidatorsWithIsReusableFalse()
{
// Arrange
var cache = new ClientValidatorCache();
var metadata = new TestModelMetadataProvider().GetMetadataForProperty(typeof(TypeWithProperty), "Property1");
var validatorProvider = new ProviderWithNonReusableValidators();
// Act - 1
var validators1 = cache.GetValidators(metadata, validatorProvider);
// Assert - 1
var validator1 = Assert.Single(validators1.OfType<RequiredAttributeAdapter>());
var validator2 = Assert.Single(validators1.OfType<StringLengthAttributeAdapter>());
Assert.Contains(validator1.Attribute, metadata.ValidatorMetadata); // Copied by provider
Assert.Contains(validator2.Attribute, metadata.ValidatorMetadata); // Copied by provider
// Act - 2
var validators2 = cache.GetValidators(metadata, validatorProvider);
// Assert - 2
Assert.NotSame(validators1, validators2);
Assert.Same(validator1, Assert.Single(validators2.OfType<RequiredAttributeAdapter>())); // cached
Assert.NotSame(validator2, Assert.Single(validators2.OfType<StringLengthAttributeAdapter>())); // not cached
}
示例5: Create_ForModelMetadataReadOnly_ReturnsNull
public void Create_ForModelMetadataReadOnly_ReturnsNull()
{
// Arrange
var metadataProvider = new TestModelMetadataProvider();
metadataProvider.ForProperty(
typeof(ModelWithIntArrayProperty),
nameof(ModelWithIntArrayProperty.ArrayProperty)).BindingDetails(bd => bd.IsReadOnly = true);
var modelMetadata = metadataProvider.GetMetadataForProperty(
typeof(ModelWithIntArrayProperty),
nameof(ModelWithIntArrayProperty.ArrayProperty));
var provider = new ArrayModelBinderProvider();
var context = new TestModelBinderProviderContext(typeof(int[]));
context.OnCreatingBinder((m) =>
{
// Expect to be called with the element type to create a binder for elements.
Assert.Equal(typeof(int), m.ModelType);
return Mock.Of<IModelBinder>();
});
// Act
var result = provider.GetBinder(context);
// Assert
Assert.IsType<ArrayModelBinder<int>>(result);
}
示例6: AddValidation_CorrectValidationTypeAndOverriddenErrorMessage
public void AddValidation_CorrectValidationTypeAndOverriddenErrorMessage()
{
// Arrange
var expectedMessage = "Error message about 'DisplayId' from override.";
var provider = new TestModelMetadataProvider();
provider
.ForProperty(typeof(TypeWithNumericProperty), nameof(TypeWithNumericProperty.Id))
.BindingDetails(d => d.ModelBindingMessageProvider.ValueMustBeANumberAccessor =
name => $"Error message about '{ name }' from override.");
var metadata = provider.GetMetadataForProperty(
typeof(TypeWithNumericProperty),
nameof(TypeWithNumericProperty.Id));
var adapter = new NumericClientModelValidator();
var actionContext = new ActionContext();
var context = new ClientModelValidationContext(actionContext, metadata, provider, new AttributeDictionary());
// Act
adapter.AddValidation(context);
// Assert
Assert.Collection(
context.Attributes,
kvp => { Assert.Equal("data-val", kvp.Key); Assert.Equal("true", kvp.Value); },
kvp => { Assert.Equal("data-val-number", kvp.Key); Assert.Equal(expectedMessage, kvp.Value); });
}
示例7: BindModel_CallsSelectedInputFormatterOnce
public async Task BindModel_CallsSelectedInputFormatterOnce()
{
// Arrange
var mockInputFormatter = new Mock<IInputFormatter>();
mockInputFormatter.Setup(f => f.CanRead(It.IsAny<InputFormatterContext>()))
.Returns(true)
.Verifiable();
mockInputFormatter.Setup(o => o.ReadAsync(It.IsAny<InputFormatterContext>()))
.Returns(InputFormatterResult.SuccessAsync(new Person()))
.Verifiable();
var inputFormatter = mockInputFormatter.Object;
var provider = new TestModelMetadataProvider();
provider.ForType<Person>().BindingDetails(d => d.BindingSource = BindingSource.Body);
var bindingContext = GetBindingContext(
typeof(Person),
new[] { inputFormatter },
metadataProvider: provider);
var binder = new BodyModelBinder();
// Act
var binderResult = await binder.BindModelAsync(bindingContext);
// Assert
mockInputFormatter.Verify(v => v.CanRead(It.IsAny<InputFormatterContext>()), Times.Once);
mockInputFormatter.Verify(v => v.ReadAsync(It.IsAny<InputFormatterContext>()), Times.Once);
Assert.NotNull(binderResult);
Assert.True(binderResult.IsModelSet);
}
示例8: GetBindingContext
private static DefaultModelBindingContext GetBindingContext(Type modelType)
{
var metadataProvider = new TestModelMetadataProvider();
metadataProvider.ForType(modelType).BindingDetails(d => d.BindingSource = BindingSource.Services);
var modelMetadata = metadataProvider.GetMetadataForType(modelType);
var services = new ServiceCollection();
services.AddSingleton<IService>(new Service());
var bindingContext = new DefaultModelBindingContext
{
ActionContext = new ActionContext()
{
HttpContext = new DefaultHttpContext()
{
RequestServices = services.BuildServiceProvider(),
}
},
ModelMetadata = modelMetadata,
ModelName = "modelName",
FieldName = "modelName",
ModelState = new ModelStateDictionary(),
BinderModelName = modelMetadata.BinderModelName,
BindingSource = modelMetadata.BindingSource,
ValidationState = new ValidationStateDictionary(),
};
return bindingContext;
}
示例9: BindModelAsync_ValueProviderContainPrefix_Succeeds
public async Task BindModelAsync_ValueProviderContainPrefix_Succeeds()
{
// Arrange
var valueProvider = new SimpleValueProvider
{
{ "someName[0]", "42" },
{ "someName[1]", "84" },
};
var bindingContext = GetBindingContext(valueProvider);
var metadataProvider = new TestModelMetadataProvider();
bindingContext.ModelMetadata = metadataProvider.GetMetadataForProperty(
typeof(ModelWithIntArrayProperty),
nameof(ModelWithIntArrayProperty.ArrayProperty));
var binder = new ArrayModelBinder<int>(new SimpleTypeModelBinder(typeof(int)));
// Act
await binder.BindModelAsync(bindingContext);
// Assert
Assert.True(bindingContext.Result.IsModelSet);
var array = Assert.IsType<int[]>(bindingContext.Result.Model);
Assert.Equal(new[] { 42, 84 }, array);
}
示例10: BindModel_NoInputFormatterFound_SetsModelStateError_RespectsBinderModelName
public async Task BindModel_NoInputFormatterFound_SetsModelStateError_RespectsBinderModelName()
{
// Arrange
var provider = new TestModelMetadataProvider();
provider.ForType<Person>().BindingDetails(d => d.BindingSource = BindingSource.Body);
var bindingContext = GetBindingContext(typeof(Person), metadataProvider: provider);
bindingContext.BinderModelName = "custom";
var binder = CreateBinder();
// Act
var binderResult = await binder.BindModelResultAsync(bindingContext);
// Assert
// Returns non-null because it understands the metadata type.
Assert.NotNull(binderResult);
Assert.False(binderResult.IsModelSet);
Assert.Null(binderResult.Model);
// Key is the bindermodelname because this was a top-level binding.
var entry = Assert.Single(bindingContext.ModelState);
Assert.Equal("custom", entry.Key);
Assert.Single(entry.Value.Errors);
}
示例11: BindModel_NoInputFormatterFound_SetsModelStateError
public async Task BindModel_NoInputFormatterFound_SetsModelStateError()
{
// Arrange
var provider = new TestModelMetadataProvider();
provider.ForType<Person>().BindingDetails(d => d.BindingSource = BindingSource.Body);
var bindingContext = GetBindingContext(typeof(Person), metadataProvider: provider);
var binder = bindingContext.OperationBindingContext.ModelBinder;
// Act
var binderResult = await binder.BindModelAsync(bindingContext);
// Assert
// Returns non-null because it understands the metadata type.
Assert.NotNull(binderResult);
Assert.False(binderResult.IsModelSet);
Assert.Null(binderResult.Model);
// Key is empty because this was a top-level binding.
var entry = Assert.Single(bindingContext.ModelState);
Assert.Equal(string.Empty, entry.Key);
Assert.Single(entry.Value.Errors);
}
示例12: ProcessAsync_GeneratesExpectedOutput
public async Task ProcessAsync_GeneratesExpectedOutput()
{
// Arrange
var expectedTagName = "not-div";
var metadataProvider = new TestModelMetadataProvider();
var htmlGenerator = new TestableHtmlGenerator(metadataProvider);
var validationSummaryTagHelper = new ValidationSummaryTagHelper(htmlGenerator)
{
ValidationSummary = ValidationSummary.All,
};
var expectedPreContent = "original pre-content";
var expectedContent = "original content";
var tagHelperContext = new TagHelperContext(
allAttributes: new ReadOnlyTagHelperAttributeList<IReadOnlyTagHelperAttribute>(
Enumerable.Empty<IReadOnlyTagHelperAttribute>()),
items: new Dictionary<object, object>(),
uniqueId: "test",
getChildContentAsync: useCachedResult =>
{
var tagHelperContent = new DefaultTagHelperContent();
tagHelperContent.SetContent("Something");
return Task.FromResult<TagHelperContent>(tagHelperContent);
});
var output = new TagHelperOutput(
expectedTagName,
attributes: new TagHelperAttributeList
{
{ "class", "form-control" }
});
output.PreContent.SetContent(expectedPreContent);
output.Content.SetContent(expectedContent);
output.PostContent.SetContent("Custom Content");
Model model = null;
var viewContext = TestableHtmlGenerator.GetViewContext(model, htmlGenerator, metadataProvider);
validationSummaryTagHelper.ViewContext = viewContext;
// Act
await validationSummaryTagHelper.ProcessAsync(tagHelperContext, output);
// Assert
Assert.Equal(2, output.Attributes.Count);
var attribute = Assert.Single(output.Attributes, attr => attr.Name.Equals("class"));
Assert.Equal("form-control validation-summary-valid", attribute.Value);
attribute = Assert.Single(output.Attributes, attr => attr.Name.Equals("data-valmsg-summary"));
Assert.Equal("true", attribute.Value);
Assert.Equal(expectedPreContent, output.PreContent.GetContent());
Assert.Equal(expectedContent, output.Content.GetContent());
Assert.Equal("Custom Content<ul><li style=\"display:none\"></li>" + Environment.NewLine + "</ul>",
output.PostContent.GetContent());
Assert.Equal(expectedTagName, output.TagName);
}
示例13: GetTypeNames_ReturnsExpectedResults
public void GetTypeNames_ReturnsExpectedResults(Type fieldType, string[] expectedResult)
{
// Arrange
var metadataProvider = new TestModelMetadataProvider();
var metadata = metadataProvider.GetMetadataForType(fieldType);
// Act
var typeNames = TemplateRenderer.GetTypeNames(metadata, fieldType);
// Assert
var collectionAssertions = expectedResult.Select<string, Action<string>>(expected =>
actual => Assert.Equal(expected, actual));
Assert.Collection(typeNames, collectionAssertions.ToArray());
}
示例14: EnterNestedScope_CopiesProperties
public void EnterNestedScope_CopiesProperties()
{
// Arrange
var bindingContext = new DefaultModelBindingContext
{
Model = new object(),
ModelMetadata = new TestModelMetadataProvider().GetMetadataForType(typeof(object)),
ModelName = "theName",
OperationBindingContext = new OperationBindingContext(),
ValueProvider = new SimpleValueProvider(),
ModelState = new ModelStateDictionary(),
};
var metadataProvider = new TestModelMetadataProvider();
metadataProvider.ForType<object>().BindingDetails(d =>
{
d.BindingSource = BindingSource.Custom;
d.BinderType = typeof(TestModelBinder);
d.BinderModelName = "custom";
});
var newModelMetadata = metadataProvider.GetMetadataForType(typeof(object));
// Act
var originalBinderModelName = bindingContext.BinderModelName;
var originalBindingSource = bindingContext.BindingSource;
var originalModelState = bindingContext.ModelState;
var originalOperationBindingContext = bindingContext.OperationBindingContext;
var originalValueProvider = bindingContext.ValueProvider;
var disposable = bindingContext.EnterNestedScope(
modelMetadata: newModelMetadata,
fieldName: "fieldName",
modelName: "modelprefix.fieldName",
model: null);
// Assert
Assert.Same(newModelMetadata.BinderModelName, bindingContext.BinderModelName);
Assert.Same(newModelMetadata.BindingSource, bindingContext.BindingSource);
Assert.Equal("fieldName", bindingContext.FieldName);
Assert.False(bindingContext.IsTopLevelObject);
Assert.Null(bindingContext.Model);
Assert.Same(newModelMetadata, bindingContext.ModelMetadata);
Assert.Equal("modelprefix.fieldName", bindingContext.ModelName);
Assert.Same(originalModelState, bindingContext.ModelState);
Assert.Same(originalOperationBindingContext, bindingContext.OperationBindingContext);
Assert.Same(originalValueProvider, bindingContext.ValueProvider);
disposable.Dispose();
}
示例15: CanCreateModel_ReturnsTrue_IfIsTopLevelObjectAndNotIsFirstChanceBinding
public async Task CanCreateModel_ReturnsTrue_IfIsTopLevelObjectAndNotIsFirstChanceBinding(
bool isTopLevelObject,
bool isFirstChanceBinding,
string binderModelName,
string modelName,
bool expectedCanCreate)
{
var mockValueProvider = new Mock<IValueProvider>();
mockValueProvider
.Setup(o => o.ContainsPrefixAsync(It.IsAny<string>()))
.Returns(Task.FromResult(false));
var metadataProvider = new TestModelMetadataProvider();
var bindingContext = new MutableObjectBinderContext
{
ModelBindingContext = new ModelBindingContext
{
IsTopLevelObject = isTopLevelObject,
IsFirstChanceBinding = isFirstChanceBinding,
// Random type.
ModelMetadata = metadataProvider.GetMetadataForType(typeof(Person)),
ValueProvider = mockValueProvider.Object,
OperationBindingContext = new OperationBindingContext
{
ValueProvider = mockValueProvider.Object,
MetadataProvider = metadataProvider,
ValidatorProvider = Mock.Of<IModelValidatorProvider>(),
},
// CanCreateModel() ignores the BinderModelName and ModelName properties.
BinderModelName = binderModelName,
ModelName = modelName,
},
};
var mutableBinder = new TestableMutableObjectModelBinder();
bindingContext.PropertyMetadata =
mutableBinder.GetMetadataForProperties(bindingContext.ModelBindingContext).ToArray();
// Act
var canCreate = await mutableBinder.CanCreateModel(bindingContext);
// Assert
Assert.Equal(expectedCanCreate, canCreate);
}