DriverAssert.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. #nullable enable
  2. using System.Text;
  3. using System.Text.RegularExpressions;
  4. using Xunit.Abstractions;
  5. namespace UnitTests;
  6. /// <summary>
  7. /// Provides xUnit-style assertions for <see cref="IDriver"/> contents.
  8. /// </summary>
  9. internal partial class DriverAssert
  10. {
  11. private const char SPACE_CHAR = ' ';
  12. private static readonly Rune _spaceRune = (Rune)SPACE_CHAR;
  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 IDriver 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. IDriver? 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. if (driver is null && ApplicationImpl.ModelUsage == ApplicationModelUsage.LegacyStatic)
  41. {
  42. driver = Application.Driver;
  43. }
  44. ArgumentNullException.ThrowIfNull(driver);
  45. Cell [,] contents = driver!.Contents!;
  46. var line = 0;
  47. foreach (string lineString in expectedLook.Split ('\n').Select (l => l.Trim ()))
  48. {
  49. for (var c = 0; c < lineString.Length; c++)
  50. {
  51. Attribute? val = contents! [line, c].Attribute;
  52. List<Attribute> match = expectedAttributes.Where (e => e == val).ToList ();
  53. switch (match.Count)
  54. {
  55. case 0:
  56. output.WriteLine (
  57. $"{driver.ToString ()}\n"
  58. + $"Expected Attribute {val} at Contents[{line},{c}] {contents [line, c]} was not found.\n"
  59. + $" Expected: {string.Join (",", expectedAttributes.Select (attr => attr))}\n"
  60. + $" But Was: <not found>"
  61. );
  62. Assert.Empty (match);
  63. return;
  64. case > 1:
  65. throw new ArgumentException (
  66. $"Bad value for expectedColors, {match.Count} Attributes had the same Value"
  67. );
  68. }
  69. char colorUsed = Array.IndexOf (expectedAttributes, match [0]).ToString () [0];
  70. char userExpected = lineString [c];
  71. if (colorUsed != userExpected)
  72. {
  73. output.WriteLine ($"{driver.ToString ()}");
  74. output.WriteLine ($"Unexpected Attribute at Contents[{line},{c}] = {contents [line, c]}.");
  75. output.WriteLine ($" Expected: {userExpected} ({expectedAttributes [int.Parse (userExpected.ToString ())]})");
  76. output.WriteLine ($" But Was: {colorUsed} ({val})");
  77. // Print `contents` as the expected and actual attribute indexes in a grid where each cell is of the form "e:a" (e = expected, a = actual)
  78. // e.g:
  79. // 0:1 0:0 1:1
  80. // 0:0 1:1 0:0
  81. // 0:0 1:1 0:0
  82. //// Use StringBuilder since output only has .WriteLine
  83. //var sb = new StringBuilder ();
  84. //// for each line in `contents`
  85. //for (var r = 0; r < driver.Rows; r++)
  86. //{
  87. // // for each column in `contents`
  88. // for (var cc = 0; cc < driver.Cols; cc++)
  89. // {
  90. // // get the attribute at the current location
  91. // Attribute? val2 = contents [r, cc].Attribute;
  92. // // if the attribute is not null
  93. // if (val2.HasValue)
  94. // {
  95. // // get the index of the attribute in `expectedAttributes`
  96. // int index = Array.IndexOf (expectedAttributes, val2.Value);
  97. // // if the index is -1, it means the attribute was not found in `expectedAttributes`
  98. // // get the index of the actual attribute in `expectedAttributes`
  99. // if (index == -1)
  100. // {
  101. // sb.Append ("x:x ");
  102. // }
  103. // else
  104. // {
  105. // sb.Append ($"{index}:{val2.Value} ");
  106. // }
  107. // }
  108. // else
  109. // {
  110. // sb.Append ("x:x ");
  111. // }
  112. // }
  113. // sb.AppendLine ();
  114. //}
  115. //output.WriteLine ($"Contents:\n{sb}");
  116. Assert.Equal (userExpected, colorUsed);
  117. return;
  118. }
  119. }
  120. line++;
  121. }
  122. }
  123. #pragma warning disable xUnit1013 // Public method should be marked as test
  124. /// <summary>Asserts that the driver contents match the expected contents, optionally ignoring any trailing whitespace.</summary>
  125. /// <param name="expectedLook"></param>
  126. /// <param name="output"></param>
  127. /// <param name="driver">The IDriver to use. If null <see cref="Application.Driver"/> will be used.</param>
  128. /// <param name="ignoreLeadingWhitespace"></param>
  129. public static void AssertDriverContentsAre (
  130. string expectedLook,
  131. ITestOutputHelper output,
  132. IDriver? driver = null,
  133. bool ignoreLeadingWhitespace = false
  134. )
  135. {
  136. #pragma warning restore xUnit1013 // Public method should be marked as test
  137. if (driver is null && ApplicationImpl.ModelUsage == ApplicationModelUsage.LegacyStatic)
  138. {
  139. driver = Application.Driver;
  140. }
  141. ArgumentNullException.ThrowIfNull (driver);
  142. var actualLook = driver.ToString ();
  143. if (string.Equals (expectedLook, actualLook))
  144. {
  145. return;
  146. }
  147. // get rid of trailing whitespace on each line (and leading/trailing whitespace of start/end of full string)
  148. expectedLook = TrailingWhiteSpaceRegEx ().Replace (expectedLook, "").Trim ();
  149. actualLook = TrailingWhiteSpaceRegEx ().Replace (actualLook, "").Trim ();
  150. if (ignoreLeadingWhitespace)
  151. {
  152. expectedLook = LeadingWhitespaceRegEx ().Replace (expectedLook, "").Trim ();
  153. actualLook = LeadingWhitespaceRegEx ().Replace (actualLook, "").Trim ();
  154. }
  155. // standardize line endings for the comparison
  156. expectedLook = expectedLook.Replace ("\r\n", "\n");
  157. actualLook = actualLook.Replace ("\r\n", "\n");
  158. // If test is about to fail show user what things looked like
  159. if (!string.Equals (expectedLook, actualLook))
  160. {
  161. output?.WriteLine ("Expected:" + Environment.NewLine + expectedLook);
  162. output?.WriteLine (" But Was:" + Environment.NewLine + actualLook);
  163. }
  164. Assert.Equal (expectedLook, actualLook);
  165. }
  166. /// <summary>
  167. /// Asserts that the driver contents are equal to the provided string.
  168. /// </summary>
  169. /// <param name="expectedLook"></param>
  170. /// <param name="output"></param>
  171. /// <param name="driver">The IDriver to use. If null <see cref="Application.Driver"/> will be used.</param>
  172. /// <returns></returns>
  173. public static Rectangle AssertDriverContentsWithFrameAre (
  174. string expectedLook,
  175. ITestOutputHelper output,
  176. IDriver? driver = null
  177. )
  178. {
  179. List<List<string>> lines = [];
  180. var sb = new StringBuilder ();
  181. if (driver is null && ApplicationImpl.ModelUsage == ApplicationModelUsage.LegacyStatic)
  182. {
  183. driver = Application.Driver;
  184. }
  185. ArgumentNullException.ThrowIfNull (driver);
  186. int x = -1;
  187. int y = -1;
  188. int w = -1;
  189. int h = -1;
  190. Cell [,] contents = driver!.Contents!;
  191. for (var rowIndex = 0; rowIndex < driver.Rows; rowIndex++)
  192. {
  193. List<string> strings = [];
  194. for (var colIndex = 0; colIndex < driver.Cols; colIndex++)
  195. {
  196. string textAtCurrentLocation = contents! [rowIndex, colIndex].Grapheme;
  197. if (textAtCurrentLocation != _spaceRune.ToString ())
  198. {
  199. if (x == -1)
  200. {
  201. x = colIndex;
  202. y = rowIndex;
  203. for (var i = 0; i < colIndex; i++)
  204. {
  205. strings.InsertRange (i, [_spaceRune.ToString ()]);
  206. }
  207. }
  208. if (textAtCurrentLocation.GetColumns () > 1)
  209. {
  210. colIndex++;
  211. }
  212. if (colIndex + 1 > w)
  213. {
  214. w = colIndex + 1;
  215. }
  216. h = rowIndex - y + 1;
  217. }
  218. if (x > -1)
  219. {
  220. strings.Add (textAtCurrentLocation);
  221. }
  222. }
  223. if (strings.Count > 0)
  224. {
  225. lines.Add (strings);
  226. }
  227. }
  228. // Remove unnecessary empty lines
  229. if (lines.Count > 0)
  230. {
  231. for (int r = lines.Count - 1; r > h - 1; r--)
  232. {
  233. lines.RemoveAt (r);
  234. }
  235. }
  236. // Remove trailing whitespace on each line
  237. foreach (List<string> row in lines)
  238. {
  239. for (int c = row.Count - 1; c >= 0; c--)
  240. {
  241. string text = row [c];
  242. if (text != " " || row.Sum (x => x.GetColumns ()) == w)
  243. {
  244. break;
  245. }
  246. row.RemoveAt (c);
  247. }
  248. }
  249. // Convert Text list to string
  250. for (var r = 0; r < lines.Count; r++)
  251. {
  252. var line = StringExtensions.ToString (lines [r]);
  253. if (r == lines.Count - 1)
  254. {
  255. sb.Append (line);
  256. }
  257. else
  258. {
  259. sb.AppendLine (line);
  260. }
  261. }
  262. var actualLook = sb.ToString ();
  263. if (string.Equals (expectedLook, actualLook))
  264. {
  265. return new (x > -1 ? x : 0, y > -1 ? y : 0, w > -1 ? w : 0, h > -1 ? h : 0);
  266. }
  267. // standardize line endings for the comparison
  268. expectedLook = expectedLook.ReplaceLineEndings ();
  269. actualLook = actualLook.ReplaceLineEndings ();
  270. // Remove the first and the last line ending from the expectedLook
  271. if (expectedLook.StartsWith (Environment.NewLine))
  272. {
  273. expectedLook = expectedLook [Environment.NewLine.Length..];
  274. }
  275. if (expectedLook.EndsWith (Environment.NewLine))
  276. {
  277. expectedLook = expectedLook [..^Environment.NewLine.Length];
  278. }
  279. // If test is about to fail show user what things looked like
  280. if (!string.Equals (expectedLook, actualLook))
  281. {
  282. output?.WriteLine ("Expected:" + Environment.NewLine + expectedLook);
  283. output?.WriteLine (" But Was:" + Environment.NewLine + actualLook);
  284. }
  285. Assert.Equal (expectedLook, actualLook);
  286. return new (x > -1 ? x : 0, y > -1 ? y : 0, w > -1 ? w : 0, h > -1 ? h : 0);
  287. }
  288. /// <summary>
  289. /// Verifies the console used all the <paramref name="expectedColors"/> when rendering. If one or more of the
  290. /// expected colors are not used then the failure will output both the colors that were found to be used and which of
  291. /// your expectations was not met.
  292. /// </summary>
  293. /// <param name="driver">if null uses <see cref="Application.Driver"/></param>
  294. /// <param name="expectedColors"></param>
  295. internal static void AssertDriverUsedColors (IDriver? driver = null, params Attribute [] expectedColors)
  296. {
  297. if (driver is null && ApplicationImpl.ModelUsage == ApplicationModelUsage.LegacyStatic)
  298. {
  299. driver = Application.Driver;
  300. }
  301. ArgumentNullException.ThrowIfNull (driver); Cell [,] contents = driver?.Contents!;
  302. List<Attribute> toFind = expectedColors.ToList ();
  303. // Contents 3rd column is an Attribute
  304. HashSet<Attribute> colorsUsed = new ();
  305. for (var r = 0; r < driver!.Rows; r++)
  306. {
  307. for (var c = 0; c < driver.Cols; c++)
  308. {
  309. Attribute? val = contents [r, c].Attribute;
  310. if (val.HasValue)
  311. {
  312. colorsUsed.Add (val.Value);
  313. Attribute match = toFind.FirstOrDefault (e => e == val);
  314. // need to check twice because Attribute is a struct and therefore cannot be null
  315. if (toFind.Any (e => e == val))
  316. {
  317. toFind.Remove (match);
  318. }
  319. }
  320. }
  321. }
  322. if (!toFind.Any ())
  323. {
  324. return;
  325. }
  326. var sb = new StringBuilder ();
  327. sb.AppendLine ("The following colors were not used:" + string.Join ("; ", toFind.Select (a => a.ToString ())));
  328. sb.AppendLine ("Colors used were:" + string.Join ("; ", colorsUsed.Select (a => a.ToString ())));
  329. throw new (sb.ToString ());
  330. }
  331. [GeneratedRegex ("^\\s+", RegexOptions.Multiline)]
  332. private static partial Regex LeadingWhitespaceRegEx ();
  333. [GeneratedRegex ("\\s+$", RegexOptions.Multiline)]
  334. private static partial Regex TrailingWhiteSpaceRegEx ();
  335. }