AnsiResponseParserTests.cs 18 KB

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