mirror of
https://github.com/gui-cs/Terminal.Gui.git
synced 2025-12-27 16:27:55 +01:00
* Removed resharper settings from editorconfig * Remove constructors with frame parameters from Button class. * Remove constructors with frame parameters from CheckBox class. * Cleanup code. * Remove constructors with frame parameters from ComboBox class. * @BDisp Remove constructors with frame parameters from FrameView class. * Remove constructors with frame parameters from Label class. * Remove constructors with frame parameters from ListView class. * Remove constructors with frame parameters from ScrollBarView class. * Remove constructors with frame parameters from ScrollView class. * Remove namespace braces. * Cleanup code. * Cleanup code. * Cleanup code. * Remove constructors with frame parameters from TextField class. * Remove constructors with frame parameters from TimeField class. * Fixes #3182. OnResizeNeeded returns int.MaxValue and int.MaxValue when Application.Top is null, should return Size.Empty. * Remove constructors with frame parameters from Toplevel class. * Remove constructors with frame parameters from Window class. * Fix merge errors. * Revert "Fixes #3182. OnResizeNeeded returns int.MaxValue and int.MaxValue when Application.Top is null, should return Size.Empty." This reverts commitcf9c24b846. * Revert unit test. * Fixes #2882. TabView: 'Frame.DrawFrame(Rect, bool)' is obsolete: 'This method is obsolete in v2. Use use LineCanvas or Frame (#2980) * Fixes #2882. TabView: 'Frame.DrawFrame(Rect, bool)' is obsolete: 'This method is obsolete in v2. Use use LineCanvas or Frame * Trying fix this unit test that sometimes fail. * Fixes #2983. View need a alternative DrawFrame for the v2. * Use new DrawFrame method. * Change _lines field to Lines property. * Add TabWindow unit test. * Add DrawIncompleteFrame method and unit tests. * Add more unit tests to LineCanvas. * Fix newline conflict errors. * Revert "Change _lines field to Lines property." This reverts commitab6c5f3094. * Add DrawIncompleteFrame method and unit tests. * Add more unit tests to LineCanvas. * Fix newline conflict errors. * Force render immediately instead of join. * I will never rely on zero-location-based unit test again. * Fix TestTreeViewColor unit test fail. * Using location of 3 to avoid be divisible by 2 and so avoiding bugs. * Revert "Using location of 3 to avoid be divisible by 2 and so avoiding bugs." This reverts commitdd3df135d8. * Revert "I will never rely on zero-location-based unit test again." This reverts commit62adf6f285. * Revert "Fix newline conflict errors." This reverts commit4acf72612d. * Revert "Add more unit tests to LineCanvas." This reverts commit66bc6f514e. * Revert "Add DrawIncompleteFrame method and unit tests." This reverts commit680ba264e1. * Resolving merge conflicts. * Revert "Use new DrawFrame method." This reverts commit69a7f17f19. * Revert "Fixes #2983. View need a alternative DrawFrame for the v2." This reverts commitdade9fd767. * Reverting this changes to start a new one. * Add horizontal and vertical support for combining glyphs. * Fix text and auto size behavior. * Add TabWidth property. * Add unit test for WordWrap. * Fixes #3017. View TextDirection returns incorrect size on a vertical direction instance with AutoSize as false. * Using Frame to force read from the get method. * Fix some issues with AutoSize and ForceValidatePosDim. * Fixing broken unit tests. * Restoring code I've broken. * Removing forgotten code. * Only LayoutStyle.Computed can change the Frame. * DateField and TimeField depends on LayoutStyle.Computed. * Fix unit tests related with LayoutStyle. * Implements tabs, left and right arrows as View. * Draws a minimum full border. * Adds missing XML parameter. * Adds assert tests for Frame. * Removes duplicates InlineData. * Adds more unit tests for minimum full border without Left and Right thickness. * Trying to fix the TestTreeViewColor unit test fail. * Prevents a user to set TextDirection to -1. * Prevents any invalid TextDirection value. * Removes (TextDirection)(-1). * Removes unnecessary TextDirection initialization. * Removes LayoutStyle. * Fixing unit tests with border. * Trying to fix TestTreeViewColor again. * Revert "Trying to fix TestTreeViewColor again." This reverts commitc2efa8e42e. * Trying to fix TestTreeViewColor again. * Fix merge errors. * Fix merge errors. * Restoring unit test. * Restores the right XML comment. * Fix Disposing unit tests that sometimes throws because some instances aren't cleared on others unit tests classes. * Fix Disposing unit tests that sometimes throws because some instances aren't cleared on others unit tests classes. * Only call OnResizeNeeded if it's LayoutStyle.Computed. * Fix merge errors. * Fix merge errors. * Fix unit tests fail. * Reformat. * Again. * Rename to OnDrawAdornments. * Fix failing unit tests. * Reduces indentation and cleanup code. * Cleanup code. * Fix bug done when cleanup. * Replace FrameHandledMouseEvent to AdornmentHandledMouseEvent. * Removes Tab constructor parameters. --------- Co-authored-by: Tig <tig@users.noreply.github.com> * Fix merge errors. * Remove constructors with parameters from Button. * Remove parenthesis on objects initializers from Button. * Remove constructors with parameters from CheckBox. * Remove parenthesis on objects initializers from CheckBox. * Remove constructors with parameters from ComboBox. * Remove constructors with parameters from FrameView. * Remove parenthesis on objects initializers from FrameView. * Initial commit * Renamed Direction enum for clarity in refactoring unit tests * Moved nav tests to NavigationTests * Moved view tests around * Cleaning up TextFormatter and View.AutoSize code * Fixed latent TextFormatter bug with \n * removed Application dependency on some autosize unit tests * Fixed Label tests to deal with auotsize overriding height/width * Fixed more label tests. WIP * Fixed all places where AutoSize = happend after setting Dims * Started adding new primitive View.Text tests * Code comments * WIP: Enforce that it makes no sense to set Width/Height if AutoSize = true. Update Unit tests to match. * WIP: Enforce that it makes no sense to set Width/Height if AutoSize = true. Update Unit tests to match. * Remove frame set from the View constructor and prevent SetRelativeLayout running if not yet initialized. * Changes needed for unit tests pass on remove parameters constructors from the Label class. * Remove constructors with parameters from Label. * Remove parenthesis on objects initializers from Label. * Prefix private fields with underscore. * Renamed to MaxLength. * Remove constructors with parameters from ListView. * MakeWrapper not needed anymore. * Remove parenthesis on objects initializers from ListView. * WIP: Enforce that it makes no sense to set Width/Height if AutoSize = true. Update Unit tests to match. * Massive code cleanup - use parameterless constructors and ensure AutoSize is set properly. Code reformat. * Massive code cleanup - use parameterless constructors and ensure AutoSize is set properly. Code reformat. * Fixed messagebox * Remove constructors with parameters from ScrollBarView and ScrollView. * Remove parenthesis on objects initializers from ScrollBarView and ScrollView. * Cleanup code. * Fix merge errors. * Add empty dotsettings for solution and projects. * Set ReSharper language analysis level for projects to C#12 * Make ReSharper consider itself the boss for style * Add rule to enforce property backing fields above the property * Disable auto-detection of naming rules so ReSharper doesn't change them by itself * Don't let someone's VS settings override the indent settings * Explicitly set tab width to 4 spaces and force spaces. * Rules to keep various multi-line constructs aligned within themselves * Curly brace rules (Using K&R style, per current project spec) * Blank line rules Mostly to add breaks in various situations, and also to enforce max of 1 blank line. * Increase auto-wrap to 160 from default of 120 * Line break at end of all files, to make Unixy systems happy * Keep attributes on their own lines except for methods and records that are themselves single-line * Increase attribute auto-wrap to 60 from default of 38 * Wrap/chop rules for long method signatures and record declarations Chop if either already multi-line or if over 8 parameters. Chop AFTER the left paren and BEFORE the first parameter. * Chop rules for generics For generics with multi-line type parameters or multiple type parameter constraints, chop in a way that has consistent alignment. * Always enforce enum members on their own lines * One-line functions completely on one line They're usually expression-bodied anyway, here, so this is almost irrelevant * Keep control flow statements on their own lines * Follow same chop rules for method invocation as method declaration * Chop long or multi-line method chains or patterns * Wrap rules for binary operators Operator at beginning of new lines Auto-chop if long or already multi-line * Spaces between keywords and their opening parentheses * Add file layout rules for organization of reorderable items like fields, properties, etc. Ugly XML, so load it up in the UI to look at it It's MOSTLY the ReSharper defaults, but with more aggressive sorting, generally by access modifier and name, within each grouping. * Deconstructors use per-member types * Use keywords for built-in types and increase severity of inspection for violations Also apply to IntPtr and similar, which should now be nint and similar * Apply syntax style on completion. * Use var when evident for built-in and simple types, but not elsewhere * Increase severity for some minor redundancy and clarity inspections * Enforce braces always required for blocks, and treat as error * Warn if a local function is not statement-bodied * Increase various inspection severities IF Condition => Severity: Attributes not wrapped property => Suggestion Constructors expression-bodied => Error default doesn't have type when it isn't clear => suggestion Namespaces not file-scoped => error Methods not statement-bodied => hint Null check pattern not the object property pattern => Error * Adjust preference order of null check patterns to make object pattern highest * XmlDoc rules to keep tags and contents aligned and wrapped * Add a few custom profiles for code cleanup and make the full profile default * Remove parts for languages not used in this solution * copied in v2_develop changes * Merged v2_develop * Added Begin/Init unit tests. Removed Application dependencey from AutoSizeFalse tests * TextFormatter.Lines -> GetLines () * Let ReSharper know we intend to localize things * TextFormatter code cleanup * copied in v2_develop changes * Merged v2_develop * Spaces aren't wanted here either. * Fix merge errors. * Fixes ContentBottomRightCorner related with https://github.com/gui-cs/Terminal.Gui/issues/3211#issue-2098878820 * Remove constructors with parameters from ContextMenu. * Remove commented code. * Remove constructors with parameters from OpenDialog. * Remove constructors with parameters from SaveDialog. * Remove constructors with parameters from TextField. * Remove constructors with parameters from TimeField. * Fix unit test. * Remove unnecessary SetInitialProperties method. * Remove unnecessary SetInitialProperties method. * Remove parenthesis on objects initializers from Toplevel and Window. * Remove constructors with parameters from RadioGroup. * Remove constructors with parameters from TextView. * Remove constructors with parameters from MenuBar. * TEMPORARY: Turn everything that was set to error down to warning or lower * Fixes #3219. MenuBar is opened by call OpenMenu even it's disabled. * Remove constructors with parameters from Menu. * Remove constructors with parameters from View. * Change constructor to internal because is mainly useful for testing. * ReSharper Cleanup Code. * Added format only r# config * Fixes #3224. TextFormatter.Lines should return a single string.Empty list even with Width or Height equal to zero. * Remove constructors with parameters from Dialog. * Remove constructors with parameters from TextValidateField. * Fixes https://github.com/gui-cs/Terminal.Gui/issues/3224#issuecomment-1924096038 * Fixes #3225. Press CursorDown on TabView doesn't move to the next view. * Fixes #3229. TextFormatter should have a FillRemaining property. * Testing formatting merge in bdisp * Testing formatting merge * Testing formatting merge bdisp * Testing formatting merge 2 * xmldoc format * R# Full Code Cleanup * R# Full Code Cleanup2 * R# Full Code Cleanup2 * Merged! But broke tests * Refixing... * Refixed DrawTests * Refixed ViewTests * Refixed Text Tests * Refixed more unit tests * Refixed scenarios * Refixed rest of scenarios * Refixed ViewsTests * Refixed rest of tests. All unit tests pass again! * Fixed warnings * Updated R# version. Added new code cleanup settings * Applied latest code cleanup to solution * Another code cleanup pass * Tweaked r# settings. .editorconfig now matches. * r# else on separate line * r# - update * r# - full solution * test commit * test commit * test commit * Removed extra profiles * Full cleanup following cleaning up profiles * Null checking pattern rules/inspections * Tabs and extra whitespace are evil * Attributes on their own lines * Code layout rules to put fields first and to put backing fields with their properties * Merged v2_develop * Full cleanup following dodexahedron's PR --------- Co-authored-by: BDisp <bd.bdisp@gmail.com> Co-authored-by: Brandon Thetford <github@snapsinazfs.com>
940 lines
28 KiB
C#
940 lines
28 KiB
C#
using System.Diagnostics;
|
|
|
|
// Alias Console to MockConsole so we don't accidentally use Console
|
|
|
|
namespace Terminal.Gui.ApplicationTests;
|
|
|
|
/// <summary>Tests MainLoop using the FakeMainLoop.</summary>
|
|
public class MainLoopTests
|
|
{
|
|
private static readonly ManualResetEventSlim _wakeUp = new (false);
|
|
private static Button btn;
|
|
private static string cancel;
|
|
private static string clickMe;
|
|
private static int four;
|
|
private static int one;
|
|
private static string pewPew;
|
|
private static bool taskCompleted;
|
|
|
|
// TODO: EventsPending tests
|
|
// - wait = true
|
|
// - wait = false
|
|
|
|
// TODO: Add IMainLoop tests
|
|
private static volatile int tbCounter;
|
|
private static int three;
|
|
private static int total;
|
|
private static int two;
|
|
private static int zero;
|
|
|
|
public static IEnumerable<object []> TestAddIdle
|
|
{
|
|
get
|
|
{
|
|
// Goes fine
|
|
Action a1 = StartWindow;
|
|
|
|
yield return new object [] { a1, "Click Me", "Cancel", "Pew Pew", 0, 1, 2, 3, 4 };
|
|
|
|
// Also goes fine
|
|
Action a2 = () => Application.Invoke (StartWindow);
|
|
|
|
yield return new object [] { a2, "Click Me", "Cancel", "Pew Pew", 0, 1, 2, 3, 4 };
|
|
}
|
|
}
|
|
|
|
// See Also ConsoleDRivers/MainLoopDriverTests.cs for tests of the MainLoopDriver
|
|
|
|
// Idle Handler tests
|
|
[Fact]
|
|
public void AddIdle_Adds_And_Removes ()
|
|
{
|
|
var ml = new MainLoop (new FakeMainLoop ());
|
|
|
|
Func<bool> fnTrue = () => true;
|
|
Func<bool> fnFalse = () => false;
|
|
|
|
ml.AddIdle (fnTrue);
|
|
ml.AddIdle (fnFalse);
|
|
|
|
Assert.Equal (2, ml.IdleHandlers.Count);
|
|
Assert.Equal (fnTrue, ml.IdleHandlers [0]);
|
|
Assert.NotEqual (fnFalse, ml.IdleHandlers [0]);
|
|
|
|
Assert.True (ml.RemoveIdle (fnTrue));
|
|
Assert.Single (ml.IdleHandlers);
|
|
|
|
// BUGBUG: This doesn't throw or indicate an error. Ideally RemoveIdle would either
|
|
// throw an exception in this case, or return an error.
|
|
// No. Only need to return a boolean.
|
|
Assert.False (ml.RemoveIdle (fnTrue));
|
|
|
|
Assert.True (ml.RemoveIdle (fnFalse));
|
|
|
|
// BUGBUG: This doesn't throw an exception or indicate an error. Ideally RemoveIdle would either
|
|
// throw an exception in this case, or return an error.
|
|
// No. Only need to return a boolean.
|
|
Assert.False (ml.RemoveIdle (fnFalse));
|
|
|
|
// Add again, but with dupe
|
|
ml.AddIdle (fnTrue);
|
|
ml.AddIdle (fnTrue);
|
|
|
|
Assert.Equal (2, ml.IdleHandlers.Count);
|
|
Assert.Equal (fnTrue, ml.IdleHandlers [0]);
|
|
Assert.True (ml.IdleHandlers [0] ());
|
|
Assert.Equal (fnTrue, ml.IdleHandlers [1]);
|
|
Assert.True (ml.IdleHandlers [1] ());
|
|
|
|
Assert.True (ml.RemoveIdle (fnTrue));
|
|
Assert.Single (ml.IdleHandlers);
|
|
Assert.Equal (fnTrue, ml.IdleHandlers [0]);
|
|
Assert.NotEqual (fnFalse, ml.IdleHandlers [0]);
|
|
|
|
Assert.True (ml.RemoveIdle (fnTrue));
|
|
Assert.Empty (ml.IdleHandlers);
|
|
|
|
// BUGBUG: This doesn't throw an exception or indicate an error. Ideally RemoveIdle would either
|
|
// throw an exception in this case, or return an error.
|
|
// No. Only need to return a boolean.
|
|
Assert.False (ml.RemoveIdle (fnTrue));
|
|
}
|
|
|
|
[Fact]
|
|
public void AddIdle_Function_GetsCalled_OnIteration ()
|
|
{
|
|
var ml = new MainLoop (new FakeMainLoop ());
|
|
|
|
var functionCalled = 0;
|
|
|
|
Func<bool> fn = () =>
|
|
{
|
|
functionCalled++;
|
|
|
|
return true;
|
|
};
|
|
|
|
ml.AddIdle (fn);
|
|
ml.RunIteration ();
|
|
Assert.Equal (1, functionCalled);
|
|
}
|
|
|
|
[Fact]
|
|
public void AddIdle_Twice_Returns_False_Called_Twice ()
|
|
{
|
|
var ml = new MainLoop (new FakeMainLoop ());
|
|
|
|
var functionCalled = 0;
|
|
|
|
Func<bool> fn1 = () =>
|
|
{
|
|
functionCalled++;
|
|
|
|
return false;
|
|
};
|
|
|
|
// Force stop if 10 iterations
|
|
var stopCount = 0;
|
|
|
|
Func<bool> fnStop = () =>
|
|
{
|
|
stopCount++;
|
|
|
|
if (stopCount == 10)
|
|
{
|
|
ml.Stop ();
|
|
}
|
|
|
|
return true;
|
|
};
|
|
|
|
ml.AddIdle (fnStop);
|
|
ml.AddIdle (fn1);
|
|
ml.AddIdle (fn1);
|
|
ml.Run ();
|
|
Assert.True (ml.RemoveIdle (fnStop));
|
|
Assert.False (ml.RemoveIdle (fn1));
|
|
Assert.False (ml.RemoveIdle (fn1));
|
|
|
|
Assert.Equal (2, functionCalled);
|
|
}
|
|
|
|
[Fact]
|
|
public void AddIdleTwice_Function_CalledTwice ()
|
|
{
|
|
var ml = new MainLoop (new FakeMainLoop ());
|
|
|
|
var functionCalled = 0;
|
|
|
|
Func<bool> fn = () =>
|
|
{
|
|
functionCalled++;
|
|
|
|
return true;
|
|
};
|
|
|
|
ml.AddIdle (fn);
|
|
ml.AddIdle (fn);
|
|
ml.RunIteration ();
|
|
Assert.Equal (2, functionCalled);
|
|
Assert.Equal (2, ml.IdleHandlers.Count);
|
|
|
|
functionCalled = 0;
|
|
Assert.True (ml.RemoveIdle (fn));
|
|
Assert.Single (ml.IdleHandlers);
|
|
ml.RunIteration ();
|
|
Assert.Equal (1, functionCalled);
|
|
|
|
functionCalled = 0;
|
|
Assert.True (ml.RemoveIdle (fn));
|
|
Assert.Empty (ml.IdleHandlers);
|
|
ml.RunIteration ();
|
|
Assert.Equal (0, functionCalled);
|
|
Assert.False (ml.RemoveIdle (fn));
|
|
}
|
|
|
|
[Fact]
|
|
public void AddThenRemoveIdle_Function_NotCalled ()
|
|
{
|
|
var ml = new MainLoop (new FakeMainLoop ());
|
|
|
|
var functionCalled = 0;
|
|
|
|
Func<bool> fn = () =>
|
|
{
|
|
functionCalled++;
|
|
|
|
return true;
|
|
};
|
|
|
|
ml.AddIdle (fn);
|
|
Assert.True (ml.RemoveIdle (fn));
|
|
ml.RunIteration ();
|
|
Assert.Equal (0, functionCalled);
|
|
}
|
|
|
|
// Timeout Handler Tests
|
|
[Fact]
|
|
public void AddTimer_Adds_Removes_NoFaults ()
|
|
{
|
|
var ml = new MainLoop (new FakeMainLoop ());
|
|
var ms = 100;
|
|
|
|
var callbackCount = 0;
|
|
|
|
Func<bool> callback = () =>
|
|
{
|
|
callbackCount++;
|
|
|
|
return true;
|
|
};
|
|
|
|
object token = ml.AddTimeout (TimeSpan.FromMilliseconds (ms), callback);
|
|
|
|
Assert.True (ml.RemoveTimeout (token));
|
|
|
|
// BUGBUG: This should probably fault?
|
|
// Must return a boolean.
|
|
Assert.False (ml.RemoveTimeout (token));
|
|
}
|
|
|
|
[Fact]
|
|
public async Task AddTimer_Duplicate_Keys_Not_Allowed ()
|
|
{
|
|
var ml = new MainLoop (new FakeMainLoop ());
|
|
const int ms = 100;
|
|
object token1 = null, token2 = null;
|
|
|
|
var callbackCount = 0;
|
|
|
|
Func<bool> callback = () =>
|
|
{
|
|
callbackCount++;
|
|
|
|
if (callbackCount == 2)
|
|
{
|
|
ml.Stop ();
|
|
}
|
|
|
|
return true;
|
|
};
|
|
|
|
var task1 = new Task (() => token1 = ml.AddTimeout (TimeSpan.FromMilliseconds (ms), callback));
|
|
var task2 = new Task (() => token2 = ml.AddTimeout (TimeSpan.FromMilliseconds (ms), callback));
|
|
Assert.Null (token1);
|
|
Assert.Null (token2);
|
|
task1.Start ();
|
|
task2.Start ();
|
|
ml.Run ();
|
|
Assert.NotNull (token1);
|
|
Assert.NotNull (token2);
|
|
await Task.WhenAll (task1, task2);
|
|
Assert.True (ml.RemoveTimeout (token1));
|
|
Assert.True (ml.RemoveTimeout (token2));
|
|
|
|
Assert.Equal (2, callbackCount);
|
|
}
|
|
|
|
// Timeout Handler Tests
|
|
[Fact]
|
|
public void AddTimer_EventFired ()
|
|
{
|
|
var ml = new MainLoop (new FakeMainLoop ());
|
|
var ms = 100;
|
|
|
|
long originTicks = DateTime.UtcNow.Ticks;
|
|
|
|
var callbackCount = 0;
|
|
|
|
Func<bool> callback = () =>
|
|
{
|
|
callbackCount++;
|
|
|
|
return true;
|
|
};
|
|
|
|
object sender = null;
|
|
TimeoutEventArgs args = null;
|
|
|
|
ml.TimeoutAdded += (s, e) =>
|
|
{
|
|
sender = s;
|
|
args = e;
|
|
};
|
|
|
|
object token = ml.AddTimeout (TimeSpan.FromMilliseconds (ms), callback);
|
|
|
|
Assert.Same (ml, sender);
|
|
Assert.NotNull (args.Timeout);
|
|
Assert.True (args.Ticks - originTicks >= 100 * TimeSpan.TicksPerMillisecond);
|
|
}
|
|
|
|
[Fact]
|
|
public void AddTimer_In_Parallel_Wont_Throw ()
|
|
{
|
|
var ml = new MainLoop (new FakeMainLoop ());
|
|
const int ms = 100;
|
|
object token1 = null, token2 = null;
|
|
|
|
var callbackCount = 0;
|
|
|
|
Func<bool> callback = () =>
|
|
{
|
|
callbackCount++;
|
|
|
|
if (callbackCount == 2)
|
|
{
|
|
ml.Stop ();
|
|
}
|
|
|
|
return true;
|
|
};
|
|
|
|
Parallel.Invoke (
|
|
() => token1 = ml.AddTimeout (TimeSpan.FromMilliseconds (ms), callback),
|
|
() => token2 = ml.AddTimeout (TimeSpan.FromMilliseconds (ms), callback)
|
|
);
|
|
ml.Run ();
|
|
Assert.NotNull (token1);
|
|
Assert.NotNull (token2);
|
|
Assert.True (ml.RemoveTimeout (token1));
|
|
Assert.True (ml.RemoveTimeout (token2));
|
|
|
|
Assert.Equal (2, callbackCount);
|
|
}
|
|
|
|
[Fact]
|
|
public void AddTimer_Remove_NotCalled ()
|
|
{
|
|
var ml = new MainLoop (new FakeMainLoop ());
|
|
TimeSpan ms = TimeSpan.FromMilliseconds (50);
|
|
|
|
// Force stop if 10 iterations
|
|
var stopCount = 0;
|
|
|
|
Func<bool> fnStop = () =>
|
|
{
|
|
stopCount++;
|
|
|
|
if (stopCount == 10)
|
|
{
|
|
ml.Stop ();
|
|
}
|
|
|
|
return true;
|
|
};
|
|
ml.AddIdle (fnStop);
|
|
|
|
var callbackCount = 0;
|
|
|
|
Func<bool> callback = () =>
|
|
{
|
|
callbackCount++;
|
|
|
|
return true;
|
|
};
|
|
|
|
object token = ml.AddTimeout (ms, callback);
|
|
Assert.True (ml.RemoveTimeout (token));
|
|
ml.Run ();
|
|
Assert.Equal (0, callbackCount);
|
|
}
|
|
|
|
[Fact]
|
|
public void AddTimer_ReturnFalse_StopsBeingCalled ()
|
|
{
|
|
var ml = new MainLoop (new FakeMainLoop ());
|
|
TimeSpan ms = TimeSpan.FromMilliseconds (50);
|
|
|
|
// Force stop if 10 iterations
|
|
var stopCount = 0;
|
|
|
|
Func<bool> fnStop = () =>
|
|
{
|
|
Thread.Sleep (10); // Sleep to enable timer to fire
|
|
stopCount++;
|
|
|
|
if (stopCount == 10)
|
|
{
|
|
ml.Stop ();
|
|
}
|
|
|
|
return true;
|
|
};
|
|
ml.AddIdle (fnStop);
|
|
|
|
var callbackCount = 0;
|
|
|
|
Func<bool> callback = () =>
|
|
{
|
|
callbackCount++;
|
|
|
|
return false;
|
|
};
|
|
|
|
object token = ml.AddTimeout (ms, callback);
|
|
ml.Run ();
|
|
Assert.Equal (1, callbackCount);
|
|
Assert.Equal (10, stopCount);
|
|
Assert.False (ml.RemoveTimeout (token));
|
|
}
|
|
|
|
[Fact]
|
|
public void AddTimer_Run_Called ()
|
|
{
|
|
var ml = new MainLoop (new FakeMainLoop ());
|
|
var ms = 100;
|
|
|
|
var callbackCount = 0;
|
|
|
|
Func<bool> callback = () =>
|
|
{
|
|
callbackCount++;
|
|
ml.Stop ();
|
|
|
|
return true;
|
|
};
|
|
|
|
object token = ml.AddTimeout (TimeSpan.FromMilliseconds (ms), callback);
|
|
ml.Run ();
|
|
Assert.True (ml.RemoveTimeout (token));
|
|
|
|
Assert.Equal (1, callbackCount);
|
|
}
|
|
|
|
[Fact]
|
|
public void AddTimer_Run_CalledAtApproximatelyRightTime ()
|
|
{
|
|
var ml = new MainLoop (new FakeMainLoop ());
|
|
TimeSpan ms = TimeSpan.FromMilliseconds (50);
|
|
var watch = new Stopwatch ();
|
|
|
|
var callbackCount = 0;
|
|
|
|
Func<bool> callback = () =>
|
|
{
|
|
watch.Stop ();
|
|
callbackCount++;
|
|
ml.Stop ();
|
|
|
|
return true;
|
|
};
|
|
|
|
object token = ml.AddTimeout (ms, callback);
|
|
watch.Start ();
|
|
ml.Run ();
|
|
|
|
// +/- 100ms should be good enuf
|
|
// https://github.com/xunit/assert.xunit/pull/25
|
|
Assert.Equal (ms * callbackCount, watch.Elapsed, new MillisecondTolerance (100));
|
|
|
|
Assert.True (ml.RemoveTimeout (token));
|
|
Assert.Equal (1, callbackCount);
|
|
}
|
|
|
|
[Fact]
|
|
public void AddTimer_Run_CalledTwiceApproximatelyRightTime ()
|
|
{
|
|
var ml = new MainLoop (new FakeMainLoop ());
|
|
TimeSpan ms = TimeSpan.FromMilliseconds (50);
|
|
var watch = new Stopwatch ();
|
|
|
|
var callbackCount = 0;
|
|
|
|
Func<bool> callback = () =>
|
|
{
|
|
callbackCount++;
|
|
|
|
if (callbackCount == 2)
|
|
{
|
|
watch.Stop ();
|
|
ml.Stop ();
|
|
}
|
|
|
|
return true;
|
|
};
|
|
|
|
object token = ml.AddTimeout (ms, callback);
|
|
watch.Start ();
|
|
ml.Run ();
|
|
|
|
// +/- 100ms should be good enuf
|
|
// https://github.com/xunit/assert.xunit/pull/25
|
|
Assert.Equal (ms * callbackCount, watch.Elapsed, new MillisecondTolerance (100));
|
|
|
|
Assert.True (ml.RemoveTimeout (token));
|
|
Assert.Equal (2, callbackCount);
|
|
}
|
|
|
|
[Fact]
|
|
public void CheckTimersAndIdleHandlers_NoTimers_Returns_False ()
|
|
{
|
|
var ml = new MainLoop (new FakeMainLoop ());
|
|
bool retVal = ml.CheckTimersAndIdleHandlers (out int waitTimeOut);
|
|
Assert.False (retVal);
|
|
Assert.Equal (-1, waitTimeOut);
|
|
}
|
|
|
|
[Fact]
|
|
public void CheckTimersAndIdleHandlers_NoTimers_WithIdle_Returns_True ()
|
|
{
|
|
var ml = new MainLoop (new FakeMainLoop ());
|
|
Func<bool> fnTrue = () => true;
|
|
|
|
ml.AddIdle (fnTrue);
|
|
bool retVal = ml.CheckTimersAndIdleHandlers (out int waitTimeOut);
|
|
Assert.True (retVal);
|
|
Assert.Equal (-1, waitTimeOut);
|
|
}
|
|
|
|
[Fact]
|
|
public void CheckTimersAndIdleHandlers_With1Timer_Returns_Timer ()
|
|
{
|
|
var ml = new MainLoop (new FakeMainLoop ());
|
|
TimeSpan ms = TimeSpan.FromMilliseconds (50);
|
|
|
|
static bool Callback () { return false; }
|
|
|
|
_ = ml.AddTimeout (ms, Callback);
|
|
bool retVal = ml.CheckTimersAndIdleHandlers (out int waitTimeOut);
|
|
|
|
Assert.True (retVal);
|
|
|
|
// It should take < 10ms to execute to here
|
|
Assert.True (ms.TotalMilliseconds <= waitTimeOut + 10);
|
|
}
|
|
|
|
[Fact]
|
|
public void CheckTimersAndIdleHandlers_With2Timers_Returns_Timer ()
|
|
{
|
|
var ml = new MainLoop (new FakeMainLoop ());
|
|
TimeSpan ms = TimeSpan.FromMilliseconds (50);
|
|
|
|
static bool Callback () { return false; }
|
|
|
|
_ = ml.AddTimeout (ms, Callback);
|
|
_ = ml.AddTimeout (ms, Callback);
|
|
bool retVal = ml.CheckTimersAndIdleHandlers (out int waitTimeOut);
|
|
|
|
Assert.True (retVal);
|
|
|
|
// It should take < 10ms to execute to here
|
|
Assert.True (ms.TotalMilliseconds <= waitTimeOut + 10);
|
|
}
|
|
|
|
[Fact]
|
|
public void False_Idle_Stops_It_Being_Called_Again ()
|
|
{
|
|
var ml = new MainLoop (new FakeMainLoop ());
|
|
|
|
var functionCalled = 0;
|
|
|
|
Func<bool> fn1 = () =>
|
|
{
|
|
functionCalled++;
|
|
|
|
if (functionCalled == 10)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
return true;
|
|
};
|
|
|
|
// Force stop if 20 iterations
|
|
var stopCount = 0;
|
|
|
|
Func<bool> fnStop = () =>
|
|
{
|
|
stopCount++;
|
|
|
|
if (stopCount == 20)
|
|
{
|
|
ml.Stop ();
|
|
}
|
|
|
|
return true;
|
|
};
|
|
|
|
ml.AddIdle (fnStop);
|
|
ml.AddIdle (fn1);
|
|
ml.Run ();
|
|
Assert.True (ml.RemoveIdle (fnStop));
|
|
Assert.False (ml.RemoveIdle (fn1));
|
|
|
|
Assert.Equal (10, functionCalled);
|
|
Assert.Equal (20, stopCount);
|
|
}
|
|
|
|
[Fact]
|
|
public void Internal_Tests ()
|
|
{
|
|
var testMainloop = new TestMainloop ();
|
|
var mainloop = new MainLoop (testMainloop);
|
|
Assert.Empty (mainloop._timeouts);
|
|
Assert.Empty (mainloop._idleHandlers);
|
|
|
|
Assert.NotNull (
|
|
new Timeout { Span = new TimeSpan (), Callback = () => true }
|
|
);
|
|
}
|
|
|
|
[Fact]
|
|
[AutoInitShutdown]
|
|
public async Task InvokeLeakTest ()
|
|
{
|
|
Random r = new ();
|
|
TextField tf = new ();
|
|
Application.Top.Add (tf);
|
|
|
|
const int numPasses = 5;
|
|
const int numIncrements = 500;
|
|
const int pollMs = 2500;
|
|
|
|
Task task = Task.Run (() => RunTest (r, tf, numPasses, numIncrements, pollMs));
|
|
|
|
// blocks here until the RequestStop is processed at the end of the test
|
|
Application.Run ();
|
|
|
|
await task; // Propagate exception if any occurred
|
|
|
|
Assert.Equal (numIncrements * numPasses, tbCounter);
|
|
}
|
|
|
|
[Theory]
|
|
[AutoInitShutdown]
|
|
[MemberData (nameof (TestAddIdle))]
|
|
public void Mainloop_Invoke_Or_AddIdle_Can_Be_Used_For_Events_Or_Actions (
|
|
Action action,
|
|
string pclickMe,
|
|
string pcancel,
|
|
string ppewPew,
|
|
int pzero,
|
|
int pone,
|
|
int ptwo,
|
|
int pthree,
|
|
int pfour
|
|
)
|
|
{
|
|
total = 0;
|
|
btn = null;
|
|
clickMe = pclickMe;
|
|
cancel = pcancel;
|
|
pewPew = ppewPew;
|
|
zero = pzero;
|
|
one = pone;
|
|
two = ptwo;
|
|
three = pthree;
|
|
four = pfour;
|
|
taskCompleted = false;
|
|
|
|
var btnLaunch = new Button { Text = "Open Window" };
|
|
|
|
btnLaunch.Clicked += (s, e) => action ();
|
|
|
|
Application.Top.Add (btnLaunch);
|
|
|
|
int iterations = -1;
|
|
|
|
Application.Iteration += (s, a) =>
|
|
{
|
|
iterations++;
|
|
|
|
if (iterations == 0)
|
|
{
|
|
Assert.Null (btn);
|
|
Assert.Equal (zero, total);
|
|
Assert.True (btnLaunch.NewKeyDownEvent (new Key (KeyCode.Space)));
|
|
|
|
if (btn == null)
|
|
{
|
|
Assert.Null (btn);
|
|
Assert.Equal (zero, total);
|
|
}
|
|
else
|
|
{
|
|
Assert.Equal (clickMe, btn.Text);
|
|
Assert.Equal (four, total);
|
|
}
|
|
}
|
|
else if (iterations == 1)
|
|
{
|
|
Assert.Equal (clickMe, btn.Text);
|
|
Assert.Equal (zero, total);
|
|
Assert.True (btn.NewKeyDownEvent (new Key (KeyCode.Space)));
|
|
Assert.Equal (cancel, btn.Text);
|
|
Assert.Equal (one, total);
|
|
}
|
|
else if (taskCompleted)
|
|
{
|
|
Application.RequestStop ();
|
|
}
|
|
};
|
|
|
|
Application.Run ();
|
|
|
|
Assert.True (taskCompleted);
|
|
Assert.Equal (clickMe, btn.Text);
|
|
Assert.Equal (four, total);
|
|
}
|
|
|
|
[Fact]
|
|
public void RemoveIdle_Function_NotCalled ()
|
|
{
|
|
var ml = new MainLoop (new FakeMainLoop ());
|
|
|
|
var functionCalled = 0;
|
|
|
|
Func<bool> fn = () =>
|
|
{
|
|
functionCalled++;
|
|
|
|
return true;
|
|
};
|
|
|
|
Assert.False (ml.RemoveIdle (fn));
|
|
ml.RunIteration ();
|
|
Assert.Equal (0, functionCalled);
|
|
}
|
|
|
|
[Fact]
|
|
public void Run_Runs_Idle_Stop_Stops_Idle ()
|
|
{
|
|
var ml = new MainLoop (new FakeMainLoop ());
|
|
|
|
var functionCalled = 0;
|
|
|
|
Func<bool> fn = () =>
|
|
{
|
|
functionCalled++;
|
|
|
|
if (functionCalled == 10)
|
|
{
|
|
ml.Stop ();
|
|
}
|
|
|
|
return true;
|
|
};
|
|
|
|
ml.AddIdle (fn);
|
|
ml.Run ();
|
|
Assert.True (ml.RemoveIdle (fn));
|
|
|
|
Assert.Equal (10, functionCalled);
|
|
}
|
|
|
|
private static void Launch (Random r, TextField tf, int target)
|
|
{
|
|
Task.Run (
|
|
() =>
|
|
{
|
|
Thread.Sleep (r.Next (2, 4));
|
|
|
|
Application.Invoke (
|
|
() =>
|
|
{
|
|
tf.Text = $"index{r.Next ()}";
|
|
Interlocked.Increment (ref tbCounter);
|
|
|
|
if (target == tbCounter)
|
|
{
|
|
// On last increment wake up the check
|
|
_wakeUp.Set ();
|
|
}
|
|
}
|
|
);
|
|
}
|
|
);
|
|
}
|
|
|
|
private static async void RunAsyncTest (object sender, EventArgs e)
|
|
{
|
|
Assert.Equal (clickMe, btn.Text);
|
|
Assert.Equal (zero, total);
|
|
|
|
btn.Text = "Cancel";
|
|
Interlocked.Increment (ref total);
|
|
btn.SetNeedsDisplay ();
|
|
|
|
await Task.Run (
|
|
() =>
|
|
{
|
|
try
|
|
{
|
|
Assert.Equal (cancel, btn.Text);
|
|
Assert.Equal (one, total);
|
|
|
|
RunSql ();
|
|
}
|
|
finally
|
|
{
|
|
SetReadyToRun ();
|
|
}
|
|
}
|
|
)
|
|
.ContinueWith (
|
|
async (s, e) =>
|
|
{
|
|
await Task.Delay (1000);
|
|
Assert.Equal (clickMe, btn.Text);
|
|
Assert.Equal (three, total);
|
|
|
|
Interlocked.Increment (ref total);
|
|
|
|
Assert.Equal (clickMe, btn.Text);
|
|
Assert.Equal (four, total);
|
|
|
|
taskCompleted = true;
|
|
},
|
|
TaskScheduler.FromCurrentSynchronizationContext ()
|
|
);
|
|
}
|
|
|
|
private static void RunSql ()
|
|
{
|
|
Thread.Sleep (100);
|
|
Assert.Equal (cancel, btn.Text);
|
|
Assert.Equal (one, total);
|
|
|
|
Application.Invoke (
|
|
() =>
|
|
{
|
|
btn.Text = "Pew Pew";
|
|
Interlocked.Increment (ref total);
|
|
btn.SetNeedsDisplay ();
|
|
}
|
|
);
|
|
}
|
|
|
|
private static void RunTest (Random r, TextField tf, int numPasses, int numIncrements, int pollMs)
|
|
{
|
|
for (var j = 0; j < numPasses; j++)
|
|
{
|
|
_wakeUp.Reset ();
|
|
|
|
for (var i = 0; i < numIncrements; i++)
|
|
{
|
|
Launch (r, tf, (j + 1) * numIncrements);
|
|
}
|
|
|
|
while (tbCounter != (j + 1) * numIncrements) // Wait for tbCounter to reach expected value
|
|
{
|
|
int tbNow = tbCounter;
|
|
_wakeUp.Wait (pollMs);
|
|
|
|
if (tbCounter == tbNow)
|
|
{
|
|
// No change after wait: Idle handlers added via Application.Invoke have gone missing
|
|
Application.Invoke (() => Application.RequestStop ());
|
|
|
|
throw new TimeoutException (
|
|
$"Timeout: Increment lost. tbCounter ({tbCounter}) didn't "
|
|
+ $"change after waiting {pollMs} ms. Failed to reach {(j + 1) * numIncrements} on pass {j + 1}"
|
|
);
|
|
}
|
|
}
|
|
|
|
;
|
|
}
|
|
|
|
Application.Invoke (() => Application.RequestStop ());
|
|
}
|
|
|
|
private static void SetReadyToRun ()
|
|
{
|
|
Thread.Sleep (100);
|
|
Assert.Equal (pewPew, btn.Text);
|
|
Assert.Equal (two, total);
|
|
|
|
Application.Invoke (
|
|
() =>
|
|
{
|
|
btn.Text = "Click Me";
|
|
Interlocked.Increment (ref total);
|
|
btn.SetNeedsDisplay ();
|
|
}
|
|
);
|
|
}
|
|
|
|
private static void StartWindow ()
|
|
{
|
|
var startWindow = new Window { Modal = true };
|
|
|
|
btn = new Button { Text = "Click Me" };
|
|
|
|
btn.Clicked += RunAsyncTest;
|
|
|
|
var totalbtn = new Button { X = Pos.Right (btn), Text = "total" };
|
|
|
|
totalbtn.Clicked += (s, e) => { MessageBox.Query ("Count", $"Count is {total}", "Ok"); };
|
|
|
|
startWindow.Add (btn);
|
|
startWindow.Add (totalbtn);
|
|
|
|
Application.Run (startWindow);
|
|
|
|
Assert.Equal (clickMe, btn.Text);
|
|
Assert.Equal (four, total);
|
|
|
|
Application.RequestStop ();
|
|
}
|
|
|
|
private class MillisecondTolerance : IEqualityComparer<TimeSpan>
|
|
{
|
|
private readonly int _tolerance;
|
|
public MillisecondTolerance (int tolerance) { _tolerance = tolerance; }
|
|
public bool Equals (TimeSpan x, TimeSpan y) { return Math.Abs (x.Milliseconds - y.Milliseconds) <= _tolerance; }
|
|
public int GetHashCode (TimeSpan obj) { return obj.GetHashCode (); }
|
|
}
|
|
|
|
private class TestMainloop : IMainLoopDriver
|
|
{
|
|
private MainLoop mainLoop;
|
|
public bool EventsPending () { throw new NotImplementedException (); }
|
|
public void Iteration () { throw new NotImplementedException (); }
|
|
public void TearDown () { throw new NotImplementedException (); }
|
|
public void Setup (MainLoop mainLoop) { this.mainLoop = mainLoop; }
|
|
public void Wakeup () { throw new NotImplementedException (); }
|
|
}
|
|
}
|