Skip to content

Instantly share code, notes, and snippets.

@aivascu
Last active February 1, 2024 16:17
Show Gist options
  • Save aivascu/739f2a845eac587ca4df11cd9c5f7d31 to your computer and use it in GitHub Desktop.
Save aivascu/739f2a845eac587ca4df11cd9c5f7d31 to your computer and use it in GitHub Desktop.
Omit constructor initialized, ini-only record properties
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();
}
}
}
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