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

94 lines
2.2 KiB
C#
Raw Normal View History

using FluentResults;
using pgLabII.PgUtils.ConnectionStrings;
using OneOf;
namespace pgLabII.PgUtils.Tests.ConnectionStrings;
using Elem = OneOf<PqToken, string, IError>;
internal class UnitTestTokenizer : IPqConnectionStringTokenizer
{
private readonly List<Elem> _tokens = new();
private int _position = 0;
public UnitTestTokenizer AddString(string output)
{
_tokens.Add(output);
return this;
}
public UnitTestTokenizer AddError(Error error)
{
_tokens.Add(error);
return this;
}
public UnitTestTokenizer AddEquals()
{
_tokens.Add(PqToken.Equals);
return this;
}
public void AddEof()
{
_tokens.Add(PqToken.Eof);
}
// note we do no whitespace at end tests here
public bool IsEof
{
get
{
EnsureNotEol();
return _tokens[_position].IsT0 && _tokens[_position].AsT0 == PqToken.Eof;
}
}
public Result<string> GetKeyword()
{
EnsureNotEol();
var elem = Consume();
return elem.Match<Result<string>>(
token => throw new Exception("Unexpected call to GetKeyword"),
str => str,
error => Result.Fail(error));
}
public Result ConsumeEquals()
{
EnsureNotEol();
var elem = Consume();
return elem.Match<Result>(
token =>
{
if (token != PqToken.Equals)
throw new Exception("Unexpected call to GetKeyword");
return Result.Ok();
},
str => throw new Exception("Unexpected call to ConsumeEquals"),
error => Result.Fail(error));
}
public Result<string> GetValue()
{
EnsureNotEol();
var elem = Consume();
return elem.Match<Result<string>>(
token => throw new Exception("Unexpected call to GetValue"),
str => str,
error => Result.Fail(error));
}
private Elem Consume()
{
return _tokens[_position++];
}
private void EnsureNotEol()
{
if (_position >= _tokens.Count)
throw new Exception("unexpected end of list in test, wrong parser call?");
}
}