-
Notifications
You must be signed in to change notification settings - Fork 841
Introduce type converter for DataClassification #5887
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 7 commits
859042b
736df75
5f7f28d
fddeecb
4edc94b
77aac5c
c30c587
ffd482f
e708e88
1e43155
e35d2ad
72d1c8b
73e3ec1
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,106 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| using System; | ||
| using System.ComponentModel; | ||
| using System.Globalization; | ||
| using Microsoft.Shared.Diagnostics; | ||
|
|
||
| namespace Microsoft.Extensions.Compliance.Classification; | ||
|
|
||
| /// <summary> | ||
| /// Provides a way to convert a <see cref="DataClassification"/> to and from a string. | ||
| /// </summary> | ||
| public class DataClassificationTypeConverter : TypeConverter | ||
|
Check failure on line 14 in src/Libraries/Microsoft.Extensions.Compliance.Abstractions/Classification/DataClassificationTypeConverter.cs
|
||
| { | ||
| private const char Delimiter = ':'; | ||
|
|
||
| /// <inheritdoc/> | ||
| public override bool CanConvertFrom(ITypeDescriptorContext? context, Type sourceType) | ||
| { | ||
| return sourceType == typeof(string); | ||
| } | ||
|
|
||
| /// <inheritdoc/> | ||
| public override bool CanConvertTo(ITypeDescriptorContext? context, Type? destinationType) | ||
| { | ||
| return destinationType == typeof(DataClassification); | ||
| } | ||
|
|
||
| /// <inheritdoc/> | ||
| public override object? ConvertFrom(ITypeDescriptorContext? context, CultureInfo? culture, object value) | ||
| { | ||
| if (value is not string stringValue) | ||
| { | ||
| Throw.ArgumentException(nameof(value), "Value must be a string."); | ||
|
|
||
| // unreachable, but need to satisfy static analysis | ||
| return DataClassification.Unknown; | ||
| } | ||
|
|
||
| if (stringValue == nameof(DataClassification.None)) | ||
| { | ||
| return DataClassification.None; | ||
| } | ||
|
|
||
| if (stringValue == nameof(DataClassification.Unknown)) | ||
| { | ||
| return DataClassification.Unknown; | ||
| } | ||
|
|
||
| if (TryParse(stringValue, out var taxonomyName, out var taxonomyValue)) | ||
| { | ||
| return new DataClassification(taxonomyName, taxonomyValue); | ||
| } | ||
|
|
||
| throw new FormatException($"Invalid data classification format: '{stringValue}'."); | ||
| } | ||
|
|
||
| /// <inheritdoc/> | ||
| public override bool IsValid(ITypeDescriptorContext? context, object? value) | ||
| { | ||
| if (value is not string stringValue) | ||
| { | ||
| return false; | ||
| } | ||
|
|
||
| if (stringValue == nameof(DataClassification.None) || | ||
| stringValue == nameof(DataClassification.Unknown)) | ||
| { | ||
| return true; | ||
| } | ||
|
|
||
| return TryParse(stringValue, out var taxonomyName, out var taxonomyValue); | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Attempts to parse a string in the format "TaxonomyName:Value". | ||
| /// </summary> | ||
| /// <param name="value">The input string to parse.</param> | ||
| /// <param name="taxonomyName">When this method returns, contains the parsed taxonomy name if the parsing succeeded, or an empty string if it failed.</param> | ||
| /// <param name="taxonomyValue">When this method returns, contains the parsed taxonomy value if the parsing succeeded, or the original input string if it failed.</param> | ||
| /// <returns><see langword="true"/> if the string was successfully parsed; otherwise, <see langword="false"/>.</returns> | ||
| private static bool TryParse(string value, out string taxonomyName, out string taxonomyValue) | ||
| { | ||
| taxonomyName = string.Empty; | ||
| taxonomyValue = value; | ||
|
|
||
| if (value.Length <= 1) | ||
| { | ||
| return false; | ||
| } | ||
|
|
||
| ReadOnlySpan<char> valueSpan = value.AsSpan(); | ||
| int index = valueSpan.IndexOf(Delimiter); | ||
|
|
||
| if (index <= 0 || index >= (value.Length - 1)) | ||
| { | ||
| return false; | ||
| } | ||
|
|
||
| taxonomyName = valueSpan.Slice(0, index).ToString(); | ||
| taxonomyValue = valueSpan.Slice(index + 1).ToString(); | ||
|
|
||
| return true; | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,176 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| using System; | ||
| using System.Collections.Generic; | ||
| using FluentAssertions; | ||
| using Microsoft.Extensions.Configuration; | ||
| using Microsoft.Extensions.DependencyInjection; | ||
| using Microsoft.Extensions.Options; | ||
| using Xunit; | ||
|
|
||
| namespace Microsoft.Extensions.Compliance.Classification.Tests; | ||
|
|
||
| public class DataClassificationTypeConverterTests | ||
| { | ||
| public static IEnumerable<object[]> DefaultDataClassificationTestData() | ||
| { | ||
| yield return new object[] { "None", DataClassification.None }; | ||
| yield return new object[] { "Unknown", DataClassification.Unknown }; | ||
| } | ||
|
|
||
| public static IEnumerable<object[]> CustomDataClassificationTestData() | ||
| { | ||
| yield return new object[] { "Example:Test", new DataClassification("Example", "Test") }; | ||
| yield return new object[] { "Taxonomy:Value", new DataClassification("Taxonomy", "Value") }; | ||
| yield return new object[] { "Custom:Data", new DataClassification("Custom", "Data") }; | ||
| } | ||
|
|
||
| [Fact] | ||
| public void BindServiceCollection_ShouldReturnIOptionsWithExpectedDataClassification() | ||
| { | ||
| // Arrange | ||
| var configuration = new ConfigurationBuilder() | ||
| .AddInMemoryCollection(new[] | ||
| { | ||
| new KeyValuePair<string, string?>("Key:Example", "Example:Test"), | ||
| new KeyValuePair<string, string?>("Key:Facts:Value", "Taxonomy:Value"), | ||
| new KeyValuePair<string, string?>("Key:Facts:Data", "Custom:Data"), | ||
| new KeyValuePair<string, string?>("Key:Facts:None", "None"), | ||
| new KeyValuePair<string, string?>("Key:Facts:Unknown", "Unknown"), | ||
| new KeyValuePair<string, string?>("Key:Facts:Invalid", "Invalid"), | ||
| }) | ||
| .Build(); | ||
|
|
||
| IServiceCollection serviceCollection = new ServiceCollection() | ||
| .Configure<TestOptions>(configuration.GetSection("Key")); | ||
|
|
||
| // Act | ||
| using var sp = serviceCollection.BuildServiceProvider(); | ||
| var options = sp.GetRequiredService<IOptions<TestOptions>>(); | ||
|
|
||
| var expected = new Dictionary<string, DataClassification> | ||
| { | ||
| { "Value", new DataClassification("Taxonomy", "Value") }, | ||
| { "Data", new DataClassification("Custom", "Data") }, | ||
| { "None", DataClassification.None }, | ||
| { "Unknown", DataClassification.Unknown }, | ||
| }; | ||
|
|
||
| // Assert | ||
| options.Value.Example.Should().NotBeNull().And.Be(new DataClassification("Example", "Test")); | ||
| options.Value.Facts.Should().NotBeEmpty().And.Equal(expected); | ||
|
|
||
| // Odd quirk: binding to dictionary succeeds but doesn't include invalid values | ||
| options.Value.Facts.Should().NotContainKey("Invalid"); | ||
| } | ||
|
|
||
| [Theory] | ||
| [InlineData(typeof(string), true)] | ||
| [InlineData(typeof(int), false)] | ||
| [InlineData(typeof(DataClassification), false)] | ||
| public void CanConvertFrom_ShouldReturnExpectedResult(Type sourceType, bool expected) | ||
| { | ||
| // Arrange | ||
| var converter = new DataClassificationTypeConverter(); | ||
|
|
||
| // Act | ||
| var result = converter.CanConvertFrom(null, sourceType); | ||
|
|
||
| // Assert | ||
| result.Should().Be(expected); | ||
| } | ||
|
|
||
| [Theory] | ||
| [InlineData(typeof(DataClassification), true)] | ||
| [InlineData(typeof(int), false)] | ||
| [InlineData(typeof(string), false)] | ||
| public void CanConvertTo_ShouldReturnExpectedResult(Type destinationType, bool expected) | ||
| { | ||
| // Arrange | ||
| var converter = new DataClassificationTypeConverter(); | ||
|
|
||
| // Act | ||
| var result = converter.CanConvertTo(null, destinationType); | ||
|
|
||
| // Assert | ||
| result.Should().Be(expected); | ||
| } | ||
|
|
||
| [Theory] | ||
| [InlineData("None", "", "None")] | ||
| [InlineData("Unknown", "", "Unknown")] | ||
| [InlineData("Example:Test", "Example", "Test")] | ||
| public void ConvertFrom_ShouldReturnExpectedResult_ForValidInput(string input, string expectedTaxonomyName, string expectedValue) | ||
| { | ||
| // Arrange | ||
| var converter = new DataClassificationTypeConverter(); | ||
|
|
||
| // Act | ||
| var result = converter.ConvertFrom(null, null, input); | ||
|
|
||
| // Assert | ||
| result.Should().NotBeNull(); | ||
| result.Should().BeOfType<DataClassification>(); | ||
|
|
||
| #pragma warning disable CS8605 // Unboxing a possibly null value. | ||
| var dataClassification = (DataClassification)result; | ||
| #pragma warning restore CS8605 // Unboxing a possibly null value. | ||
|
|
||
| dataClassification.TaxonomyName.Should().Be(expectedTaxonomyName); | ||
| dataClassification.Value.Should().Be(expectedValue); | ||
| } | ||
|
|
||
| [Theory] | ||
| [InlineData("InvalidFormat", typeof(FormatException))] | ||
| [InlineData("InvalidFormat:", typeof(FormatException))] | ||
| [InlineData(":InvalidFormat", typeof(FormatException))] | ||
| [InlineData(":", typeof(FormatException))] | ||
| [InlineData("", typeof(FormatException))] | ||
| [InlineData(42, typeof(ArgumentException))] | ||
| [InlineData(false, typeof(ArgumentException))] | ||
| public void ConvertFrom_ShouldThrowException_ForInvalidInput(object input, Type expectedException) | ||
| { | ||
| // Arrange | ||
| var converter = new DataClassificationTypeConverter(); | ||
|
|
||
| // Act | ||
| var act = () => converter.ConvertFrom(null, null, input); | ||
|
|
||
| // Assert | ||
| Assert.Throws(expectedException, act); | ||
| } | ||
|
|
||
| [Theory] | ||
| [InlineData("None", true)] | ||
| [InlineData("Unknown", true)] | ||
| [InlineData("Example:Test", true)] | ||
| [InlineData("InvalidFormat", false)] | ||
| [InlineData("InvalidFormat:", false)] | ||
| [InlineData(":InvalidFormat", false)] | ||
| [InlineData(":", false)] | ||
| [InlineData("", false)] | ||
| [InlineData(42, false)] | ||
| [InlineData(false, false)] | ||
| public void IsValid_ShouldReturnExpectedResult(object input, bool expected) | ||
| { | ||
| // Arrange | ||
| var converter = new DataClassificationTypeConverter(); | ||
|
|
||
| // Act | ||
| var result = converter.IsValid(null, input); | ||
|
|
||
| // Assert | ||
| result.Should().Be(expected); | ||
| } | ||
|
|
||
| private class TestOptions | ||
| { | ||
| #pragma warning disable S3459 // Unassigned members should be removed | ||
| #pragma warning disable S1144 // Unused private types or members should be removed | ||
| public DataClassification? Example { get; set; } | ||
| #pragma warning restore S1144 // Unused private types or members should be removed | ||
| #pragma warning restore S3459 // Unassigned members should be removed | ||
| public IDictionary<string, DataClassification> Facts { get; set; } = new Dictionary<string, DataClassification>(); | ||
| } | ||
| } | ||
Uh oh!
There was an error while loading. Please reload this page.