AnsiResponseParserTests.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. using System.CommandLine.Parsing;
  2. using System.Diagnostics;
  3. using System.Text;
  4. using Xunit.Abstractions;
  5. namespace UnitTests.ConsoleDrivers;
  6. public class AnsiResponseParserTests (ITestOutputHelper output)
  7. {
  8. AnsiResponseParser<int> _parser1 = new AnsiResponseParser<int> ();
  9. AnsiResponseParser _parser2 = new AnsiResponseParser ();
  10. /// <summary>
  11. /// Used for the T value in batches that are passed to the AnsiResponseParser&lt;int&gt; (parser1)
  12. /// </summary>
  13. private int tIndex = 0;
  14. [Fact]
  15. public void TestInputProcessing ()
  16. {
  17. string ansiStream = "\u001b[<0;10;20M" + // ANSI escape for mouse move at (10, 20)
  18. "Hello" + // User types "Hello"
  19. "\u001b[0c"; // Device Attributes response (e.g., terminal identification i.e. DAR)
  20. string? response1 = null;
  21. string? response2 = null;
  22. int i = 0;
  23. // Imagine that we are expecting a DAR
  24. _parser1.ExpectResponse ("c",(s)=> response1 = s);
  25. _parser2.ExpectResponse ("c", (s) => response2 = s);
  26. // First char is Escape which we must consume incase what follows is the DAR
  27. AssertConsumed (ansiStream, ref i); // Esc
  28. for (int c = 0; c < "[<0;10;20".Length; c++)
  29. {
  30. AssertConsumed (ansiStream, ref i);
  31. }
  32. // We see the M terminator
  33. AssertReleased (ansiStream, ref i, "\u001b[<0;10;20M");
  34. // Regular user typing
  35. for (int c = 0; c < "Hello".Length; c++)
  36. {
  37. AssertIgnored (ansiStream,"Hello"[c], ref i);
  38. }
  39. // Now we have entered the actual DAR we should be consuming these
  40. for (int c = 0; c < "\u001b[0".Length; c++)
  41. {
  42. AssertConsumed (ansiStream, ref i);
  43. }
  44. // Consume the terminator 'c' and expect this to call the above event
  45. Assert.Null (response1);
  46. Assert.Null (response1);
  47. AssertConsumed (ansiStream, ref i);
  48. Assert.NotNull (response2);
  49. Assert.Equal ("\u001b[0c", response2);
  50. Assert.NotNull (response2);
  51. Assert.Equal ("\u001b[0c", response2);
  52. }
  53. [Theory]
  54. [InlineData ("\u001b[<0;10;20MHi\u001b[0c", "c", "\u001b[0c", "\u001b[<0;10;20MHi")]
  55. [InlineData ("\u001b[<1;15;25MYou\u001b[1c", "c", "\u001b[1c", "\u001b[<1;15;25MYou")]
  56. [InlineData ("\u001b[0cHi\u001b[0c", "c", "\u001b[0c", "Hi\u001b[0c")]
  57. [InlineData ("\u001b[<0;0;0MHe\u001b[3c", "c", "\u001b[3c", "\u001b[<0;0;0MHe")]
  58. [InlineData ("\u001b[<0;1;2Da\u001b[0c\u001b[1c", "c", "\u001b[0c", "\u001b[<0;1;2Da\u001b[1c")]
  59. [InlineData ("\u001b[1;1M\u001b[3cAn", "c", "\u001b[3c", "\u001b[1;1MAn")]
  60. [InlineData ("hi\u001b[2c\u001b[<5;5;5m", "c", "\u001b[2c", "hi\u001b[<5;5;5m")]
  61. [InlineData ("\u001b[3c\u001b[4c\u001b[<0;0;0MIn", "c", "\u001b[3c", "\u001b[4c\u001b[<0;0;0MIn")]
  62. [InlineData ("\u001b[<1;2;3M\u001b[0c\u001b[<1;2;3M\u001b[2c", "c", "\u001b[0c", "\u001b[<1;2;3M\u001b[<1;2;3M\u001b[2c")]
  63. [InlineData ("\u001b[<0;1;1MHi\u001b[6c\u001b[2c\u001b[<1;0;0MT", "c", "\u001b[6c", "\u001b[<0;1;1MHi\u001b[2c\u001b[<1;0;0MT")]
  64. [InlineData ("Te\u001b[<2;2;2M\u001b[7c", "c", "\u001b[7c", "Te\u001b[<2;2;2M")]
  65. [InlineData ("\u001b[0c\u001b[<0;0;0M\u001b[3c\u001b[0c\u001b[1;0MT", "c", "\u001b[0c", "\u001b[<0;0;0M\u001b[3c\u001b[0c\u001b[1;0MT")]
  66. [InlineData ("\u001b[0;0M\u001b[<0;0;0M\u001b[3cT\u001b[1c", "c", "\u001b[3c", "\u001b[0;0M\u001b[<0;0;0MT\u001b[1c")]
  67. [InlineData ("\u001b[3c\u001b[<0;0;0M\u001b[0c\u001b[<1;1;1MIn\u001b[1c", "c", "\u001b[3c", "\u001b[<0;0;0M\u001b[0c\u001b[<1;1;1MIn\u001b[1c")]
  68. [InlineData ("\u001b[<5;5;5M\u001b[7cEx\u001b[8c", "c", "\u001b[7c", "\u001b[<5;5;5MEx\u001b[8c")]
  69. // Random characters and mixed inputs
  70. [InlineData ("\u001b[<1;1;1MJJ\u001b[9c", "c", "\u001b[9c", "\u001b[<1;1;1MJJ")] // Mixed text
  71. [InlineData ("Be\u001b[0cAf", "c", "\u001b[0c", "BeAf")] // Escape in the middle of the string
  72. [InlineData ("\u001b[<0;0;0M\u001b[2cNot e", "c", "\u001b[2c", "\u001b[<0;0;0MNot e")] // Unexpected sequence followed by text
  73. [InlineData ("Just te\u001b[<0;0;0M\u001b[3c\u001b[2c\u001b[4c", "c", "\u001b[3c", "Just te\u001b[<0;0;0M\u001b[2c\u001b[4c")] // Multiple unexpected responses
  74. [InlineData ("\u001b[1;2;3M\u001b[0c\u001b[2;2M\u001b[0;0;0MTe", "c", "\u001b[0c", "\u001b[1;2;3M\u001b[2;2M\u001b[0;0;0MTe")] // Multiple commands with responses
  75. [InlineData ("\u001b[<3;3;3Mabc\u001b[4cde", "c", "\u001b[4c", "\u001b[<3;3;3Mabcde")] // Escape sequences mixed with regular text
  76. // Edge cases
  77. [InlineData ("\u001b[0c\u001b[0c\u001b[0c", "c", "\u001b[0c", "\u001b[0c\u001b[0c")] // Multiple identical responses
  78. [InlineData ("", "c", "", "")] // Empty input
  79. [InlineData ("Normal", "c", "", "Normal")] // No escape sequences
  80. [InlineData ("\u001b[<0;0;0M", "c", "", "\u001b[<0;0;0M")] // Escape sequence only
  81. [InlineData ("\u001b[1;2;3M\u001b[0c", "c", "\u001b[0c", "\u001b[1;2;3M")] // Last response consumed
  82. [InlineData ("Inpu\u001b[0c\u001b[1;0;0M", "c", "\u001b[0c", "Inpu\u001b[1;0;0M")] // Single input followed by escape
  83. [InlineData ("\u001b[2c\u001b[<5;6;7MDa", "c", "\u001b[2c", "\u001b[<5;6;7MDa")] // Multiple escape sequences followed by text
  84. [InlineData ("\u001b[0cHi\u001b[1cGo", "c", "\u001b[0c", "Hi\u001b[1cGo")] // Normal text with multiple escape sequences
  85. [InlineData ("\u001b[<1;1;1MTe", "c", "", "\u001b[<1;1;1MTe")]
  86. // Add more test cases here...
  87. public void TestInputSequences (string ansiStream, string expectedTerminator, string expectedResponse, string expectedOutput)
  88. {
  89. var swGenBatches = Stopwatch.StartNew ();
  90. int tests = 0;
  91. var permutations = GetBatchPermutations (ansiStream,5).ToArray ();
  92. swGenBatches.Stop ();
  93. var swRunTest = Stopwatch.StartNew ();
  94. foreach (var batchSet in permutations)
  95. {
  96. tIndex = 0;
  97. string response1 = string.Empty;
  98. string response2 = string.Empty;
  99. // Register the expected response with the given terminator
  100. _parser1.ExpectResponse (expectedTerminator, s => response1 = s);
  101. _parser2.ExpectResponse (expectedTerminator, s => response2 = s);
  102. // Process the input
  103. StringBuilder actualOutput1 = new StringBuilder ();
  104. StringBuilder actualOutput2 = new StringBuilder ();
  105. foreach (var batch in batchSet)
  106. {
  107. var output1 = _parser1.ProcessInput (StringToBatch (batch));
  108. actualOutput1.Append (BatchToString (output1));
  109. var output2 = _parser2.ProcessInput (batch);
  110. actualOutput2.Append (output2);
  111. }
  112. // Assert the final output minus the expected response
  113. Assert.Equal (expectedOutput, actualOutput1.ToString());
  114. Assert.Equal (expectedResponse, response1);
  115. Assert.Equal (expectedOutput, actualOutput2.ToString ());
  116. Assert.Equal (expectedResponse, response2);
  117. tests++;
  118. }
  119. output.WriteLine ($"Tested {tests} in {swRunTest.ElapsedMilliseconds} ms (gen batches took {swGenBatches.ElapsedMilliseconds} ms)" );
  120. }
  121. public static IEnumerable<object []> TestInputSequencesExact_Cases ()
  122. {
  123. yield return
  124. [
  125. "Esc Only",
  126. null,
  127. new []
  128. {
  129. new StepExpectation ('\u001b',AnsiResponseParserState.ExpectingBracket,string.Empty)
  130. }
  131. ];
  132. yield return
  133. [
  134. "Esc Hi with intermediate",
  135. 'c',
  136. new []
  137. {
  138. new StepExpectation ('\u001b',AnsiResponseParserState.ExpectingBracket,string.Empty),
  139. new StepExpectation ('H',AnsiResponseParserState.Normal,"\u001bH"), // H is known terminator and not expected one so here we release both chars
  140. new StepExpectation ('\u001b',AnsiResponseParserState.ExpectingBracket,string.Empty),
  141. new StepExpectation ('[',AnsiResponseParserState.InResponse,string.Empty),
  142. new StepExpectation ('0',AnsiResponseParserState.InResponse,string.Empty),
  143. new StepExpectation ('c',AnsiResponseParserState.Normal,string.Empty,"\u001b[0c"), // c is expected terminator so here we swallow input and populate expected response
  144. new StepExpectation ('\u001b',AnsiResponseParserState.ExpectingBracket,string.Empty),
  145. }
  146. ];
  147. }
  148. public class StepExpectation ()
  149. {
  150. /// <summary>
  151. /// The input character to feed into the parser at this step of the test
  152. /// </summary>
  153. public char Input { get; }
  154. /// <summary>
  155. /// What should the state of the parser be after the <see cref="Input"/>
  156. /// is fed in.
  157. /// </summary>
  158. public AnsiResponseParserState ExpectedStateAfterOperation { get; }
  159. /// <summary>
  160. /// If this step should release one or more characters, put them here.
  161. /// </summary>
  162. public string ExpectedRelease { get; } = string.Empty;
  163. /// <summary>
  164. /// If this step should result in a completing of detection of ANSI response
  165. /// then put the expected full response sequence here.
  166. /// </summary>
  167. public string ExpectedAnsiResponse { get; } = string.Empty;
  168. public StepExpectation (
  169. char input,
  170. AnsiResponseParserState expectedStateAfterOperation,
  171. string expectedRelease = "",
  172. string expectedAnsiResponse = "") : this ()
  173. {
  174. Input = input;
  175. ExpectedStateAfterOperation = expectedStateAfterOperation;
  176. ExpectedRelease = expectedRelease;
  177. ExpectedAnsiResponse = expectedAnsiResponse;
  178. }
  179. }
  180. [MemberData(nameof(TestInputSequencesExact_Cases))]
  181. [Theory]
  182. public void TestInputSequencesExact (string caseName, char? terminator, IEnumerable<StepExpectation> expectedStates)
  183. {
  184. output.WriteLine ("Running test case:" + caseName);
  185. var parser = new AnsiResponseParser ();
  186. string? response = null;
  187. if (terminator.HasValue)
  188. {
  189. parser.ExpectResponse (terminator.Value.ToString (),(s)=> response = s);
  190. }
  191. foreach (var state in expectedStates)
  192. {
  193. // If we expect the response to be detected at this step
  194. if (!string.IsNullOrWhiteSpace (state.ExpectedAnsiResponse))
  195. {
  196. // Then before passing input it should be null
  197. Assert.Null (response);
  198. }
  199. var actual = parser.ProcessInput (state.Input.ToString ());
  200. Assert.Equal (state.ExpectedRelease,actual);
  201. Assert.Equal (state.ExpectedStateAfterOperation, parser.State);
  202. // If we expect the response to be detected at this step
  203. if (!string.IsNullOrWhiteSpace (state.ExpectedAnsiResponse))
  204. {
  205. // And after passing input it shuld be the expected value
  206. Assert.Equal (state.ExpectedAnsiResponse, response);
  207. }
  208. }
  209. }
  210. [Fact]
  211. public void ReleasesEscapeAfterTimeout ()
  212. {
  213. string input = "\u001b";
  214. int i = 0;
  215. // Esc on its own looks like it might be an esc sequence so should be consumed
  216. AssertConsumed (input,ref i);
  217. // We should know when the state changed
  218. Assert.Equal (AnsiResponseParserState.ExpectingBracket, _parser1.State);
  219. Assert.Equal (AnsiResponseParserState.ExpectingBracket, _parser2.State);
  220. Assert.Equal (DateTime.Now.Date, _parser1.StateChangedAt.Date);
  221. Assert.Equal (DateTime.Now.Date, _parser2.StateChangedAt.Date);
  222. AssertManualReleaseIs (input);
  223. }
  224. [Fact]
  225. public void TwoExcapesInARow ()
  226. {
  227. // Example user presses Esc key then a DAR comes in
  228. string input = "\u001b\u001b";
  229. int i = 0;
  230. // First Esc gets grabbed
  231. AssertConsumed (input, ref i);
  232. // Upon getting the second Esc we should release the first
  233. AssertReleased (input, ref i, "\u001b",0);
  234. // Assume 50ms or something has passed, lets force release as no new content
  235. // It should be the second escape that gets released (i.e. index 1)
  236. AssertManualReleaseIs ("\u001b",1);
  237. }
  238. [Fact]
  239. public void TwoExcapesInARowWithTextBetween ()
  240. {
  241. // Example user presses Esc key and types at the speed of light (normally the consumer should be handling Esc timeout)
  242. // then a DAR comes in.
  243. string input = "\u001bfish\u001b";
  244. int i = 0;
  245. // First Esc gets grabbed
  246. AssertConsumed (input, ref i); // Esc
  247. Assert.Equal (AnsiResponseParserState.ExpectingBracket,_parser1.State);
  248. Assert.Equal (AnsiResponseParserState.ExpectingBracket, _parser2.State);
  249. // Because next char is 'f' we do not see a bracket so release both
  250. AssertReleased (input, ref i, "\u001bf", 0,1); // f
  251. Assert.Equal (AnsiResponseParserState.Normal, _parser1.State);
  252. Assert.Equal (AnsiResponseParserState.Normal, _parser2.State);
  253. AssertReleased (input, ref i,"i",2);
  254. AssertReleased (input, ref i, "s", 3);
  255. AssertReleased (input, ref i, "h", 4);
  256. AssertConsumed (input, ref i); // Second Esc
  257. // Assume 50ms or something has passed, lets force release as no new content
  258. AssertManualReleaseIs ("\u001b", 5);
  259. }
  260. private Tuple<char, int> [] StringToBatch (string batch)
  261. {
  262. return batch.Select ((k) => Tuple.Create (k, tIndex++)).ToArray ();
  263. }
  264. public static IEnumerable<string []> GetBatchPermutations (string input, int maxDepth = 3)
  265. {
  266. // Call the recursive method to generate batches with an initial depth of 0
  267. return GenerateBatches (input, 0, maxDepth, 0);
  268. }
  269. private static IEnumerable<string []> GenerateBatches (string input, int start, int maxDepth, int currentDepth)
  270. {
  271. // If we have reached the maximum recursion depth, return no results
  272. if (currentDepth >= maxDepth)
  273. {
  274. yield break; // No more batches can be generated at this depth
  275. }
  276. // If we have reached the end of the string, return an empty list
  277. if (start >= input.Length)
  278. {
  279. yield return new string [0];
  280. yield break;
  281. }
  282. // Iterate over the input string to create batches
  283. for (int i = start + 1; i <= input.Length; i++)
  284. {
  285. // Take a batch from 'start' to 'i'
  286. string batch = input.Substring (start, i - start);
  287. // Recursively get batches from the remaining substring, increasing the depth
  288. foreach (var remainingBatches in GenerateBatches (input, i, maxDepth, currentDepth + 1))
  289. {
  290. // Combine the current batch with the remaining batches
  291. var result = new string [1 + remainingBatches.Length];
  292. result [0] = batch;
  293. Array.Copy (remainingBatches, 0, result, 1, remainingBatches.Length);
  294. yield return result;
  295. }
  296. }
  297. }
  298. private void AssertIgnored (string ansiStream,char expected, ref int i)
  299. {
  300. var c2 = ansiStream [i];
  301. var c1 = NextChar (ansiStream, ref i);
  302. // Parser does not grab this key (i.e. driver can continue with regular operations)
  303. Assert.Equal ( c1,_parser1.ProcessInput (c1));
  304. Assert.Equal (expected,c1.Single().Item1);
  305. Assert.Equal (c2, _parser2.ProcessInput (c2.ToString()).Single());
  306. Assert.Equal (expected, c2 );
  307. }
  308. private void AssertConsumed (string ansiStream, ref int i)
  309. {
  310. // Parser grabs this key
  311. var c2 = ansiStream [i];
  312. var c1 = NextChar (ansiStream, ref i);
  313. Assert.Empty (_parser1.ProcessInput(c1));
  314. Assert.Empty (_parser2.ProcessInput (c2.ToString()));
  315. }
  316. private void AssertReleased (string ansiStream, ref int i, string expectedRelease, params int[] expectedTValues)
  317. {
  318. var c2 = ansiStream [i];
  319. var c1 = NextChar (ansiStream, ref i);
  320. // Parser realizes it has grabbed content that does not belong to an outstanding request
  321. // Parser returns false to indicate to continue
  322. var released1 = _parser1.ProcessInput (c1).ToArray ();
  323. Assert.Equal (expectedRelease, BatchToString (released1));
  324. if (expectedTValues.Length > 0)
  325. {
  326. Assert.True (expectedTValues.SequenceEqual (released1.Select (kv=>kv.Item2)));
  327. }
  328. Assert.Equal (expectedRelease, _parser2.ProcessInput (c2.ToString ()));
  329. }
  330. private string BatchToString (IEnumerable<Tuple<char, int>> processInput)
  331. {
  332. return new string(processInput.Select (a=>a.Item1).ToArray ());
  333. }
  334. private Tuple<char,int>[] NextChar (string ansiStream, ref int i)
  335. {
  336. return StringToBatch(ansiStream [i++].ToString());
  337. }
  338. private void AssertManualReleaseIs (string expectedRelease, params int [] expectedTValues)
  339. {
  340. // Consumer is responsible for determining this based on e.g. after 50ms
  341. var released1 = _parser1.Release ().ToArray ();
  342. Assert.Equal (expectedRelease, BatchToString (released1));
  343. if (expectedTValues.Length > 0)
  344. {
  345. Assert.True (expectedTValues.SequenceEqual (released1.Select (kv => kv.Item2)));
  346. }
  347. Assert.Equal (expectedRelease, _parser2.Release ());
  348. Assert.Equal (AnsiResponseParserState.Normal, _parser1.State);
  349. Assert.Equal (AnsiResponseParserState.Normal, _parser2.State);
  350. }
  351. }