Skip to content

Instantly share code, notes, and snippets.

@jnm2

jnm2/Has.cs Secret

Created February 1, 2017 00:56
Show Gist options
  • Save jnm2/f5c4e2224114d23e566467dbf1467128 to your computer and use it in GitHub Desktop.
Save jnm2/f5c4e2224114d23e566467dbf1467128 to your computer and use it in GitHub Desktop.
Has.MaxTime prototype
using System;
using System.Diagnostics;
using NUnit.Framework;
using NUnit.Framework.Constraints;
public sealed class Has : NUnit.Framework.Has
{
public static ResolvableConstraintExpression MaxTime(int milliseconds) => MaxTime(TimeSpan.FromMilliseconds(milliseconds));
public static ResolvableConstraintExpression MaxTime(TimeSpan maxTime) => new ConstraintExpression().Append(new MaxTimeOperator(maxTime));
public sealed class MaxTimeOperator : SelfResolvingOperator
{
private readonly TimeSpan maxTime;
public MaxTimeOperator(TimeSpan maxTime)
{
this.maxTime = maxTime;
left_precedence = 1;
right_precedence = 100;
}
public override void Reduce(ConstraintBuilder.ConstraintStack stack)
{
stack.Push(new MaxTimeConstraint(maxTime));
}
}
public sealed class MaxTimeConstraint : Constraint
{
private readonly TimeSpan maxTime;
public MaxTimeConstraint(TimeSpan maxTime)
{
this.maxTime = maxTime;
}
public override string Description => $"maximum time {maxTime}";
private static void InvokeTestDelegate(object @delegate)
{
@delegate.Match(
(TestDelegate _) => _.Invoke(),
(AsyncTestDelegate _) => _.Invoke().GetAwaiter().GetResult(),
(object _) => { throw new NotSupportedException(_.GetType().Name); });
}
public override ConstraintResult ApplyTo<TActual>(TActual actual)
{
var stopwatch = Stopwatch.StartNew();
InvokeTestDelegate(actual);
stopwatch.Stop();
return new ConstraintResult(this, stopwatch.Elapsed, stopwatch.Elapsed <= maxTime);
}
protected override object GetTestObject<TActual>(ActualValueDelegate<TActual> del)
{
return (TestDelegate)(() => del());
}
}
}
@bmolnar2
Copy link

bmolnar2 commented Oct 16, 2017

@jnm2, this defines quite well the structure we need to implement for the Has.MaxTime. What we miss here, is the implementation to execute the delegate, that InvokeTestDelegate will have to do. Am I right?
I guess ExceptionInterceptor's implementation could be shared and reused by MaxTimeConstraint.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment