Skip to content

Commit

Permalink
ConsoleInput test
Browse files Browse the repository at this point in the history
  • Loading branch information
tznind committed Dec 16, 2024
1 parent e0f6643 commit efd6b97
Show file tree
Hide file tree
Showing 2 changed files with 82 additions and 19 deletions.
44 changes: 25 additions & 19 deletions Terminal.Gui/ConsoleDrivers/V2/ConsoleInput.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,34 +28,40 @@ public void Initialize (ConcurrentQueue<T> inputBuffer)
/// <inheritdoc />
public void Run (CancellationToken token)
{
if (_inputBuffer == null)
try
{
throw new ("Cannot run input before Initialization");
}

do
{
var dt = Now ();
if (_inputBuffer == null)
{
throw new ("Cannot run input before Initialization");
}

if (Peek ())
do
{
foreach (var r in Read ())
var dt = Now ();

if (Peek ())
{
_inputBuffer.Enqueue (r);
foreach (var r in Read ())
{
_inputBuffer.Enqueue (r);
}
}
}

var took = Now () - dt;
var sleepFor = TimeSpan.FromMilliseconds (20) - took;
var took = Now () - dt;
var sleepFor = TimeSpan.FromMilliseconds (20) - took;

if (sleepFor.Milliseconds > 0)
{
Task.Delay (sleepFor, token).Wait (token);
}
if (sleepFor.Milliseconds > 0)
{
Task.Delay (sleepFor, token).Wait (token);
}

token.ThrowIfCancellationRequested ();
token.ThrowIfCancellationRequested ();
}
while (!token.IsCancellationRequested);
}
catch (OperationCanceledException)
{
}
while (!token.IsCancellationRequested);
}

/// <summary>
Expand Down
57 changes: 57 additions & 0 deletions UnitTests/ConsoleDrivers/V2/ConsoleInputTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace UnitTests.ConsoleDrivers.V2;
public class ConsoleInputTests
{
class FakeInput : ConsoleInput<char>
{
private readonly string [] _reads;

public FakeInput (params string [] reads ) { _reads = reads; }

int iteration = 0;
/// <inheritdoc />
protected override bool Peek ()
{
return iteration < _reads.Length;
}

/// <inheritdoc />
protected override IEnumerable<char> Read ()
{
return _reads [iteration++];
}
}

[Fact]
public void Test_ThrowsIfNotInitialized ()
{
var input = new FakeInput ("Fish");

var ex = Assert.Throws<Exception>(()=>input.Run (new (canceled: true)));
Assert.Equal ("Cannot run input before Initialization", ex.Message);
}


[Fact]
public void Test_Simple ()
{
var input = new FakeInput ("Fish");
var queue = new ConcurrentQueue<char> ();

input.Initialize (queue);

var cts = new CancellationTokenSource ();
cts.CancelAfter (25); // Cancel after 25 milliseconds
CancellationToken token = cts.Token;
Assert.Empty (queue);
input.Run (token);

Assert.Equal ("Fish",new string (queue.ToArray ()));
}
}

0 comments on commit efd6b97

Please sign in to comment.