Files
spectre.console/src/Spectre.Console.Testing/TestConsoleInput.cs
Patrik Svensson 3f57df5af6 Modernization of the code base (#1993)
* Update packages
* Convert extension methods to extension blocks
* Move extension methods closer to what they are extending
* Use ArgumentNullException.ThrowIfNull
* Move WriteAnsi and ToAnsi methods to Spectre.Console namespace
* Make shared global state obsolete
* Make AnsiConsole.Clear an extension method
* Linting should not fail build
2026-01-05 00:32:54 +01:00

92 lines
2.4 KiB
C#

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