Skip to content

Instantly share code, notes, and snippets.

@aivascu
Created March 24, 2022 19:08
Show Gist options
  • Save aivascu/80257daa1dfcdc8a3dcd782b8fd63ba1 to your computer and use it in GitHub Desktop.
Save aivascu/80257daa1dfcdc8a3dcd782b8fd63ba1 to your computer and use it in GitHub Desktop.
Random relay customization
public class RandomRelayCustomization : ISpecimenBuilder
{
private readonly List<ISpecimenBuilder> builders;
private readonly IEnumerator<int> randomizer;
public RandomRelayCustomization(params ISpecimenBuilder[] builders)
: this(builders.AsEnumerable())
{
}
public RandomRelayCustomization(IEnumerable<ISpecimenBuilder> builders)
{
if (builders is null)
{
throw new ArgumentNullException(nameof(builders));
}
this.builders = builders.ToList();
this.randomizer = new RoundRobinSequence(0, this.builders.Count - 1)
.GetEnumerator();
}
public object Create(object request, ISpecimenContext context)
{
this.randomizer.MoveNext();
var builder = this.builders[this.randomizer.Current];
return builder.Create(request, context);
}
}
public class RoundRobinSequence : IEnumerable<int>
{
private readonly int min;
private readonly int max;
private int current;
public RoundRobinSequence(int min, int max)
{
this.min = min;
this.max = max;
this.current = min;
}
public IEnumerator<int> GetEnumerator()
{
while (true)
{
this.current++;
if (this.current > this.max)
{
this.current = this.current % 2 == 0 ? this.min + 1 : this.min;
}
yield return this.current;
this.current++;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment