AnsiResponseParserTests.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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,"Hello"[c], 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,char expected, 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. Assert.Equal (expected,c.Single());
  45. }
  46. private void AssertConsumed (string ansiStream, ref int i)
  47. {
  48. // Parser grabs this key
  49. var c = NextChar (ansiStream, ref i);
  50. Assert.Empty (_parser.ProcessInput(c));
  51. }
  52. private void AssertReleased (string ansiStream, ref int i, string expectedRelease)
  53. {
  54. var c = NextChar (ansiStream, ref i);
  55. // Parser realizes it has grabbed content that does not belong to an outstanding request
  56. // Parser returns false to indicate to continue
  57. Assert.Equal(expectedRelease,_parser.ProcessInput (c));
  58. }
  59. private string NextChar (string ansiStream, ref int i)
  60. {
  61. return ansiStream [i++].ToString();
  62. }
  63. }