Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 4 additions & 7 deletions src/Validation/src/ValidateContext.cs
Original file line number Diff line number Diff line change
@@ -1,16 +1,14 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Linq;

namespace Microsoft.Extensions.Validation;

/// <summary>
/// Represents the context for validating a validatable object.
/// </summary>
public sealed class ValidateContext
{
private Dictionary<string, List<ValidationError>>? _validationErrors;
private Dictionary<string, IReadOnlyList<ValidationError>>? _validationErrors;

/// <summary>
/// Initializes a new instance of <see cref="ValidateContext"/>.
Expand Down Expand Up @@ -46,7 +44,7 @@ public ValidateContext()
/// There are no guarantees whether or not this dictionary is lazy. Usages should treat null and empty dictionary the same.
/// </remarks>
public IReadOnlyDictionary<string, IReadOnlyList<ValidationError>>? ValidationErrors
=> _validationErrors?.ToDictionary(kvp => kvp.Key, kvp => (IReadOnlyList<ValidationError>)kvp.Value.AsReadOnly()).AsReadOnly();
=> _validationErrors;

/// <summary>
/// Gets or sets the current depth in the validation hierarchy.
Expand All @@ -62,15 +60,14 @@ public IReadOnlyDictionary<string, IReadOnlyList<ValidationError>>? ValidationEr
/// <param name="validationError">The validation error to add.</param>
public void AddValidationError(ValidationError validationError)
{
_validationErrors ??= new Dictionary<string, List<ValidationError>>();

_validationErrors ??= new Dictionary<string, IReadOnlyList<ValidationError>>();
if (!_validationErrors.TryGetValue(validationError.Path, out var existingErrors))
{
_validationErrors.Add(validationError.Path, new List<ValidationError> { validationError });
}
else
{
existingErrors.Add(validationError);
((List<ValidationError>)existingErrors).Add(validationError);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// The .NET Foundation licenses this file to you under the MIT license.

using System.ComponentModel.DataAnnotations;
using System.Diagnostics;
using System.Reflection;

namespace Microsoft.Extensions.Validation.Tests;
Expand Down Expand Up @@ -108,6 +109,29 @@ public async Task Validate_WithEnumerableOfValidatableType_ValidatesEachItem(boo
Assert.Equal("The Name field is required.", error.Value.Select(e => e.ErrorMessage).Single());
}

[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task Validate_WithEnumerableOfValidatableType_ValidatesEachItem_AccessingValidationErrorsDoesNotCopy(bool useAsync)
{
var (provider, options) = GeneratedValidationTestHelpers.CreateValidationServices();
var parameterInfo = GetParameter(nameof(ParameterActions.PeopleParameter));
Assert.True(options.TryGetValidatableParameterInfo(parameterInfo, out var paramInfo));
var context = GeneratedValidationTestHelpers.CreateContext(provider, options);

var array = new ParameterPerson[10000];
for (var i = 0; i < array.Length; i++)
{
array[i] = new ParameterPerson();
}

await ValidateAsync(paramInfo, array, context, useAsync, default);

Assert.NotNull(context.ValidationErrors);
Assert.True(ReferenceEquals(context.ValidationErrors, context.ValidationErrors));
Assert.Equal(array.Length, context.ValidationErrors.Count);
}

[Theory]
[InlineData(true)]
[InlineData(false)]
Expand Down Expand Up @@ -158,37 +182,6 @@ public async Task Validate_ExceptionDuringValidation_Rethrown(bool useAsync)
Assert.True(context.ValidationErrors is null || context.ValidationErrors.Count == 0);
}

[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task ValidationErrors_ReturnsImmutableCollections(bool useAsync)
{
var (provider, options) = GeneratedValidationTestHelpers.CreateValidationServices();
var parameterInfo = GetParameter(nameof(ParameterActions.RequiredParameter));
Assert.True(options.TryGetValidatableParameterInfo(parameterInfo, out var paramInfo));
var context = GeneratedValidationTestHelpers.CreateContext(provider, options);

await ValidateAsync(paramInfo, null, context, useAsync, default);

var errors = context.ValidationErrors;
Assert.NotNull(errors);

// The outer dictionary must not be castable to a mutable Dictionary
Assert.False(errors is Dictionary<string, IReadOnlyList<ValidationError>>);

// The value lists must not be castable to a mutable List<ValidationError>
var value = Assert.Single(errors).Value;
Assert.False(value is List<ValidationError>);

// Attempting to mutate the outer dictionary must throw
Assert.Throws<NotSupportedException>(() =>
((IDictionary<string, IReadOnlyList<ValidationError>>)errors)["newKey"] = []);

// Attempting to mutate a value list must throw
Assert.Throws<NotSupportedException>(() =>
((IList<ValidationError>)value).Add(new ValidationError { Name = "x", Path = "x", ErrorMessage = "x", Container = null }));
}

private static ParameterInfo GetParameter(string methodName)
=> typeof(ParameterActions).GetMethod(methodName)!.GetParameters()[0];
}
Expand Down
Loading