pgLabII/pgLabII.PgUtils.Tests/ConnectionStrings/Util/UnitTestTokenizer.cs

85 lines
2 KiB
C#
Raw Normal View History

using pgLabII.PgUtils.ConnectionStrings;
namespace pgLabII.PgUtils.Tests.ConnectionStrings;
internal class UnitTestTokenizer : IPqConnectionStringTokenizer
{
private readonly struct Elem(PqToken result, object? output)
{
public readonly PqToken Result = result;
public readonly object? Output = output;
}
private readonly List<Elem> _tokens = [];
private int _position = 0;
public UnitTestTokenizer AddString(string? output)
{
_tokens.Add(new(PqToken.String, output));
return this;
}
public UnitTestTokenizer AddException(Exception? output)
{
_tokens.Add(new(PqToken.Exception, output));
return this;
}
public UnitTestTokenizer AddEquals()
{
_tokens.Add(new(PqToken.Equals, null));
return this;
}
// note we do no whitespace at end tests here
public bool Eof => _position >= _tokens.Count;
public string GetKeyword()
{
EnsureNotEof();
var elem = Consume();
if (elem.Result == PqToken.String)
return (string)elem.Output!;
throw new Exception("Unexpected call to GetKeyword");
}
public void ConsumeEquals()
{
EnsureNotEof();
var elem = Consume();
if (elem.Result == PqToken.Equals)
return;
throw new Exception("Unexpected call to ConsumeEquals");
}
public string GetValue()
{
EnsureNotEof();
var elem = Consume();
if (elem.Result == PqToken.String)
return (string)elem.Output!;
throw new Exception("Unexpected call to GetValue");
}
private Elem Consume()
{
var elem = _tokens[_position++];
if (elem.Result == PqToken.Exception)
{
throw (Exception)elem.Output!;
}
return elem;
}
private void EnsureNotEof()
{
if (Eof)
throw new Exception("unexpected eof in test, wrong parser call?");
}
}