Last active
February 1, 2024 16:17
-
-
Save aivascu/739f2a845eac587ca4df11cd9c5f7d31 to your computer and use it in GitHub Desktop.
Omit constructor initialized, ini-only record properties
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class OmitInitOnlyRecordProperties : ICustomization | |
{ | |
public void Customize(IFixture fixture) | |
{ | |
fixture.Customizations.Insert(0, new Omitter(new ExtenalInitPropertySpecification())); | |
} | |
private class ExtenalInitPropertySpecification : IRequestSpecification | |
{ | |
public bool IsSatisfiedBy(object request) | |
{ | |
return request is PropertyInfo propertyInfo | |
&& propertyInfo.DeclaringType.IsRecord() | |
&& propertyInfo.IsExternalInit() | |
&& propertyInfo.IsConstructorInitialized(); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class TypeExtensions | |
{ | |
public static bool IsConstructorInitialized(this PropertyInfo propertyInfo) | |
{ | |
var declaringType = propertyInfo.DeclaringType; | |
if(declaringType is null) | |
{ | |
return false; | |
} | |
return Array.Exists(declaringType.GetConstructors(), ctor => Array.Exists(ctor.GetParameters(), | |
param => param.ParameterType == propertyInfo.PropertyType && param.Name == propertyInfo.Name)); | |
} | |
public static bool IsExternalInit(this PropertyInfo propertyInfo) | |
{ | |
if (!propertyInfo.CanWrite || propertyInfo.SetMethod is null) | |
{ | |
return false; | |
} | |
return propertyInfo.SetMethod.ReturnParameter | |
.GetRequiredCustomModifiers().Contains(typeof(System.Runtime.CompilerServices.IsExternalInit)); | |
} | |
public static bool IsRecord(this Type? type) | |
{ | |
return type?.GetMethod("<Clone>$") is not null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment