Skip to content

Commit

Permalink
Fix options Validation with objects have indexers (#92309)
Browse files Browse the repository at this point in the history
  • Loading branch information
tarekgh authored Sep 20, 2023
1 parent fcf7b11 commit 5883b72
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,8 @@ private static bool TryValidateOptions(object options, string qualifiedName, Lis

foreach (PropertyInfo propertyInfo in options.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public))
{
if (propertyInfo.GetMethod is null)
// Indexers are properties which take parameters. Ignore them.
if (propertyInfo.GetMethod is null || propertyInfo.GetMethod.GetParameters().Length > 0)
{
continue;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,30 @@ public void TestValidationWithEnumeration()
result2.Failures);
}

[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotBrowser))]
public void TestObjectsWithIndexerProperties()
{
DataAnnotationValidateOptions<MyDictionaryOptions> dataAnnotationValidateOptions1 = new("MyDictionaryOptions");
MyDictionaryOptionsOptionsValidator sourceGenOptionsValidator1 = new();

var options1 = new MyDictionaryOptions();
ValidateOptionsResult result1 = sourceGenOptionsValidator1.Validate("MyDictionaryOptions", options1);
ValidateOptionsResult result2 = dataAnnotationValidateOptions1.Validate("MyDictionaryOptions", options1);

Assert.True(result1.Succeeded);
Assert.True(result2.Succeeded);

DataAnnotationValidateOptions<MyListOptions<string>> dataAnnotationValidateOptions2 = new("MyListOptions");
MyListOptionsOptionsValidator sourceGenOptionsValidator2 = new();

var options2 = new MyListOptions<string>() { Prop = "test" };
result1 = sourceGenOptionsValidator2.Validate("MyListOptions", options2);
result2 = dataAnnotationValidateOptions2.Validate("MyListOptions", options2);

Assert.True(result1.Succeeded);
Assert.True(result2.Succeeded);
}

[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotBrowser))]
public void TestValidationWithCyclicReferences()
{
Expand Down Expand Up @@ -302,6 +326,12 @@ public partial class MySourceGenOptionsValidator : IValidateOptions<MyOptions>
{
}

public class MyDictionaryOptions : Dictionary<string, string> { [Required] public string Prop { get; set; } = "test"; }
[OptionsValidator] public partial class MyDictionaryOptionsOptionsValidator : IValidateOptions<MyDictionaryOptions> { }

public class MyListOptions<T> : List<T> { [Required] public T Prop { get; set; } = default; }
[OptionsValidator] public partial class MyListOptionsOptionsValidator : IValidateOptions<MyListOptions<string>> { }

#if NET8_0_OR_GREATER
public class OptionsUsingNewAttributes
{
Expand Down

0 comments on commit 5883b72

Please sign in to comment.