DriverAssert.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  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. #pragma warning disable xUnit1013 // Public method should be marked as test
  167. /// <summary>Asserts that the driver raw ANSI output matches the expected output.</summary>
  168. /// <param name="expectedLook">Expected output with C# escape sequences (e.g., \x1b for ESC)</param>
  169. /// <param name="output"></param>
  170. /// <param name="driver">The IDriver to use. If null <see cref="Application.Driver"/> will be used.</param>
  171. public static void AssertDriverOutputIs (
  172. string expectedLook,
  173. ITestOutputHelper output,
  174. IDriver? driver = null
  175. )
  176. {
  177. #pragma warning restore xUnit1013 // Public method should be marked as test
  178. if (driver is null && ApplicationImpl.ModelUsage == ApplicationModelUsage.LegacyStatic)
  179. {
  180. driver = Application.Driver;
  181. }
  182. ArgumentNullException.ThrowIfNull (driver);
  183. string? actualLook = driver.GetOutput().GetLastOutput ();
  184. // Unescape the expected string to convert C# escape sequences like \x1b to actual characters
  185. string unescapedExpected = UnescapeString (expectedLook);
  186. // Trim trailing whitespace from actual (screen padding)
  187. actualLook = actualLook.TrimEnd ();
  188. unescapedExpected = unescapedExpected.TrimEnd ();
  189. if (string.Equals (unescapedExpected, actualLook))
  190. {
  191. return;
  192. }
  193. // If test is about to fail show user what things looked like
  194. if (!string.Equals (unescapedExpected, actualLook))
  195. {
  196. output?.WriteLine ($"Expected (length={unescapedExpected.Length}):" + Environment.NewLine + unescapedExpected);
  197. output?.WriteLine ($" But Was (length={actualLook.Length}):" + Environment.NewLine + actualLook);
  198. // Show the difference at the end
  199. int minLen = Math.Min (unescapedExpected.Length, actualLook.Length);
  200. output?.WriteLine ($"Lengths: Expected={unescapedExpected.Length}, Actual={actualLook.Length}, MinLen={minLen}");
  201. if (actualLook.Length > unescapedExpected.Length)
  202. {
  203. output?.WriteLine ($"Actual has {actualLook.Length - unescapedExpected.Length} extra characters at the end");
  204. }
  205. }
  206. Assert.Equal (unescapedExpected, actualLook);
  207. }
  208. /// <summary>
  209. /// Unescapes a C# string literal by processing escape sequences like \x1b, \n, \r, \t, etc.
  210. /// </summary>
  211. /// <param name="input">String with C# escape sequences</param>
  212. /// <returns>String with escape sequences converted to actual characters</returns>
  213. private static string UnescapeString (string input)
  214. {
  215. if (string.IsNullOrEmpty (input))
  216. {
  217. return input;
  218. }
  219. var result = new StringBuilder (input.Length);
  220. int i = 0;
  221. while (i < input.Length)
  222. {
  223. if (input [i] == '\\' && i + 1 < input.Length)
  224. {
  225. char next = input [i + 1];
  226. switch (next)
  227. {
  228. case 'x' when i + 3 < input.Length:
  229. // Handle \xHH (2-digit hex)
  230. string hex = input.Substring (i + 2, 2);
  231. if (int.TryParse (hex, System.Globalization.NumberStyles.HexNumber, null, out int hexValue))
  232. {
  233. result.Append ((char)hexValue);
  234. i += 4; // Skip \xHH
  235. continue;
  236. }
  237. break;
  238. case 'n':
  239. result.Append ('\n');
  240. i += 2;
  241. continue;
  242. case 'r':
  243. result.Append ('\r');
  244. i += 2;
  245. continue;
  246. case 't':
  247. result.Append ('\t');
  248. i += 2;
  249. continue;
  250. case '\\':
  251. result.Append ('\\');
  252. i += 2;
  253. continue;
  254. case '"':
  255. result.Append ('"');
  256. i += 2;
  257. continue;
  258. case '\'':
  259. result.Append ('\'');
  260. i += 2;
  261. continue;
  262. case '0':
  263. result.Append ('\0');
  264. i += 2;
  265. continue;
  266. }
  267. }
  268. // Not an escape sequence, add the character as-is
  269. result.Append (input [i]);
  270. i++;
  271. }
  272. return result.ToString ();
  273. }
  274. /// <summary>
  275. /// Asserts that the driver contents are equal to the provided string.
  276. /// </summary>
  277. /// <param name="expectedLook"></param>
  278. /// <param name="output"></param>
  279. /// <param name="driver">The IDriver to use. If null <see cref="Application.Driver"/> will be used.</param>
  280. /// <returns></returns>
  281. public static Rectangle AssertDriverContentsWithFrameAre (
  282. string expectedLook,
  283. ITestOutputHelper output,
  284. IDriver? driver = null
  285. )
  286. {
  287. List<List<string>> lines = [];
  288. var sb = new StringBuilder ();
  289. if (driver is null && ApplicationImpl.ModelUsage == ApplicationModelUsage.LegacyStatic)
  290. {
  291. driver = Application.Driver;
  292. }
  293. ArgumentNullException.ThrowIfNull (driver);
  294. int x = -1;
  295. int y = -1;
  296. int w = -1;
  297. int h = -1;
  298. Cell [,] contents = driver!.Contents!;
  299. for (var rowIndex = 0; rowIndex < driver.Rows; rowIndex++)
  300. {
  301. List<string> strings = [];
  302. for (var colIndex = 0; colIndex < driver.Cols; colIndex++)
  303. {
  304. string textAtCurrentLocation = contents! [rowIndex, colIndex].Grapheme;
  305. if (textAtCurrentLocation != _spaceRune.ToString ())
  306. {
  307. if (x == -1)
  308. {
  309. x = colIndex;
  310. y = rowIndex;
  311. for (var i = 0; i < colIndex; i++)
  312. {
  313. strings.InsertRange (i, [_spaceRune.ToString ()]);
  314. }
  315. }
  316. if (textAtCurrentLocation.GetColumns () > 1)
  317. {
  318. colIndex++;
  319. }
  320. if (colIndex + 1 > w)
  321. {
  322. w = colIndex + 1;
  323. }
  324. h = rowIndex - y + 1;
  325. }
  326. if (x > -1)
  327. {
  328. strings.Add (textAtCurrentLocation);
  329. }
  330. }
  331. if (strings.Count > 0)
  332. {
  333. lines.Add (strings);
  334. }
  335. }
  336. // Remove unnecessary empty lines
  337. if (lines.Count > 0)
  338. {
  339. for (int r = lines.Count - 1; r > h - 1; r--)
  340. {
  341. lines.RemoveAt (r);
  342. }
  343. }
  344. // Remove trailing whitespace on each line
  345. foreach (List<string> row in lines)
  346. {
  347. for (int c = row.Count - 1; c >= 0; c--)
  348. {
  349. string text = row [c];
  350. if (text != " " || row.Sum (x => x.GetColumns ()) == w)
  351. {
  352. break;
  353. }
  354. row.RemoveAt (c);
  355. }
  356. }
  357. // Convert Text list to string
  358. for (var r = 0; r < lines.Count; r++)
  359. {
  360. var line = StringExtensions.ToString (lines [r]);
  361. if (r == lines.Count - 1)
  362. {
  363. sb.Append (line);
  364. }
  365. else
  366. {
  367. sb.AppendLine (line);
  368. }
  369. }
  370. var actualLook = sb.ToString ();
  371. if (string.Equals (expectedLook, actualLook))
  372. {
  373. return new (x > -1 ? x : 0, y > -1 ? y : 0, w > -1 ? w : 0, h > -1 ? h : 0);
  374. }
  375. // standardize line endings for the comparison
  376. expectedLook = expectedLook.ReplaceLineEndings ();
  377. actualLook = actualLook.ReplaceLineEndings ();
  378. // Remove the first and the last line ending from the expectedLook
  379. if (expectedLook.StartsWith (Environment.NewLine))
  380. {
  381. expectedLook = expectedLook [Environment.NewLine.Length..];
  382. }
  383. if (expectedLook.EndsWith (Environment.NewLine))
  384. {
  385. expectedLook = expectedLook [..^Environment.NewLine.Length];
  386. }
  387. // If test is about to fail show user what things looked like
  388. if (!string.Equals (expectedLook, actualLook))
  389. {
  390. output?.WriteLine ("Expected:" + Environment.NewLine + expectedLook);
  391. output?.WriteLine (" But Was:" + Environment.NewLine + actualLook);
  392. }
  393. Assert.Equal (expectedLook, actualLook);
  394. return new (x > -1 ? x : 0, y > -1 ? y : 0, w > -1 ? w : 0, h > -1 ? h : 0);
  395. }
  396. /// <summary>
  397. /// Verifies the console used all the <paramref name="expectedColors"/> when rendering. If one or more of the
  398. /// expected colors are not used then the failure will output both the colors that were found to be used and which of
  399. /// your expectations was not met.
  400. /// </summary>
  401. /// <param name="driver">if null uses <see cref="Application.Driver"/></param>
  402. /// <param name="expectedColors"></param>
  403. internal static void AssertDriverUsedColors (IDriver? driver = null, params Attribute [] expectedColors)
  404. {
  405. if (driver is null && ApplicationImpl.ModelUsage == ApplicationModelUsage.LegacyStatic)
  406. {
  407. driver = Application.Driver;
  408. }
  409. ArgumentNullException.ThrowIfNull (driver); Cell [,] contents = driver?.Contents!;
  410. List<Attribute> toFind = expectedColors.ToList ();
  411. // Contents 3rd column is an Attribute
  412. HashSet<Attribute> colorsUsed = new ();
  413. for (var r = 0; r < driver!.Rows; r++)
  414. {
  415. for (var c = 0; c < driver.Cols; c++)
  416. {
  417. Attribute? val = contents [r, c].Attribute;
  418. if (val.HasValue)
  419. {
  420. colorsUsed.Add (val.Value);
  421. Attribute match = toFind.FirstOrDefault (e => e == val);
  422. // need to check twice because Attribute is a struct and therefore cannot be null
  423. if (toFind.Any (e => e == val))
  424. {
  425. toFind.Remove (match);
  426. }
  427. }
  428. }
  429. }
  430. if (!toFind.Any ())
  431. {
  432. return;
  433. }
  434. var sb = new StringBuilder ();
  435. sb.AppendLine ("The following colors were not used:" + string.Join ("; ", toFind.Select (a => a.ToString ())));
  436. sb.AppendLine ("Colors used were:" + string.Join ("; ", colorsUsed.Select (a => a.ToString ())));
  437. throw new (sb.ToString ());
  438. }
  439. [GeneratedRegex ("^\\s+", RegexOptions.Multiline)]
  440. private static partial Regex LeadingWhitespaceRegEx ();
  441. [GeneratedRegex ("\\s+$", RegexOptions.Multiline)]
  442. private static partial Regex TrailingWhiteSpaceRegEx ();
  443. }