5dplomacy/MultiversalDiplomacyTests/ReplDriver.cs

52 lines
1.6 KiB
C#

using NUnit.Framework;
using MultiversalDiplomacy.Script;
namespace MultiversalDiplomacyTests;
public class ReplDriver(IScriptHandler initialHandler, bool echo = false)
{
public IScriptHandler? Handler { get; private set; } = initialHandler;
private string? LastInput { get; set; } = "";
/// <summary>
/// Whether to print the inputs as they are executed. This is primarily a debugging aid.
/// </summary>
bool Echo { get; } = echo;
/// <summary>
/// Input a multiline string into the repl. Call <see cref="AssertReady"/> or <see cref="AssertClosed"/> at the end so the
/// statement is valid.
/// </summary>
public ReplDriver this[string input] => ExecuteAll(input);
public ReplDriver ExecuteAll(string multiline)
{
var lines = multiline.Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
return lines.Aggregate(this, (repl, line) => repl.Execute(line));
}
public ReplDriver Execute(string inputLine)
{
if (Handler is null) throw new AssertionException(
$"Cannot execute \"{inputLine}\", handler quit. Last input was \"{LastInput}\"");
if (Echo) Console.WriteLine($"{Handler.Prompt}{inputLine}");
Handler = Handler.HandleInput(inputLine);
LastInput = inputLine;
return this;
}
public void AssertReady()
{
if (Handler is null) Assert.Fail($"Handler terminated after \"{LastInput}\"");
}
public void AssertClosed()
{
if (Handler is not null) Assert.Fail($"Handler did not terminate after \"{LastInput}\"");
}
}