TestHelpers.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using Xunit.Abstractions;
  6. using Xunit;
  7. using System.Text.RegularExpressions;
  8. using System.Reflection;
  9. using System.Diagnostics;
  10. using Attribute = Terminal.Gui.Attribute;
  11. using Microsoft.VisualStudio.TestPlatform.Utilities;
  12. using Xunit.Sdk;
  13. using System.Globalization;
  14. namespace Terminal.Gui;
  15. // This class enables test functions annotated with the [AutoInitShutdown] attribute to
  16. // automatically call Application.Init at start of the test and Application.Shutdown after the
  17. // test exits.
  18. //
  19. // This is necessary because a) Application is a singleton and Init/Shutdown must be called
  20. // as a pair, and b) all unit test functions should be atomic..
  21. [AttributeUsage (AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
  22. public class AutoInitShutdownAttribute : Xunit.Sdk.BeforeAfterTestAttribute {
  23. /// <summary>
  24. /// Initializes a [AutoInitShutdown] attribute, which determines if/how Application.Init and
  25. /// Application.Shutdown are automatically called Before/After a test runs.
  26. /// </summary>
  27. /// <param name="autoInit">If true, Application.Init will be called Before the test runs.</param>
  28. /// <param name="autoShutdown">If true, Application.Shutdown will be called After the test runs.</param>
  29. /// <param name="consoleDriverType">Determines which ConsoleDriver (FakeDriver, WindowsDriver,
  30. /// CursesDriver, NetDriver) will be used when Application.Init is called. If null FakeDriver will be used.
  31. /// Only valid if <paramref name="autoInit"/> is true.</param>
  32. /// <param name="useFakeClipboard">If true, will force the use of <see cref="FakeDriver.FakeClipboard"/>.
  33. /// Only valid if <see cref="ConsoleDriver"/> == <see cref="FakeDriver"/> and <paramref name="autoInit"/> is true.</param>
  34. /// <param name="fakeClipboardAlwaysThrowsNotSupportedException">Only valid if <paramref name="autoInit"/> is true.
  35. /// Only valid if <see cref="ConsoleDriver"/> == <see cref="FakeDriver"/> and <paramref name="autoInit"/> is true.</param>
  36. /// <param name="fakeClipboardIsSupportedAlwaysTrue">Only valid if <paramref name="autoInit"/> is true.
  37. /// Only valid if <see cref="ConsoleDriver"/> == <see cref="FakeDriver"/> and <paramref name="autoInit"/> is true.</param>
  38. /// <param name="configLocation">Determines what config file locations <see cref="ConfigurationManager"/> will
  39. /// load from.</param>
  40. public AutoInitShutdownAttribute (bool autoInit = true,
  41. Type consoleDriverType = null,
  42. bool useFakeClipboard = true,
  43. bool fakeClipboardAlwaysThrowsNotSupportedException = false,
  44. bool fakeClipboardIsSupportedAlwaysTrue = false,
  45. ConfigurationManager.ConfigLocations configLocation = ConfigurationManager.ConfigLocations.DefaultOnly)
  46. {
  47. AutoInit = autoInit;
  48. CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.GetCultureInfo ("en-US");
  49. _driverType = consoleDriverType ?? typeof (FakeDriver);
  50. FakeDriver.FakeBehaviors.UseFakeClipboard = useFakeClipboard;
  51. FakeDriver.FakeBehaviors.FakeClipboardAlwaysThrowsNotSupportedException = fakeClipboardAlwaysThrowsNotSupportedException;
  52. FakeDriver.FakeBehaviors.FakeClipboardIsSupportedAlwaysFalse = fakeClipboardIsSupportedAlwaysTrue;
  53. ConfigurationManager.Locations = configLocation;
  54. }
  55. bool AutoInit { get; }
  56. Type _driverType;
  57. public override void Before (MethodInfo methodUnderTest)
  58. {
  59. Debug.WriteLine ($"Before: {methodUnderTest.Name}");
  60. if (AutoInit) {
  61. Application.Init ((ConsoleDriver)Activator.CreateInstance (_driverType));
  62. }
  63. }
  64. public override void After (MethodInfo methodUnderTest)
  65. {
  66. Debug.WriteLine ($"After: {methodUnderTest.Name}");
  67. if (AutoInit) {
  68. Application.Shutdown ();
  69. }
  70. }
  71. }
  72. [AttributeUsage (AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
  73. public class SetupFakeDriverAttribute : Xunit.Sdk.BeforeAfterTestAttribute {
  74. /// <summary>
  75. /// Enables test functions annotated with the [SetupFakeDriver] attribute to
  76. /// set Application.Driver to new FakeDriver().
  77. /// </summary>
  78. public SetupFakeDriverAttribute ()
  79. {
  80. }
  81. public override void Before (MethodInfo methodUnderTest)
  82. {
  83. Debug.WriteLine ($"Before: {methodUnderTest.Name}");
  84. Assert.Null (Application.Driver);
  85. Application.Driver = new FakeDriver ();
  86. }
  87. public override void After (MethodInfo methodUnderTest)
  88. {
  89. Debug.WriteLine ($"After: {methodUnderTest.Name}");
  90. Application.Driver = null;
  91. }
  92. }
  93. partial class TestHelpers {
  94. [GeneratedRegex ("\\s+$", RegexOptions.Multiline)]
  95. private static partial Regex TrailingWhiteSpaceRegEx ();
  96. [GeneratedRegex ("^\\s+", RegexOptions.Multiline)]
  97. private static partial Regex LeadingWhitespaceRegEx ();
  98. #pragma warning disable xUnit1013 // Public method should be marked as test
  99. public static void AssertDriverContentsAre (string expectedLook, ITestOutputHelper output, bool ignoreLeadingWhitespace = false)
  100. {
  101. #pragma warning restore xUnit1013 // Public method should be marked as test
  102. var sb = new StringBuilder ();
  103. var driver = (FakeDriver)Application.Driver;
  104. var contents = driver.Contents;
  105. for (int r = 0; r < driver.Rows; r++) {
  106. for (int c = 0; c < driver.Cols; c++) {
  107. // TODO: Remove hard-coded [0] once combining pairs is supported
  108. Rune rune = contents [r, c].Runes[0];
  109. if (rune.DecodeSurrogatePair (out char [] spair)) {
  110. sb.Append (spair);
  111. } else {
  112. sb.Append ((char)rune.Value);
  113. }
  114. if (rune.GetColumns () > 1) {
  115. c++;
  116. }
  117. }
  118. sb.AppendLine ();
  119. }
  120. var actualLook = sb.ToString ();
  121. if (string.Equals (expectedLook, actualLook)) return;
  122. // get rid of trailing whitespace on each line (and leading/trailing whitespace of start/end of full string)
  123. expectedLook = TrailingWhiteSpaceRegEx ().Replace (expectedLook, "").Trim ();
  124. actualLook = TrailingWhiteSpaceRegEx ().Replace (actualLook, "").Trim ();
  125. if (ignoreLeadingWhitespace) {
  126. expectedLook = LeadingWhitespaceRegEx().Replace (expectedLook, "").Trim ();
  127. actualLook = LeadingWhitespaceRegEx().Replace (actualLook, "").Trim ();
  128. }
  129. // standardize line endings for the comparison
  130. expectedLook = expectedLook.Replace ("\r\n", "\n");
  131. actualLook = actualLook.Replace ("\r\n", "\n");
  132. // If test is about to fail show user what things looked like
  133. if (!string.Equals (expectedLook, actualLook)) {
  134. output?.WriteLine ("Expected:" + Environment.NewLine + expectedLook);
  135. output?.WriteLine ("But Was:" + Environment.NewLine + actualLook);
  136. }
  137. Assert.Equal (expectedLook, actualLook);
  138. }
  139. public static Rect AssertDriverContentsWithFrameAre (string expectedLook, ITestOutputHelper output)
  140. {
  141. var lines = new List<List<Rune>> ();
  142. var sb = new StringBuilder ();
  143. var driver = Application.Driver;
  144. var x = -1;
  145. var y = -1;
  146. var w = -1;
  147. var h = -1;
  148. var contents = driver.Contents;
  149. for (var r = 0; r < driver.Rows; r++) {
  150. var runes = new List<Rune> ();
  151. for (var c = 0; c < driver.Cols; c++) {
  152. // TODO: Remove hard-coded [0] once combining pairs is supported
  153. Rune rune = contents [r, c].Runes [0];
  154. if (rune != (Rune)' ') {
  155. if (x == -1) {
  156. x = c;
  157. y = r;
  158. for (int i = 0; i < c; i++) {
  159. runes.InsertRange (i, new List<Rune> () { (Rune)' ' });
  160. }
  161. }
  162. if (rune.GetColumns () > 1) {
  163. c++;
  164. }
  165. if (c + 1 > w) {
  166. w = c + 1;
  167. }
  168. h = r - y + 1;
  169. }
  170. if (x > -1) runes.Add (rune);
  171. }
  172. if (runes.Count > 0) lines.Add (runes);
  173. }
  174. // Remove unnecessary empty lines
  175. if (lines.Count > 0) {
  176. for (var r = lines.Count - 1; r > h - 1; r--) lines.RemoveAt (r);
  177. }
  178. // Remove trailing whitespace on each line
  179. foreach (var row in lines) {
  180. for (var c = row.Count - 1; c >= 0; c--) {
  181. var rune = row [c];
  182. if (rune != (Rune)' ' || (row.Sum (x => x.GetColumns ()) == w)) {
  183. break;
  184. }
  185. row.RemoveAt (c);
  186. }
  187. }
  188. // Convert Rune list to string
  189. for (int r = 0; r < lines.Count; r++) {
  190. var line = Terminal.Gui.StringExtensions.ToString (lines [r]).ToString ();
  191. if (r == lines.Count - 1) {
  192. sb.Append (line);
  193. } else {
  194. sb.AppendLine (line);
  195. }
  196. }
  197. var actualLook = sb.ToString ();
  198. if (string.Equals (expectedLook, actualLook)) {
  199. return new Rect (x > -1 ? x : 0, y > -1 ? y : 0, w > -1 ? w : 0, h > -1 ? h : 0);
  200. }
  201. // standardize line endings for the comparison
  202. expectedLook = expectedLook.Replace ("\r\n", "\n");
  203. actualLook = actualLook.Replace ("\r\n", "\n");
  204. // Remove the first and the last line ending from the expectedLook
  205. if (expectedLook.StartsWith ("\n")) expectedLook = expectedLook [1..];
  206. if (expectedLook.EndsWith ("\n")) expectedLook = expectedLook [..^1];
  207. output?.WriteLine ("Expected:" + Environment.NewLine + expectedLook);
  208. output?.WriteLine ("But Was:" + Environment.NewLine + actualLook);
  209. Assert.Equal (expectedLook, actualLook);
  210. return new Rect (x > -1 ? x : 0, y > -1 ? y : 0, w > -1 ? w : 0, h > -1 ? h : 0);
  211. }
  212. #pragma warning disable xUnit1013 // Public method should be marked as test
  213. /// <summary>
  214. /// Verifies the console was rendered using the given <paramref name="expectedColors"/> at the given locations.
  215. /// Pass a bitmap of indexes into <paramref name="expectedColors"/> as <paramref name="expectedLook"/> and the
  216. /// test method will verify those colors were used in the row/col of the console during rendering
  217. /// </summary>
  218. /// <param name="expectedLook">Numbers between 0 and 9 for each row/col of the console. Must be valid indexes of <paramref name="expectedColors"/></param>
  219. /// <param name="expectedColors"></param>
  220. public static void AssertDriverColorsAre (string expectedLook, params Attribute [] expectedColors)
  221. {
  222. #pragma warning restore xUnit1013 // Public method should be marked as test
  223. if (expectedColors.Length > 10) throw new ArgumentException ("This method only works for UIs that use at most 10 colors");
  224. expectedLook = expectedLook.Trim ();
  225. var driver = (FakeDriver)Application.Driver;
  226. var contents = driver.Contents;
  227. var r = 0;
  228. foreach (var line in expectedLook.Split ('\n').Select (l => l.Trim ())) {
  229. for (var c = 0; c < line.Length; c++) {
  230. var val = contents [r, c].Attribute;
  231. var match = expectedColors.Where (e => e == val).ToList ();
  232. switch (match.Count) {
  233. case 0:
  234. throw new Exception ($"Unexpected color {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 => c.Value.ToString()))})");
  235. case > 1:
  236. throw new ArgumentException ($"Bad value for expectedColors, {match.Count} Attributes had the same Value");
  237. }
  238. var colorUsed = Array.IndexOf (expectedColors, match [0]).ToString () [0];
  239. var userExpected = line [c];
  240. 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} ({val}) but test expected {userExpected} ({expectedColors [int.Parse (userExpected.ToString ())].Value}) (these are indexes into the expectedColors array)");
  241. }
  242. r++;
  243. }
  244. }
  245. /// <summary>
  246. /// Verifies the console used all the <paramref name="expectedColors"/> when rendering.
  247. /// If one or more of the expected colors are not used then the failure will output both
  248. /// the colors that were found to be used and which of your expectations was not met.
  249. /// </summary>
  250. /// <param name="expectedColors"></param>
  251. internal static void AssertDriverUsedColors (params Attribute [] expectedColors)
  252. {
  253. var driver = (FakeDriver)Application.Driver;
  254. var contents = driver.Contents;
  255. var toFind = expectedColors.ToList ();
  256. // Contents 3rd column is an Attribute
  257. var colorsUsed = new HashSet<Attribute> ();
  258. for (var r = 0; r < driver.Rows; r++) {
  259. for (var c = 0; c < driver.Cols; c++) {
  260. var val = contents [r, c].Attribute;
  261. if (val.HasValue) {
  262. colorsUsed.Add (val.Value);
  263. var match = toFind.FirstOrDefault (e => e == val);
  264. // need to check twice because Attribute is a struct and therefore cannot be null
  265. if (toFind.Any (e => e == val)) {
  266. toFind.Remove (match);
  267. }
  268. }
  269. }}
  270. if (!toFind.Any ()) {
  271. return;
  272. }
  273. var sb = new StringBuilder ();
  274. sb.AppendLine ("The following colors were not used:" + string.Join ("; ", toFind.Select (a => a.ToString())));
  275. sb.AppendLine ("Colors used were:" + string.Join ("; ", colorsUsed.Select (a => a.ToString())));
  276. throw new Exception (sb.ToString ());
  277. }
  278. #pragma warning disable xUnit1013 // Public method should be marked as test
  279. /// <summary>
  280. /// Verifies two strings are equivalent. If the assert fails, output will be generated to standard
  281. /// output showing the expected and actual look.
  282. /// </summary>
  283. /// <param name="output"></param>
  284. /// <param name="expectedLook">A string containing the expected look. Newlines should be specified as "\r\n" as
  285. /// they will be converted to <see cref="Environment.NewLine"/> to make tests platform independent.</param>
  286. /// <param name="actualLook"></param>
  287. public static void AssertEqual (ITestOutputHelper output, string expectedLook, string actualLook)
  288. {
  289. // Convert newlines to platform-specific newlines
  290. expectedLook = ReplaceNewLinesToPlatformSpecific (expectedLook);
  291. // If test is about to fail show user what things looked like
  292. if (!string.Equals (expectedLook, actualLook)) {
  293. output?.WriteLine ("Expected:" + Environment.NewLine + expectedLook);
  294. output?.WriteLine ("But Was:" + Environment.NewLine + actualLook);
  295. }
  296. Assert.Equal (expectedLook, actualLook);
  297. }
  298. #pragma warning restore xUnit1013 // Public method should be marked as test
  299. private static string ReplaceNewLinesToPlatformSpecific (string toReplace)
  300. {
  301. var replaced = toReplace;
  302. replaced = Environment.NewLine.Length switch {
  303. 2 when !replaced.Contains ("\r\n") => replaced.Replace ("\n", Environment.NewLine),
  304. 1 => replaced.Replace ("\r\n", Environment.NewLine),
  305. var _ => replaced
  306. };
  307. return replaced;
  308. }
  309. }