Skip to content

Instantly share code, notes, and snippets.

@jnm2
Created November 11, 2021 00:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jnm2/a2840d7d3cd02ffba1a1574e53f7d1ff to your computer and use it in GitHub Desktop.
Save jnm2/a2840d7d3cd02ffba1a1574e53f7d1ff to your computer and use it in GitHub Desktop.
using System;
using System.Reflection;
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal;
using NUnit.Framework.Internal.Commands;
[AttributeUsage(AttributeTargets.Method)]
public sealed class SeedAttribute : Attribute, IWrapSetUpTearDown
{
public SeedAttribute(int randomSeed)
{
RandomSeed = randomSeed;
}
public int RandomSeed { get; }
public TestCommand Wrap(TestCommand command)
{
return new SeedCommand(command, RandomSeed);
}
private sealed class SeedCommand : DelegatingTestCommand
{
private readonly int randomSeed;
public SeedCommand(TestCommand innerCommand, int randomSeed) : base(innerCommand)
{
this.randomSeed = randomSeed;
}
public override TestResult Execute(TestExecutionContext context)
{
ResetRandomSeed(context, randomSeed);
try
{
return innerCommand.Execute(context);
}
finally
{
if (context.CurrentTest.Seed != randomSeed)
throw new InvalidOperationException($"{nameof(SeedAttribute)} cannot be used together with an attribute or test that changes the seed.");
}
}
}
private static void ResetRandomSeed(TestExecutionContext context, int seed)
{
context.CurrentTest.Seed = seed;
typeof(TestExecutionContext)
.GetField("_randomGenerator", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly)
.SetValue(context, null);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment