namespace Spectre.Console.Testing;
///
/// Represents a testable console input mechanism.
///
public sealed class TestConsoleInput : IAnsiConsoleInput
{
private readonly Queue _input;
///
/// Initializes a new instance of the class.
///
public TestConsoleInput()
{
_input = new Queue();
}
///
/// Pushes the specified text to the input queue.
///
/// The input string.
public void PushText(string input)
{
if (input is null)
{
throw new ArgumentNullException(nameof(input));
}
foreach (var character in input)
{
PushCharacter(character);
}
}
///
/// Pushes the specified text followed by 'Enter' to the input queue.
///
/// The input.
public void PushTextWithEnter(string input)
{
PushText(input);
PushKey(ConsoleKey.Enter);
}
///
/// Pushes the specified character to the input queue.
///
/// The input.
public void PushCharacter(char input)
{
var control = char.IsUpper(input);
_input.Enqueue(new ConsoleKeyInfo(input, (ConsoleKey)input, false, false, control));
}
///
/// Pushes the specified key to the input queue.
///
/// The input.
public void PushKey(ConsoleKey input)
{
_input.Enqueue(new ConsoleKeyInfo((char)input, input, false, false, false));
}
///
public bool IsKeyAvailable()
{
return _input.Count > 0;
}
///
public ConsoleKeyInfo? ReadKey(bool intercept)
{
if (_input.Count == 0)
{
throw new InvalidOperationException("No input available.");
}
return _input.Dequeue();
}
///
public Task ReadKeyAsync(bool intercept, CancellationToken cancellationToken)
{
return Task.FromResult(ReadKey(intercept));
}
}