AnsiResponseParserTests.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. namespace UnitTests.ConsoleDrivers;
  2. public class AnsiResponseParserTests
  3. {
  4. AnsiResponseParser _parser = new AnsiResponseParser ();
  5. [Fact]
  6. public void TestInputProcessing ()
  7. {
  8. string ansiStream = "\x1B[<0;10;20M" + // ANSI escape for mouse move at (10, 20)
  9. "Hello" + // User types "Hello"
  10. "\x1B[0c"; // Device Attributes response (e.g., terminal identification i.e. DAR)
  11. string? response = null;
  12. int i = 0;
  13. // Imagine that we are expecting a DAR
  14. _parser.ExpectResponse ("c",(s)=> response = s);
  15. // First char is Escape which we must consume incase what follows is the DAR
  16. AssertConsumed (ansiStream, ref i); // Esc
  17. for (int c = 0; c < "[<0;10;20".Length; c++)
  18. {
  19. AssertConsumed (ansiStream, ref i);
  20. }
  21. // We see the M terminator
  22. AssertReleased (ansiStream, ref i, "\x1B[<0;10;20M");
  23. // Regular user typing
  24. for (int c = 0; c < "Hello".Length; c++)
  25. {
  26. AssertIgnored (ansiStream, ref i);
  27. }
  28. // Now we have entered the actual DAR we should be consuming these
  29. for (int c = 0; c < "\x1B [0".Length; c++)
  30. {
  31. AssertConsumed (ansiStream, ref i);
  32. }
  33. // Consume the terminator 'c' and expect this to call the above event
  34. Assert.Null (response);
  35. AssertConsumed (ansiStream, ref i);
  36. Assert.NotNull (response);
  37. Assert.Equal ("\u001b[0c", response);
  38. }
  39. private void AssertIgnored (string ansiStream, ref int i)
  40. {
  41. var c = NextChar (ansiStream, ref i);
  42. // Parser does not grab this key (i.e. driver can continue with regular operations)
  43. Assert.Equal ( c,_parser.ProcessInput (c));
  44. }
  45. private void AssertConsumed (string ansiStream, ref int i)
  46. {
  47. // Parser grabs this key
  48. var c = NextChar (ansiStream, ref i);
  49. Assert.Empty (_parser.ProcessInput(c));
  50. }
  51. private void AssertReleased (string ansiStream, ref int i, string expectedRelease)
  52. {
  53. var c = NextChar (ansiStream, ref i);
  54. // Parser realizes it has grabbed content that does not belong to an outstanding request
  55. // Parser returns false to indicate to continue
  56. Assert.Equal(expectedRelease,_parser.ProcessInput (c));
  57. }
  58. private string NextChar (string ansiStream, ref int i)
  59. {
  60. return ansiStream [i++].ToString();
  61. }
  62. }