TimeoutCommand
TimeoutCommand creates a timer in order to cancel
a test if it exceeds a specified time and adjusts
the test result if it did time out.
using NUnit.Framework.Interfaces;
using System.Threading;
namespace NUnit.Framework.Internal.Commands
{
public class TimeoutCommand : BeforeAndAfterTestCommand
{
private Timer _commandTimer;
private bool _commandTimedOut;
public TimeoutCommand(TestCommand innerCommand, int timeout)
: base(innerCommand)
{
Guard.ArgumentValid(innerCommand.Test is TestMethod, "TimeoutCommand may only apply to a TestMethod", "innerCommand");
Guard.ArgumentValid(timeout > 0, "Timeout value must be greater than zero", "timeout");
BeforeTest = delegate {
Thread testThread = Thread.CurrentThread;
int nativeThreadId = ThreadUtility.GetCurrentThreadNativeId();
_commandTimer = new Timer(delegate {
_commandTimedOut = true;
ThreadUtility.Abort(testThread, nativeThreadId);
}, null, timeout, -1);
};
AfterTest = delegate(TestExecutionContext context) {
_commandTimer.Dispose();
if (_commandTimedOut)
context.CurrentResult.SetResult(ResultState.Failure, $"""{timeout}""");
};
}
}
}