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>
723 lines
25 KiB
C#
723 lines
25 KiB
C#
using System.Diagnostics;
|
|
using System.Globalization;
|
|
using System.Reflection;
|
|
using System.Text;
|
|
using System.Text.RegularExpressions;
|
|
using Xunit.Abstractions;
|
|
using Xunit.Sdk;
|
|
|
|
namespace Terminal.Gui;
|
|
|
|
// This class enables test functions annotated with the [AutoInitShutdown] attribute to
|
|
// automatically call Application.Init at start of the test and Application.Shutdown after the
|
|
// test exits.
|
|
//
|
|
// This is necessary because a) Application is a singleton and Init/Shutdown must be called
|
|
// as a pair, and b) all unit test functions should be atomic..
|
|
[AttributeUsage (AttributeTargets.Class | AttributeTargets.Method)]
|
|
public class AutoInitShutdownAttribute : BeforeAfterTestAttribute
|
|
{
|
|
private readonly Type _driverType;
|
|
|
|
/// <summary>
|
|
/// Initializes a [AutoInitShutdown] attribute, which determines if/how Application.Init and Application.Shutdown
|
|
/// are automatically called Before/After a test runs.
|
|
/// </summary>
|
|
/// <param name="autoInit">If true, Application.Init will be called Before the test runs.</param>
|
|
/// <param name="autoShutdown">If true, Application.Shutdown will be called After the test runs.</param>
|
|
/// <param name="consoleDriverType">
|
|
/// Determines which ConsoleDriver (FakeDriver, WindowsDriver, CursesDriver, NetDriver)
|
|
/// will be used when Application.Init is called. If null FakeDriver will be used. Only valid if
|
|
/// <paramref name="autoInit"/> is true.
|
|
/// </param>
|
|
/// <param name="useFakeClipboard">
|
|
/// If true, will force the use of <see cref="FakeDriver.FakeClipboard"/>. Only valid if
|
|
/// <see cref="ConsoleDriver"/> == <see cref="FakeDriver"/> and <paramref name="autoInit"/> is true.
|
|
/// </param>
|
|
/// <param name="fakeClipboardAlwaysThrowsNotSupportedException">
|
|
/// Only valid if <paramref name="autoInit"/> is true. Only
|
|
/// valid if <see cref="ConsoleDriver"/> == <see cref="FakeDriver"/> and <paramref name="autoInit"/> is true.
|
|
/// </param>
|
|
/// <param name="fakeClipboardIsSupportedAlwaysTrue">
|
|
/// Only valid if <paramref name="autoInit"/> is true. Only valid if
|
|
/// <see cref="ConsoleDriver"/> == <see cref="FakeDriver"/> and <paramref name="autoInit"/> is true.
|
|
/// </param>
|
|
/// <param name="configLocation">Determines what config file locations <see cref="ConfigurationManager"/> will load from.</param>
|
|
public AutoInitShutdownAttribute (
|
|
bool autoInit = true,
|
|
Type consoleDriverType = null,
|
|
bool useFakeClipboard = true,
|
|
bool fakeClipboardAlwaysThrowsNotSupportedException = false,
|
|
bool fakeClipboardIsSupportedAlwaysTrue = false,
|
|
ConfigurationManager.ConfigLocations configLocation = ConfigurationManager.ConfigLocations.DefaultOnly
|
|
)
|
|
{
|
|
AutoInit = autoInit;
|
|
CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.GetCultureInfo ("en-US");
|
|
_driverType = consoleDriverType ?? typeof (FakeDriver);
|
|
FakeDriver.FakeBehaviors.UseFakeClipboard = useFakeClipboard;
|
|
|
|
FakeDriver.FakeBehaviors.FakeClipboardAlwaysThrowsNotSupportedException =
|
|
fakeClipboardAlwaysThrowsNotSupportedException;
|
|
FakeDriver.FakeBehaviors.FakeClipboardIsSupportedAlwaysFalse = fakeClipboardIsSupportedAlwaysTrue;
|
|
ConfigurationManager.Locations = configLocation;
|
|
}
|
|
|
|
private bool AutoInit { get; }
|
|
|
|
public override void After (MethodInfo methodUnderTest)
|
|
{
|
|
Debug.WriteLine ($"After: {methodUnderTest.Name}");
|
|
|
|
if (AutoInit)
|
|
{
|
|
Application.Shutdown ();
|
|
#if DEBUG_IDISPOSABLE
|
|
if (Responder.Instances.Count == 0)
|
|
{
|
|
Assert.Empty (Responder.Instances);
|
|
}
|
|
else
|
|
{
|
|
Responder.Instances.Clear ();
|
|
}
|
|
#endif
|
|
}
|
|
}
|
|
|
|
public override void Before (MethodInfo methodUnderTest)
|
|
{
|
|
Debug.WriteLine ($"Before: {methodUnderTest.Name}");
|
|
|
|
if (AutoInit)
|
|
{
|
|
#if DEBUG_IDISPOSABLE
|
|
|
|
// Clear out any lingering Responder instances from previous tests
|
|
if (Responder.Instances.Count == 0)
|
|
{
|
|
Assert.Empty (Responder.Instances);
|
|
}
|
|
else
|
|
{
|
|
Responder.Instances.Clear ();
|
|
}
|
|
#endif
|
|
Application.Init ((ConsoleDriver)Activator.CreateInstance (_driverType));
|
|
}
|
|
}
|
|
}
|
|
|
|
[AttributeUsage (AttributeTargets.Class | AttributeTargets.Method)]
|
|
public class TestRespondersDisposed : BeforeAfterTestAttribute
|
|
{
|
|
public TestRespondersDisposed () { CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.GetCultureInfo ("en-US"); }
|
|
|
|
public override void After (MethodInfo methodUnderTest)
|
|
{
|
|
Debug.WriteLine ($"After: {methodUnderTest.Name}");
|
|
#if DEBUG_IDISPOSABLE
|
|
Assert.Empty (Responder.Instances);
|
|
#endif
|
|
}
|
|
|
|
public override void Before (MethodInfo methodUnderTest)
|
|
{
|
|
Debug.WriteLine ($"Before: {methodUnderTest.Name}");
|
|
#if DEBUG_IDISPOSABLE
|
|
|
|
// Clear out any lingering Responder instances from previous tests
|
|
Responder.Instances.Clear ();
|
|
Assert.Empty (Responder.Instances);
|
|
#endif
|
|
}
|
|
}
|
|
|
|
[AttributeUsage (AttributeTargets.Class | AttributeTargets.Method)]
|
|
public class SetupFakeDriverAttribute : BeforeAfterTestAttribute
|
|
{
|
|
/// <summary>
|
|
/// Enables test functions annotated with the [SetupFakeDriver] attribute to set Application.Driver to new
|
|
/// FakeDriver(). The driver is setup with 25 rows and columns.
|
|
/// </summary>
|
|
public SetupFakeDriverAttribute () { }
|
|
|
|
public override void After (MethodInfo methodUnderTest)
|
|
{
|
|
Debug.WriteLine ($"After: {methodUnderTest.Name}");
|
|
Application.Driver = null;
|
|
}
|
|
|
|
public override void Before (MethodInfo methodUnderTest)
|
|
{
|
|
Debug.WriteLine ($"Before: {methodUnderTest.Name}");
|
|
Assert.Null (Application.Driver);
|
|
Application.Driver = new FakeDriver { Rows = 25, Cols = 25 };
|
|
}
|
|
}
|
|
|
|
[AttributeUsage (AttributeTargets.Class | AttributeTargets.Method)]
|
|
public class TestDateAttribute : BeforeAfterTestAttribute
|
|
{
|
|
private readonly CultureInfo _currentCulture = CultureInfo.CurrentCulture;
|
|
public TestDateAttribute () { CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; }
|
|
|
|
public override void After (MethodInfo methodUnderTest)
|
|
{
|
|
CultureInfo.CurrentCulture = _currentCulture;
|
|
Assert.Equal (CultureInfo.CurrentCulture, _currentCulture);
|
|
}
|
|
|
|
public override void Before (MethodInfo methodUnderTest) { Assert.Equal (CultureInfo.CurrentCulture, CultureInfo.InvariantCulture); }
|
|
}
|
|
|
|
internal partial class TestHelpers
|
|
{
|
|
#pragma warning disable xUnit1013 // Public method should be marked as test
|
|
/// <summary>
|
|
/// Verifies <paramref name="expectedAttributes"/> are found at the locations specified by
|
|
/// <paramref name="expectedLook"/>. <paramref name="expectedLook"/> is a bitmap of indexes into
|
|
/// <paramref name="expectedAttributes"/> (e.g. "00110" means the attribute at <c>expectedAttributes[1]</c> is expected
|
|
/// at the 3rd and 4th columns of the 1st row of driver.Contents).
|
|
/// </summary>
|
|
/// <param name="expectedLook">
|
|
/// Numbers between 0 and 9 for each row/col of the console. Must be valid indexes into
|
|
/// <paramref name="expectedAttributes"/>.
|
|
/// </param>
|
|
/// <param name="driver">The ConsoleDriver to use. If null <see cref="Application.Driver"/> will be used.</param>
|
|
/// <param name="expectedAttributes"></param>
|
|
public static void AssertDriverAttributesAre (
|
|
string expectedLook,
|
|
ConsoleDriver driver = null,
|
|
params Attribute [] expectedAttributes
|
|
)
|
|
{
|
|
#pragma warning restore xUnit1013 // Public method should be marked as test
|
|
|
|
if (expectedAttributes.Length > 10)
|
|
{
|
|
throw new ArgumentException ("This method only works for UIs that use at most 10 colors");
|
|
}
|
|
|
|
expectedLook = expectedLook.Trim ();
|
|
driver ??= Application.Driver;
|
|
|
|
Cell [,] contents = driver.Contents;
|
|
|
|
var line = 0;
|
|
|
|
foreach (string lineString in expectedLook.Split ('\n').Select (l => l.Trim ()))
|
|
{
|
|
for (var c = 0; c < lineString.Length; c++)
|
|
{
|
|
Attribute? val = contents [line, c].Attribute;
|
|
|
|
List<Attribute> match = expectedAttributes.Where (e => e == val).ToList ();
|
|
|
|
switch (match.Count)
|
|
{
|
|
case 0:
|
|
throw new Exception (
|
|
$"{DriverContentsToString (driver)}\n"
|
|
+ $"Expected Attribute {
|
|
val
|
|
} (PlatformColor = {
|
|
val.Value.PlatformColor
|
|
}) at Contents[{
|
|
line
|
|
},{
|
|
c
|
|
}] {
|
|
contents [line, c]
|
|
} ((PlatformColor = {
|
|
contents [line, c].Attribute.Value.PlatformColor
|
|
}) was not found.\n"
|
|
+ $" Expected: {string.Join (",", expectedAttributes.Select (c => c))}\n"
|
|
+ $" But Was: <not found>"
|
|
);
|
|
case > 1:
|
|
throw new ArgumentException (
|
|
$"Bad value for expectedColors, {match.Count} Attributes had the same Value"
|
|
);
|
|
}
|
|
|
|
char colorUsed = Array.IndexOf (expectedAttributes, match [0]).ToString () [0];
|
|
char userExpected = lineString [c];
|
|
|
|
if (colorUsed != userExpected)
|
|
{
|
|
throw new Exception (
|
|
$"{DriverContentsToString (driver)}\n"
|
|
+ $"Unexpected Attribute at Contents[{line},{c}] {contents [line, c]}.\n"
|
|
+ $" Expected: {userExpected} ({expectedAttributes [int.Parse (userExpected.ToString ())]})\n"
|
|
+ $" But Was: {colorUsed} ({val})\n"
|
|
);
|
|
}
|
|
}
|
|
|
|
line++;
|
|
}
|
|
}
|
|
|
|
#pragma warning disable xUnit1013 // Public method should be marked as test
|
|
/// <summary>Asserts that the driver contents match the expected contents, optionally ignoring any trailing whitespace.</summary>
|
|
/// <param name="expectedLook"></param>
|
|
/// <param name="output"></param>
|
|
/// <param name="driver">The ConsoleDriver to use. If null <see cref="Application.Driver"/> will be used.</param>
|
|
/// <param name="ignoreLeadingWhitespace"></param>
|
|
public static void AssertDriverContentsAre (
|
|
string expectedLook,
|
|
ITestOutputHelper output,
|
|
ConsoleDriver driver = null,
|
|
bool ignoreLeadingWhitespace = false
|
|
)
|
|
{
|
|
#pragma warning restore xUnit1013 // Public method should be marked as test
|
|
string actualLook = DriverContentsToString (driver);
|
|
|
|
if (string.Equals (expectedLook, actualLook))
|
|
{
|
|
return;
|
|
}
|
|
|
|
// get rid of trailing whitespace on each line (and leading/trailing whitespace of start/end of full string)
|
|
expectedLook = TrailingWhiteSpaceRegEx ().Replace (expectedLook, "").Trim ();
|
|
actualLook = TrailingWhiteSpaceRegEx ().Replace (actualLook, "").Trim ();
|
|
|
|
if (ignoreLeadingWhitespace)
|
|
{
|
|
expectedLook = LeadingWhitespaceRegEx ().Replace (expectedLook, "").Trim ();
|
|
actualLook = LeadingWhitespaceRegEx ().Replace (actualLook, "").Trim ();
|
|
}
|
|
|
|
// standardize line endings for the comparison
|
|
expectedLook = expectedLook.Replace ("\r\n", "\n");
|
|
actualLook = actualLook.Replace ("\r\n", "\n");
|
|
|
|
// If test is about to fail show user what things looked like
|
|
if (!string.Equals (expectedLook, actualLook))
|
|
{
|
|
output?.WriteLine ("Expected:" + Environment.NewLine + expectedLook);
|
|
output?.WriteLine (" But Was:" + Environment.NewLine + actualLook);
|
|
}
|
|
|
|
Assert.Equal (expectedLook, actualLook);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Asserts that the driver contents are equal to the expected look, and that the cursor is at the expected
|
|
/// position.
|
|
/// </summary>
|
|
/// <param name="expectedLook"></param>
|
|
/// <param name="output"></param>
|
|
/// <param name="driver">The ConsoleDriver to use. If null <see cref="Application.Driver"/> will be used.</param>
|
|
/// <returns></returns>
|
|
public static Rect AssertDriverContentsWithFrameAre (
|
|
string expectedLook,
|
|
ITestOutputHelper output,
|
|
ConsoleDriver driver = null
|
|
)
|
|
{
|
|
List<List<Rune>> lines = new ();
|
|
var sb = new StringBuilder ();
|
|
driver ??= Application.Driver;
|
|
int x = -1;
|
|
int y = -1;
|
|
int w = -1;
|
|
int h = -1;
|
|
|
|
Cell [,] contents = driver.Contents;
|
|
|
|
for (var r = 0; r < driver.Rows; r++)
|
|
{
|
|
List<Rune> runes = new ();
|
|
|
|
for (var c = 0; c < driver.Cols; c++)
|
|
{
|
|
Rune rune = contents [r, c].Rune;
|
|
|
|
if (rune != (Rune)' ')
|
|
{
|
|
if (x == -1)
|
|
{
|
|
x = c;
|
|
y = r;
|
|
|
|
for (var i = 0; i < c; i++)
|
|
{
|
|
runes.InsertRange (i, new List<Rune> { (Rune)' ' });
|
|
}
|
|
}
|
|
|
|
if (rune.GetColumns () > 1)
|
|
{
|
|
c++;
|
|
}
|
|
|
|
if (c + 1 > w)
|
|
{
|
|
w = c + 1;
|
|
}
|
|
|
|
h = r - y + 1;
|
|
}
|
|
|
|
if (x > -1)
|
|
{
|
|
runes.Add (rune);
|
|
}
|
|
|
|
// See Issue #2616
|
|
//foreach (var combMark in contents [r, c].CombiningMarks) {
|
|
// runes.Add (combMark);
|
|
//}
|
|
}
|
|
|
|
if (runes.Count > 0)
|
|
{
|
|
lines.Add (runes);
|
|
}
|
|
}
|
|
|
|
// Remove unnecessary empty lines
|
|
if (lines.Count > 0)
|
|
{
|
|
for (int r = lines.Count - 1; r > h - 1; r--)
|
|
{
|
|
lines.RemoveAt (r);
|
|
}
|
|
}
|
|
|
|
// Remove trailing whitespace on each line
|
|
foreach (List<Rune> row in lines)
|
|
{
|
|
for (int c = row.Count - 1; c >= 0; c--)
|
|
{
|
|
Rune rune = row [c];
|
|
|
|
if (rune != (Rune)' ' || row.Sum (x => x.GetColumns ()) == w)
|
|
{
|
|
break;
|
|
}
|
|
|
|
row.RemoveAt (c);
|
|
}
|
|
}
|
|
|
|
// Convert Rune list to string
|
|
for (var r = 0; r < lines.Count; r++)
|
|
{
|
|
var line = StringExtensions.ToString (lines [r]);
|
|
|
|
if (r == lines.Count - 1)
|
|
{
|
|
sb.Append (line);
|
|
}
|
|
else
|
|
{
|
|
sb.AppendLine (line);
|
|
}
|
|
}
|
|
|
|
var actualLook = sb.ToString ();
|
|
|
|
if (string.Equals (expectedLook, actualLook))
|
|
{
|
|
return new Rect (x > -1 ? x : 0, y > -1 ? y : 0, w > -1 ? w : 0, h > -1 ? h : 0);
|
|
}
|
|
|
|
// standardize line endings for the comparison
|
|
expectedLook = expectedLook.Replace ("\r\n", "\n");
|
|
actualLook = actualLook.Replace ("\r\n", "\n");
|
|
|
|
// Remove the first and the last line ending from the expectedLook
|
|
if (expectedLook.StartsWith ("\n"))
|
|
{
|
|
expectedLook = expectedLook [1..];
|
|
}
|
|
|
|
if (expectedLook.EndsWith ("\n"))
|
|
{
|
|
expectedLook = expectedLook [..^1];
|
|
}
|
|
|
|
output?.WriteLine ("Expected:" + Environment.NewLine + expectedLook);
|
|
output?.WriteLine (" But Was:" + Environment.NewLine + actualLook);
|
|
|
|
Assert.Equal (expectedLook, actualLook);
|
|
|
|
return new Rect (x > -1 ? x : 0, y > -1 ? y : 0, w > -1 ? w : 0, h > -1 ? h : 0);
|
|
}
|
|
|
|
#pragma warning disable xUnit1013 // Public method should be marked as test
|
|
/// <summary>
|
|
/// Verifies two strings are equivalent. If the assert fails, output will be generated to standard output showing
|
|
/// the expected and actual look.
|
|
/// </summary>
|
|
/// <param name="output"></param>
|
|
/// <param name="expectedLook">
|
|
/// A string containing the expected look. Newlines should be specified as "\r\n" as they will
|
|
/// be converted to <see cref="Environment.NewLine"/> to make tests platform independent.
|
|
/// </param>
|
|
/// <param name="actualLook"></param>
|
|
public static void AssertEqual (ITestOutputHelper output, string expectedLook, string actualLook)
|
|
{
|
|
// Convert newlines to platform-specific newlines
|
|
expectedLook = ReplaceNewLinesToPlatformSpecific (expectedLook);
|
|
|
|
// If test is about to fail show user what things looked like
|
|
if (!string.Equals (expectedLook, actualLook))
|
|
{
|
|
output?.WriteLine ("Expected:" + Environment.NewLine + expectedLook);
|
|
output?.WriteLine (" But Was:" + Environment.NewLine + actualLook);
|
|
}
|
|
|
|
Assert.Equal (expectedLook, actualLook);
|
|
}
|
|
#pragma warning restore xUnit1013 // Public method should be marked as test
|
|
|
|
public static string DriverContentsToString (ConsoleDriver driver = null)
|
|
{
|
|
var sb = new StringBuilder ();
|
|
driver ??= Application.Driver;
|
|
|
|
Cell [,] contents = driver.Contents;
|
|
|
|
for (var r = 0; r < driver.Rows; r++)
|
|
{
|
|
for (var c = 0; c < driver.Cols; c++)
|
|
{
|
|
Rune rune = contents [r, c].Rune;
|
|
|
|
if (rune.DecodeSurrogatePair (out char [] sp))
|
|
{
|
|
sb.Append (sp);
|
|
}
|
|
else
|
|
{
|
|
sb.Append ((char)rune.Value);
|
|
}
|
|
|
|
if (rune.GetColumns () > 1)
|
|
{
|
|
c++;
|
|
}
|
|
|
|
// See Issue #2616
|
|
//foreach (var combMark in contents [r, c].CombiningMarks) {
|
|
// sb.Append ((char)combMark.Value);
|
|
//}
|
|
}
|
|
|
|
sb.AppendLine ();
|
|
}
|
|
|
|
return sb.ToString ();
|
|
}
|
|
|
|
/// <summary>Gets a list of instances of all classes derived from View.</summary>
|
|
/// <returns>List of View objects</returns>
|
|
public static List<View> GetAllViews ()
|
|
{
|
|
return typeof (View).Assembly.GetTypes ()
|
|
.Where (
|
|
type => type.IsClass
|
|
&& !type.IsAbstract
|
|
&& type.IsPublic
|
|
&& type.IsSubclassOf (typeof (View))
|
|
)
|
|
.Select (type => GetTypeInitializer (type, type.GetConstructor (Array.Empty<Type> ())))
|
|
.ToList ();
|
|
}
|
|
|
|
/// <summary>
|
|
/// Verifies the console used all the <paramref name="expectedColors"/> when rendering. If one or more of the
|
|
/// expected colors are not used then the failure will output both the colors that were found to be used and which of
|
|
/// your expectations was not met.
|
|
/// </summary>
|
|
/// <param name="driver">if null uses <see cref="Application.Driver"/></param>
|
|
/// <param name="expectedColors"></param>
|
|
internal static void AssertDriverUsedColors (ConsoleDriver driver = null, params Attribute [] expectedColors)
|
|
{
|
|
driver ??= Application.Driver;
|
|
Cell [,] contents = driver.Contents;
|
|
|
|
List<Attribute> toFind = expectedColors.ToList ();
|
|
|
|
// Contents 3rd column is an Attribute
|
|
HashSet<Attribute> colorsUsed = new ();
|
|
|
|
for (var r = 0; r < driver.Rows; r++)
|
|
{
|
|
for (var c = 0; c < driver.Cols; c++)
|
|
{
|
|
Attribute? val = contents [r, c].Attribute;
|
|
|
|
if (val.HasValue)
|
|
{
|
|
colorsUsed.Add (val.Value);
|
|
|
|
Attribute match = toFind.FirstOrDefault (e => e == val);
|
|
|
|
// need to check twice because Attribute is a struct and therefore cannot be null
|
|
if (toFind.Any (e => e == val))
|
|
{
|
|
toFind.Remove (match);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
if (!toFind.Any ())
|
|
{
|
|
return;
|
|
}
|
|
|
|
var sb = new StringBuilder ();
|
|
sb.AppendLine ("The following colors were not used:" + string.Join ("; ", toFind.Select (a => a.ToString ())));
|
|
sb.AppendLine ("Colors used were:" + string.Join ("; ", colorsUsed.Select (a => a.ToString ())));
|
|
|
|
throw new Exception (sb.ToString ());
|
|
}
|
|
|
|
private static void AddArguments (Type paramType, List<object> pTypes)
|
|
{
|
|
if (paramType == typeof (Rect))
|
|
{
|
|
pTypes.Add (Rect.Empty);
|
|
}
|
|
else if (paramType == typeof (string))
|
|
{
|
|
pTypes.Add (string.Empty);
|
|
}
|
|
else if (paramType == typeof (int))
|
|
{
|
|
pTypes.Add (0);
|
|
}
|
|
else if (paramType == typeof (bool))
|
|
{
|
|
pTypes.Add (true);
|
|
}
|
|
else if (paramType.Name == "IList")
|
|
{
|
|
pTypes.Add (new List<object> ());
|
|
}
|
|
else if (paramType.Name == "View")
|
|
{
|
|
var top = new Toplevel ();
|
|
var view = new View ();
|
|
top.Add (view);
|
|
pTypes.Add (view);
|
|
}
|
|
else if (paramType.Name == "View[]")
|
|
{
|
|
pTypes.Add (new View [] { });
|
|
}
|
|
else if (paramType.Name == "Stream")
|
|
{
|
|
pTypes.Add (new MemoryStream ());
|
|
}
|
|
else if (paramType.Name == "String")
|
|
{
|
|
pTypes.Add (string.Empty);
|
|
}
|
|
else if (paramType.Name == "TreeView`1[T]")
|
|
{
|
|
pTypes.Add (string.Empty);
|
|
}
|
|
else
|
|
{
|
|
pTypes.Add (null);
|
|
}
|
|
}
|
|
|
|
private static View GetTypeInitializer (Type type, ConstructorInfo ctor)
|
|
{
|
|
View viewType = null;
|
|
|
|
if (type.IsGenericType && type.IsTypeDefinition)
|
|
{
|
|
List<Type> gTypes = new ();
|
|
|
|
foreach (Type args in type.GetGenericArguments ())
|
|
{
|
|
gTypes.Add (typeof (object));
|
|
}
|
|
|
|
type = type.MakeGenericType (gTypes.ToArray ());
|
|
|
|
Assert.IsType (type, (View)Activator.CreateInstance (type));
|
|
}
|
|
else
|
|
{
|
|
ParameterInfo [] paramsInfo = ctor.GetParameters ();
|
|
Type paramType;
|
|
List<object> pTypes = new ();
|
|
|
|
if (type.IsGenericType)
|
|
{
|
|
foreach (Type args in type.GetGenericArguments ())
|
|
{
|
|
paramType = args.GetType ();
|
|
|
|
if (args.Name == "T")
|
|
{
|
|
pTypes.Add (typeof (object));
|
|
}
|
|
else
|
|
{
|
|
AddArguments (paramType, pTypes);
|
|
}
|
|
}
|
|
}
|
|
|
|
foreach (ParameterInfo p in paramsInfo)
|
|
{
|
|
paramType = p.ParameterType;
|
|
|
|
if (p.HasDefaultValue)
|
|
{
|
|
pTypes.Add (p.DefaultValue);
|
|
}
|
|
else
|
|
{
|
|
AddArguments (paramType, pTypes);
|
|
}
|
|
}
|
|
|
|
if (type.IsGenericType && !type.IsTypeDefinition)
|
|
{
|
|
viewType = (View)Activator.CreateInstance (type);
|
|
Assert.IsType (type, viewType);
|
|
}
|
|
else
|
|
{
|
|
viewType = (View)ctor.Invoke (pTypes.ToArray ());
|
|
Assert.IsType (type, viewType);
|
|
}
|
|
}
|
|
|
|
return viewType;
|
|
}
|
|
|
|
[GeneratedRegex ("^\\s+", RegexOptions.Multiline)]
|
|
private static partial Regex LeadingWhitespaceRegEx ();
|
|
|
|
private static string ReplaceNewLinesToPlatformSpecific (string toReplace)
|
|
{
|
|
string replaced = toReplace;
|
|
|
|
replaced = Environment.NewLine.Length switch
|
|
{
|
|
2 when !replaced.Contains ("\r\n") => replaced.Replace ("\n", Environment.NewLine),
|
|
1 => replaced.Replace ("\r\n", Environment.NewLine),
|
|
var _ => replaced
|
|
};
|
|
|
|
return replaced;
|
|
}
|
|
|
|
[GeneratedRegex ("\\s+$", RegexOptions.Multiline)]
|
|
private static partial Regex TrailingWhiteSpaceRegEx ();
|
|
}
|