Skip to content

Instantly share code, notes, and snippets.

@fiseni
Last active April 3, 2026 08:06
Show Gist options
  • Select an option

  • Save fiseni/aa78e0b6c3e51d41e0683e227ddc297c to your computer and use it in GitHub Desktop.

Select an option

Save fiseni/aa78e0b6c3e51d41e0683e227ddc297c to your computer and use it in GitHub Desktop.
Verify Scrubber for int Id values
using System.Collections.Concurrent;
namespace Tests.VerifyConfigurations;
public static class VerifyInitializer
{
public static void Initialize()
{
Verifier.DerivePathInfo((sourceFile, projectDirectory, type, method) =>
new PathInfo(directory: $"Snapshots/{type.Name}"));
VerifierSettings.AddExtraSettings(settings =>
{
settings.Converters.Add(new IntegerIdConverter());
});
}
}
public sealed class IntegerIdConverter : WriteOnlyJsonConverter
{
private static readonly ConcurrentDictionary<(VerifyJsonWriter, string), IntegerIdContext> _contextByScope = [];
public override bool CanConvert(Type type)
=> type == typeof(int) || type == typeof(long) || type == typeof(int?) || type == typeof(long?);
public override void Write(VerifyJsonWriter writer, object value)
{
var propertyName = GetPropertyName(writer.Path);
if (!propertyName.EndsWith("Id", StringComparison.OrdinalIgnoreCase))
{
writer.WriteValue(value);
return;
}
var scope = propertyName.Equals("Id", StringComparison.OrdinalIgnoreCase)
? GetModelScope(writer.Path)
: propertyName.ToString();
var context = _contextByScope.GetOrAdd((writer, scope), _ => new());
var key = Convert.ToInt64(value);
if (!context.Mapping.TryGetValue(key, out var placeholder))
{
placeholder = $"{propertyName}_{++context.Counter}";
context.Mapping[key] = placeholder;
}
writer.WriteValue(placeholder);
}
public static ReadOnlySpan<char> GetPropertyName(ReadOnlySpan<char> path)
{
var lastDot = path.LastIndexOf('.');
var lastSegment = lastDot >= 0 ? path[(lastDot + 1)..] : path;
var bracketIndex = lastSegment.IndexOf('[');
return bracketIndex >= 0 ? lastSegment[..bracketIndex] : lastSegment;
}
private static string GetModelScope(ReadOnlySpan<char> path)
{
var lastDot = path.LastIndexOf('.');
if (lastDot < 0) return "root";
var parentPath = path[..lastDot];
var entitySegment = GetPropertyName(parentPath);
return entitySegment.IsEmpty ? "root" : entitySegment.ToString();
}
private sealed class IntegerIdContext
{
public Dictionary<long, string> Mapping { get; } = [];
public int Counter { get; set; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment