DriverAssert.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. using System.Text;
  2. using System.Text.RegularExpressions;
  3. using Xunit.Abstractions;
  4. using Attribute = Terminal.Gui.Attribute;
  5. namespace UnitTests;
  6. /// <summary>
  7. /// Provides xUnit-style assertions for <see cref="Terminal.Gui.IConsoleDriver"/> contents.
  8. /// </summary>
  9. internal partial class DriverAssert
  10. {
  11. private const char SpaceChar = ' ';
  12. private static readonly Rune SpaceRune = (Rune)SpaceChar;
  13. #pragma warning disable xUnit1013 // Public method should be marked as test
  14. /// <summary>
  15. /// Verifies <paramref name="expectedAttributes"/> are found at the locations specified by
  16. /// <paramref name="expectedLook"/>. <paramref name="expectedLook"/> is a bitmap of indexes into
  17. /// <paramref name="expectedAttributes"/> (e.g. "00110" means the attribute at <c>expectedAttributes[1]</c> is expected
  18. /// at the 3rd and 4th columns of the 1st row of driver.Contents).
  19. /// </summary>
  20. /// <param name="expectedLook">
  21. /// Numbers between 0 and 9 for each row/col of the console. Must be valid indexes into
  22. /// <paramref name="expectedAttributes"/>.
  23. /// </param>
  24. /// <param name="output"></param>
  25. /// <param name="driver">The IConsoleDriver to use. If null <see cref="Application.Driver"/> will be used.</param>
  26. /// <param name="expectedAttributes"></param>
  27. public static void AssertDriverAttributesAre (
  28. string expectedLook,
  29. ITestOutputHelper output,
  30. IConsoleDriver driver = null,
  31. params Attribute [] expectedAttributes
  32. )
  33. {
  34. #pragma warning restore xUnit1013 // Public method should be marked as test
  35. if (expectedAttributes.Length > 10)
  36. {
  37. throw new ArgumentException ("This method only works for UIs that use at most 10 colors");
  38. }
  39. expectedLook = expectedLook.Trim ();
  40. driver ??= Application.Driver;
  41. Cell [,] contents = driver.Contents;
  42. var line = 0;
  43. foreach (string lineString in expectedLook.Split ('\n').Select (l => l.Trim ()))
  44. {
  45. for (var c = 0; c < lineString.Length; c++)
  46. {
  47. Attribute? val = contents [line, c].Attribute;
  48. List<Attribute> match = expectedAttributes.Where (e => e == val).ToList ();
  49. switch (match.Count)
  50. {
  51. case 0:
  52. output.WriteLine (
  53. $"{Application.ToString (driver)}\n"
  54. + $"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"
  55. + $" Expected: {string.Join (",", expectedAttributes.Select (c => c))}\n"
  56. + $" But Was: <not found>"
  57. );
  58. Assert.Empty (match);
  59. return;
  60. case > 1:
  61. throw new ArgumentException (
  62. $"Bad value for expectedColors, {match.Count} Attributes had the same Value"
  63. );
  64. }
  65. char colorUsed = Array.IndexOf (expectedAttributes, match [0]).ToString () [0];
  66. char userExpected = lineString [c];
  67. if (colorUsed != userExpected)
  68. {
  69. output.WriteLine ($"{Application.ToString (driver)}");
  70. output.WriteLine ($"Unexpected Attribute at Contents[{line},{c}] {contents [line, c]}.");
  71. output.WriteLine ($" Expected: {userExpected} ({expectedAttributes [int.Parse (userExpected.ToString ())]})");
  72. output.WriteLine ($" But Was: {colorUsed} ({val})");
  73. Assert.Equal (userExpected, colorUsed);
  74. return;
  75. }
  76. }
  77. line++;
  78. }
  79. }
  80. #pragma warning disable xUnit1013 // Public method should be marked as test
  81. /// <summary>Asserts that the driver contents match the expected contents, optionally ignoring any trailing whitespace.</summary>
  82. /// <param name="expectedLook"></param>
  83. /// <param name="output"></param>
  84. /// <param name="driver">The IConsoleDriver to use. If null <see cref="Application.Driver"/> will be used.</param>
  85. /// <param name="ignoreLeadingWhitespace"></param>
  86. public static void AssertDriverContentsAre (
  87. string expectedLook,
  88. ITestOutputHelper output,
  89. IConsoleDriver driver = null,
  90. bool ignoreLeadingWhitespace = false
  91. )
  92. {
  93. #pragma warning restore xUnit1013 // Public method should be marked as test
  94. var actualLook = Application.ToString (driver ?? Application.Driver);
  95. if (string.Equals (expectedLook, actualLook))
  96. {
  97. return;
  98. }
  99. // get rid of trailing whitespace on each line (and leading/trailing whitespace of start/end of full string)
  100. expectedLook = TrailingWhiteSpaceRegEx ().Replace (expectedLook, "").Trim ();
  101. actualLook = TrailingWhiteSpaceRegEx ().Replace (actualLook, "").Trim ();
  102. if (ignoreLeadingWhitespace)
  103. {
  104. expectedLook = LeadingWhitespaceRegEx ().Replace (expectedLook, "").Trim ();
  105. actualLook = LeadingWhitespaceRegEx ().Replace (actualLook, "").Trim ();
  106. }
  107. // standardize line endings for the comparison
  108. expectedLook = expectedLook.Replace ("\r\n", "\n");
  109. actualLook = actualLook.Replace ("\r\n", "\n");
  110. // If test is about to fail show user what things looked like
  111. if (!string.Equals (expectedLook, actualLook))
  112. {
  113. output?.WriteLine ("Expected:" + Environment.NewLine + expectedLook);
  114. output?.WriteLine (" But Was:" + Environment.NewLine + actualLook);
  115. }
  116. Assert.Equal (expectedLook, actualLook);
  117. }
  118. /// <summary>
  119. /// Asserts that the driver contents are equal to the provided string.
  120. /// </summary>
  121. /// <param name="expectedLook"></param>
  122. /// <param name="output"></param>
  123. /// <param name="driver">The IConsoleDriver to use. If null <see cref="Application.Driver"/> will be used.</param>
  124. /// <returns></returns>
  125. public static Rectangle AssertDriverContentsWithFrameAre (
  126. string expectedLook,
  127. ITestOutputHelper output,
  128. IConsoleDriver driver = null
  129. )
  130. {
  131. List<List<Rune>> lines = new ();
  132. var sb = new StringBuilder ();
  133. driver ??= Application.Driver;
  134. int x = -1;
  135. int y = -1;
  136. int w = -1;
  137. int h = -1;
  138. Cell [,] contents = driver.Contents;
  139. for (var rowIndex = 0; rowIndex < driver.Rows; rowIndex++)
  140. {
  141. List<Rune> runes = [];
  142. for (var colIndex = 0; colIndex < driver.Cols; colIndex++)
  143. {
  144. Rune runeAtCurrentLocation = contents [rowIndex, colIndex].Rune;
  145. if (runeAtCurrentLocation != SpaceRune)
  146. {
  147. if (x == -1)
  148. {
  149. x = colIndex;
  150. y = rowIndex;
  151. for (var i = 0; i < colIndex; i++)
  152. {
  153. runes.InsertRange (i, [SpaceRune]);
  154. }
  155. }
  156. if (runeAtCurrentLocation.GetColumns () > 1)
  157. {
  158. colIndex++;
  159. }
  160. if (colIndex + 1 > w)
  161. {
  162. w = colIndex + 1;
  163. }
  164. h = rowIndex - y + 1;
  165. }
  166. if (x > -1)
  167. {
  168. runes.Add (runeAtCurrentLocation);
  169. }
  170. // See Issue #2616
  171. //foreach (var combMark in contents [r, c].CombiningMarks) {
  172. // runes.Add (combMark);
  173. //}
  174. }
  175. if (runes.Count > 0)
  176. {
  177. lines.Add (runes);
  178. }
  179. }
  180. // Remove unnecessary empty lines
  181. if (lines.Count > 0)
  182. {
  183. for (int r = lines.Count - 1; r > h - 1; r--)
  184. {
  185. lines.RemoveAt (r);
  186. }
  187. }
  188. // Remove trailing whitespace on each line
  189. foreach (List<Rune> row in lines)
  190. {
  191. for (int c = row.Count - 1; c >= 0; c--)
  192. {
  193. Rune rune = row [c];
  194. if (rune != (Rune)' ' || row.Sum (x => x.GetColumns ()) == w)
  195. {
  196. break;
  197. }
  198. row.RemoveAt (c);
  199. }
  200. }
  201. // Convert Rune list to string
  202. for (var r = 0; r < lines.Count; r++)
  203. {
  204. var line = StringExtensions.ToString (lines [r]);
  205. if (r == lines.Count - 1)
  206. {
  207. sb.Append (line);
  208. }
  209. else
  210. {
  211. sb.AppendLine (line);
  212. }
  213. }
  214. var actualLook = sb.ToString ();
  215. if (string.Equals (expectedLook, actualLook))
  216. {
  217. return new (x > -1 ? x : 0, y > -1 ? y : 0, w > -1 ? w : 0, h > -1 ? h : 0);
  218. }
  219. // standardize line endings for the comparison
  220. expectedLook = expectedLook.ReplaceLineEndings ();
  221. actualLook = actualLook.ReplaceLineEndings ();
  222. // Remove the first and the last line ending from the expectedLook
  223. if (expectedLook.StartsWith (Environment.NewLine))
  224. {
  225. expectedLook = expectedLook [Environment.NewLine.Length..];
  226. }
  227. if (expectedLook.EndsWith (Environment.NewLine))
  228. {
  229. expectedLook = expectedLook [..^Environment.NewLine.Length];
  230. }
  231. // If test is about to fail show user what things looked like
  232. if (!string.Equals (expectedLook, actualLook))
  233. {
  234. output?.WriteLine ("Expected:" + Environment.NewLine + expectedLook);
  235. output?.WriteLine (" But Was:" + Environment.NewLine + actualLook);
  236. }
  237. Assert.Equal (expectedLook, actualLook);
  238. return new (x > -1 ? x : 0, y > -1 ? y : 0, w > -1 ? w : 0, h > -1 ? h : 0);
  239. }
  240. /// <summary>
  241. /// Verifies the console used all the <paramref name="expectedColors"/> when rendering. If one or more of the
  242. /// expected colors are not used then the failure will output both the colors that were found to be used and which of
  243. /// your expectations was not met.
  244. /// </summary>
  245. /// <param name="driver">if null uses <see cref="Application.Driver"/></param>
  246. /// <param name="expectedColors"></param>
  247. internal static void AssertDriverUsedColors (IConsoleDriver driver = null, params Attribute [] expectedColors)
  248. {
  249. driver ??= Application.Driver;
  250. Cell [,] contents = driver.Contents;
  251. List<Attribute> toFind = expectedColors.ToList ();
  252. // Contents 3rd column is an Attribute
  253. HashSet<Attribute> colorsUsed = new ();
  254. for (var r = 0; r < driver.Rows; r++)
  255. {
  256. for (var c = 0; c < driver.Cols; c++)
  257. {
  258. Attribute? val = contents [r, c].Attribute;
  259. if (val.HasValue)
  260. {
  261. colorsUsed.Add (val.Value);
  262. Attribute match = toFind.FirstOrDefault (e => e == val);
  263. // need to check twice because Attribute is a struct and therefore cannot be null
  264. if (toFind.Any (e => e == val))
  265. {
  266. toFind.Remove (match);
  267. }
  268. }
  269. }
  270. }
  271. if (!toFind.Any ())
  272. {
  273. return;
  274. }
  275. var sb = new StringBuilder ();
  276. sb.AppendLine ("The following colors were not used:" + string.Join ("; ", toFind.Select (a => a.ToString ())));
  277. sb.AppendLine ("Colors used were:" + string.Join ("; ", colorsUsed.Select (a => a.ToString ())));
  278. throw new (sb.ToString ());
  279. }
  280. [GeneratedRegex ("^\\s+", RegexOptions.Multiline)]
  281. private static partial Regex LeadingWhitespaceRegEx ();
  282. [GeneratedRegex ("\\s+$", RegexOptions.Multiline)]
  283. private static partial Regex TrailingWhiteSpaceRegEx ();
  284. }