-
-
Notifications
You must be signed in to change notification settings - Fork 524
/
Copy pathTestConsoleInput.cs
95 lines (83 loc) · 2.45 KB
/
TestConsoleInput.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
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)
{
if (input is null)
{
throw new ArgumentNullException(nameof(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));
}
}