Files
Terminal.Gui/UnitTests/TestHelpers.cs
Thomas Nind c1a578891b Fixes #2150. Revamping FileDialog (#2259)
* Investigating new file dialog

* Column sorting

* Add navigationStack

* Append autocomplete half working

* Change autocomplete append to use draw effect instead of selection effect

* WIP on FileDialog2

* Refactor sort order and add more 'ls' colors

* Refactor history to its own class

* FileDialog2 navigation fixes/improvements

* Added centered Title

* Add tree view and split container

* Add FileDialogState

* Add AllowsMultipleSelection

* Add result fields and Scenario

* Added FileDialo2 test file

* Fix FileDialog2 Redraw padding to respect max/min view bounds

* Fix unit tests and warnings

* Started on better keyboard navigation in FileDialog2

* Update to match new SplitContainer API

* Quality of Life improvements

* Fix recommending parent folder

* Remove border from SplitContainer in FileDialog2 and fixed tests

* Bugfixes and improvements to FileDialog2

* usability improvements to FileDialog2

* Add multi select and OpenMode

* Enforce OpenMode when making a multi selection

* Prevent typing illegal characters

* Added AllowedTypes to FileDialog2

* Added combo box filter AllowedType

* Improve code readability by reordering members

* Do not update FileDialog2 text box when selecting ".." in TableView

* Fix history navigation in FileDialog2

* Restore selection after navigating backwards in history

* Add FileDialog2 tests

* Make FileDialog2 Title user configurable

* Fix DirectTyping_Allowed unit test when running on linux

* Change Home/End to go to first/last cell in table in FileDialog2

* Remove overloaded Title property

* Switch to `ustring.IsNullOrEmpty`

* Update to latest TileView API

* Add TableView navigation by letter using CollectionNavigator

* Fix recreating search navigator too often

* Add tests for proper disposing

* Make Ctrl+F10 toggle split line focusability

* Fix layout bug in first tile when orientation is horizontal

* Switch to GenerateImage

* Fix not calling base constructor

* Revert "Merges latest LineCanvas into TileView"

* Fix keyboard tab navigation problems

* Workaround for changing CanFocus throwing Exceptions sometimes

* Update to latest splitcontainer API

* Adjust suggestions to be gray and properly update on keystrokes

* Move ok and cancel to bottom

* Add MustExist and fix multi selection of 1 result

* bugfixes and quality of life

* Navigating to .. clears path up to current dir

* Better arrow key navigation

* Make title pretty and informative

* Fix test

* Fix test

* Trim default Titles to be more compact and readable

* Fix bad merge changes

* Remove EscSeqReq files that are not in v2... came from develop?!

* Fix nullable and enable toggle select on table view

* Fix multi select return value

* Add icon and monochrome support

* Add search elements

* Add search for current directory

* WIP: Async search

* Thread safety and disposal

* Improve UX

* Fix for rapid search results

* Fix warnings and whitespace

* Don't add more than 10000 search results

* Add support for adjusting search matching

* Added ISearchMatcher example to FileDialog2Example

* Remove double spaces after periods

* Make MaxSearchResults a config setting

* Localization for FileDialog2

* Fix build error

* Support for custom open button Text

* Improve file dialog scenario UX

* Change feedback to a drawing effect in center of screen

* Explore MenuBar instead of ComboBox for AllowedTypes

* Fix prompt and move file open into try/catch for errors reading files

* Open menu when tabbed to

* FileDialog2 improvements
- Expose table/tree style properties
- Rename Monochrome to UseColors and default to false
- IconGetter no longer forces space
- On Windows in Scenario just use a backslash for folder icon (i.e. not unicode)
-

* Add style settings in scenario and make autocomplete case insensitive on Windows

* Move ok button text to Style

* xmldoc

* Remove old FileDialog and re-wire OpenDialog and SaveDialog to use FileDialog2 base

* localization

* Move open/save dialog to their own files

* Rename FileDialog2 to FileDialog

* Fix repetition in string

* Add IAllowedType

* Get rid of AllowedTypesIsStrict

User now adds the `IAllowedType` implementation `AllowedTypeAny`

* Add max length to AllowedType ToString

* Pressing Enter in find restarts search instead of confirm selection

* Add TreeRootGetter for customizing the quick access items in FileDialog

* Add FilesSelected event
Allows user to do things like confirm dialogs on selecting existing file(s)

* Update to new sender, event args signature

* Fix naming on MouseEventArgs

* Fix mouse events naming

* Revert "Fix naming on MouseEventArgs"

This reverts commit 2f557f52d9.

* Add deletion support

* Move delete keybinding to tableview

* Scaffold for rename and new operations

* Prevent delete dialog popping up again on cancel

* Add rename and new folder implementations

* Add rename,delete,new to context menu

* On rename or new, reselect the file in its new location in tree

* Support searching on multiple terms

* Localization support for new/rename/delete

* Refactor internal classes and add class diagram

* Move some visual properties to FileDialogStyle

* Ensure MultiSelected is never null and always contains Path if relevant

* Fix spacing/indentation

* WIP: Add new namespace Terminal.Gui.FileServices

* Improve appearance of back/forward/up

* Move SpinnerLabel to Views

* Add SpinnerView

* Code formatting

* Add AutoSpin test

* Avoid ever removing spinner timeout twice

* Make SpinnerView show/hide instead of stopping

* WIP: Refactor to use 3 sub PRs
- SpinnerView
- Suggest Append Autocomplete
- Caption TextField

* Add FilepathSuggestionGenerator

* WIP: FileDialog autocomplete append mostly working again

* Improve file autocomplete

* Move IconGetter to Style and provide default implementation

- Depends on `UseUnicodeCharacters`
- Also updated up/back/collapse/expand tree to use spicier icons

* Fix failing unit test

* Improved colors and layout

* Adjust use of unicode

* Fix UseUnicodeCharacters

* Update table style to include scroll indicators and lines

* Fix cycle suggestion with down cursor

* Adjust sort indicators

* Add default sort order on isDir then name

* Always use left/right unicode arrows

* Fix autocomplete suggesting in empty textbox

* Press escape to cancel ongoing search (when search box is focused)

* When entering a TreeView if there is no selection then select first object

* Move CursorIsAtEnd to TextField

* Improve layout

* Change UseColors to be a cell color fill

* Fxied tests for new apis

* Remove manual title drawing code

* Fix MoveEnd name conflicting with base class

* Fix merge conflicts

* Switched to IFileSystem for unit testing

* Add unit test

* Revert "Fix MoveEnd name conflicting with base class"

This reverts commit a5f9c07022.

* Fix MoveEnd name collision with 'new' keyword

* Fixed tree not toggling

* DateTime fixes and mocking

* Fix TestDirectoryContents_Windows

* Expose UseColors and UseUnicodeCharacters as config settings

* Fix linter settings having removed curly brackets

* Fix namespace on test

* Move tests to file services folder

* Remove the FileServices namespace

* Updated class diagram

* Clear title from tests for futureproofing

* Localization support for FileDialog title

* Remove trailing whitespace in "open existing"

* Fix listing suggestions immediately after folder path entered

---------

Co-authored-by: Tig <tig@users.noreply.github.com>
2023-04-09 03:28:56 -06:00

290 lines
10 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xunit.Abstractions;
using Xunit;
using Terminal.Gui;
using System.Text.RegularExpressions;
using System.Reflection;
using System.Diagnostics;
using Rune = System.Rune;
using Attribute = Terminal.Gui.Attribute;
// 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, AllowMultiple = false, Inherited = true)]
public class AutoInitShutdownAttribute : Xunit.Sdk.BeforeAfterTestAttribute {
/// <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, bool autoShutdown = true,
Type consoleDriverType = null,
bool useFakeClipboard = false,
bool fakeClipboardAlwaysThrowsNotSupportedException = false,
bool fakeClipboardIsSupportedAlwaysTrue = false,
ConfigurationManager.ConfigLocations configLocation = ConfigurationManager.ConfigLocations.DefaultOnly)
{
//Assert.True (autoInit == false && consoleDriverType == null);
AutoInit = autoInit;
AutoShutdown = autoShutdown;
DriverType = consoleDriverType ?? typeof (FakeDriver);
FakeDriver.FakeBehaviors.UseFakeClipboard = useFakeClipboard;
FakeDriver.FakeBehaviors.FakeClipboardAlwaysThrowsNotSupportedException = fakeClipboardAlwaysThrowsNotSupportedException;
FakeDriver.FakeBehaviors.FakeClipboardIsSupportedAlwaysFalse = fakeClipboardIsSupportedAlwaysTrue;
ConfigurationManager.Locations = configLocation;
}
static bool _init = false;
bool AutoInit { get; }
bool AutoShutdown { get; }
Type DriverType;
public override void Before (MethodInfo methodUnderTest)
{
Debug.WriteLine ($"Before: {methodUnderTest.Name}");
if (AutoShutdown && _init) {
throw new InvalidOperationException ("After did not run when AutoShutdown was specified.");
}
if (AutoInit) {
Application.Init ((ConsoleDriver)Activator.CreateInstance (DriverType));
_init = true;
}
}
public override void After (MethodInfo methodUnderTest)
{
Debug.WriteLine ($"After: {methodUnderTest.Name}");
if (AutoShutdown) {
Application.Shutdown ();
_init = false;
}
}
}
class TestHelpers {
#pragma warning disable xUnit1013 // Public method should be marked as test
public static void AssertDriverContentsAre (string expectedLook, ITestOutputHelper output, bool ignoreLeadingWhitespace = false)
{
#pragma warning restore xUnit1013 // Public method should be marked as test
var sb = new StringBuilder ();
var driver = ((FakeDriver)Application.Driver);
var contents = driver.Contents;
for (int r = 0; r < driver.Rows; r++) {
for (int c = 0; c < driver.Cols; c++) {
Rune rune = contents [r, c, 0];
if (Rune.DecodeSurrogatePair (rune, out char [] spair)) {
sb.Append (spair);
} else {
sb.Append ((char)rune);
}
if (Rune.ColumnWidth (rune) > 1) {
c++;
}
}
sb.AppendLine ();
}
var actualLook = sb.ToString ();
if (!string.Equals (expectedLook, actualLook)) {
// ignore trailing whitespace on each line
var trailingWhitespace = new Regex (@"\s+$", RegexOptions.Multiline);
var leadingWhitespace = new Regex(@"^\s+",RegexOptions.Multiline);
// get rid of trailing whitespace on each line (and leading/trailing whitespace of start/end of full string)
expectedLook = trailingWhitespace.Replace (expectedLook, "").Trim ();
actualLook = trailingWhitespace.Replace (actualLook, "").Trim ();
if(ignoreLeadingWhitespace)
{
expectedLook = leadingWhitespace.Replace (expectedLook, "").Trim ();
actualLook = leadingWhitespace.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);
}
}
public static Rect AssertDriverContentsWithFrameAre (string expectedLook, ITestOutputHelper output)
{
var lines = new List<List<Rune>> ();
var sb = new StringBuilder ();
var driver = ((FakeDriver)Application.Driver);
var x = -1;
var y = -1;
int w = -1;
int h = -1;
var contents = driver.Contents;
for (int r = 0; r < driver.Rows; r++) {
var runes = new List<Rune> ();
for (int c = 0; c < driver.Cols; c++) {
var rune = (Rune)contents [r, c, 0];
if (rune != ' ') {
if (x == -1) {
x = c;
y = r;
for (int i = 0; i < c; i++) {
runes.InsertRange (i, new List<Rune> () { ' ' });
}
}
if (Rune.ColumnWidth (rune) > 1) {
c++;
}
if (c + 1 > w) {
w = c + 1;
}
h = r - y + 1;
}
if (x > -1) {
runes.Add (rune);
}
}
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
for (int r = 0; r < lines.Count; r++) {
List<Rune> row = lines [r];
for (int c = row.Count - 1; c >= 0; c--) {
var rune = row [c];
if (rune != ' ' || (row.Sum (x => Rune.ColumnWidth (x)) == w)) {
break;
}
row.RemoveAt (c);
}
}
// Convert Rune list to string
for (int r = 0; r < lines.Count; r++) {
var line = NStack.ustring.Make (lines [r]).ToString ();
if (r == lines.Count - 1) {
sb.Append (line);
} else {
sb.AppendLine (line);
}
}
var actualLook = sb.ToString ();
if (!string.Equals (expectedLook, actualLook)) {
// 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 the console was rendered using the given <paramref name="expectedColors"/> at the given locations.
/// Pass a bitmap of indexes into <paramref name="expectedColors"/> as <paramref name="expectedLook"/> and the
/// test method will verify those colors were used in the row/col of the console during rendering
/// </summary>
/// <param name="expectedLook">Numbers between 0 and 9 for each row/col of the console. Must be valid indexes of <paramref name="expectedColors"/></param>
/// <param name="expectedColors"></param>
public static void AssertDriverColorsAre (string expectedLook, Attribute [] expectedColors)
{
#pragma warning restore xUnit1013 // Public method should be marked as test
if (expectedColors.Length > 10) {
throw new ArgumentException ("This method only works for UIs that use at most 10 colors");
}
expectedLook = expectedLook.Trim ();
var driver = ((FakeDriver)Application.Driver);
var contents = driver.Contents;
int r = 0;
foreach (var line in expectedLook.Split ('\n').Select (l => l.Trim ())) {
for (int c = 0; c < line.Length; c++) {
int val = contents [r, c, 1];
var match = expectedColors.Where (e => e.Value == val).ToList ();
if (match.Count == 0) {
throw new Exception ($"Unexpected color {DescribeColor (val)} was used at row {r} and col {c} (indexes start at 0). Color value was {val} (expected colors were {string.Join (",", expectedColors.Select (c => DescribeColor (c.Value)))})");
} else if (match.Count > 1) {
throw new ArgumentException ($"Bad value for expectedColors, {match.Count} Attributes had the same Value");
}
var colorUsed = Array.IndexOf (expectedColors, match [0]).ToString () [0];
var userExpected = line [c];
if (colorUsed != userExpected) {
throw new Exception ($"Colors used did not match expected at row {r} and col {c} (indexes start at 0). Color index used was {colorUsed} ({DescribeColor (val)}) but test expected {userExpected} ({DescribeColor (expectedColors [int.Parse (userExpected.ToString ())].Value)}) (these are indexes into the expectedColors array)");
}
}
r++;
}
}
private static object DescribeColor (int userExpected)
{
var a = new Attribute (userExpected);
return $"{a.Foreground},{a.Background}";
}
}