5dplomacy/MultiversalDiplomacyTests/ReplDriver.cs

52 lines
1.5 KiB
C#
Raw Normal View History

2024-08-27 04:18:36 +00:00
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="Ready"/> or <see cref="Closed"/> 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 Ready()
{
Assert.That(Handler, Is.Not.Null, "Handler is closed");
}
public void Closed()
{
Assert.That(Handler, Is.Null, "Handler is not closed");
}
}