ShellStreamTest_ReadExpect.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Text;
  5. using System.Text.RegularExpressions;
  6. using System.Threading.Tasks;
  7. using Microsoft.VisualStudio.TestTools.UnitTesting;
  8. using Moq;
  9. using Renci.SshNet.Channels;
  10. using Renci.SshNet.Common;
  11. namespace Renci.SshNet.Tests.Classes
  12. {
  13. [TestClass]
  14. public class ShellStreamTest_ReadExpect
  15. {
  16. private ShellStream _shellStream;
  17. private ChannelSessionStub _channelSessionStub;
  18. [TestInitialize]
  19. public void Initialize()
  20. {
  21. _channelSessionStub = new ChannelSessionStub();
  22. var connectionInfoMock = new Mock<IConnectionInfo>();
  23. connectionInfoMock.Setup(p => p.Encoding).Returns(Encoding.UTF8);
  24. var sessionMock = new Mock<ISession>();
  25. sessionMock.Setup(p => p.ConnectionInfo).Returns(connectionInfoMock.Object);
  26. sessionMock.Setup(p => p.CreateChannelSession()).Returns(_channelSessionStub);
  27. _shellStream = new ShellStream(
  28. sessionMock.Object,
  29. "terminalName",
  30. columns: 80,
  31. rows: 24,
  32. width: 800,
  33. height: 600,
  34. terminalModeValues: null,
  35. bufferSize: 1024);
  36. }
  37. [TestMethod]
  38. public void Read_String()
  39. {
  40. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("Hello "));
  41. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("World!"));
  42. Assert.AreEqual("Hello World!", _shellStream.Read());
  43. }
  44. [TestMethod]
  45. public void Read_Bytes()
  46. {
  47. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("Hello "));
  48. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("World!"));
  49. byte[] buffer = new byte[12];
  50. Assert.AreEqual(7, _shellStream.Read(buffer, 3, 7));
  51. CollectionAssert.AreEqual(Encoding.UTF8.GetBytes("\0\0\0Hello W\0\0"), buffer);
  52. Assert.AreEqual(5, _shellStream.Read(buffer, 0, 12));
  53. CollectionAssert.AreEqual(Encoding.UTF8.GetBytes("orld!llo W\0\0"), buffer);
  54. }
  55. [DataTestMethod]
  56. [DataRow("\r\n")]
  57. //[DataRow("\r")] These currently fail.
  58. //[DataRow("\n")]
  59. public void ReadLine(string newLine)
  60. {
  61. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("Hello "));
  62. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("World!"));
  63. // We specify a nonzero timeout to avoid waiting infinitely.
  64. Assert.IsNull(_shellStream.ReadLine(TimeSpan.FromTicks(1)));
  65. _channelSessionStub.Receive(Encoding.UTF8.GetBytes(newLine));
  66. Assert.AreEqual("Hello World!", _shellStream.ReadLine(TimeSpan.FromTicks(1)));
  67. Assert.IsNull(_shellStream.ReadLine(TimeSpan.FromTicks(1)));
  68. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("Second line!" + newLine + "Third line!" + newLine));
  69. Assert.AreEqual("Second line!", _shellStream.ReadLine(TimeSpan.FromTicks(1)));
  70. Assert.AreEqual("Third line!", _shellStream.ReadLine(TimeSpan.FromTicks(1)));
  71. Assert.IsNull(_shellStream.ReadLine(TimeSpan.FromTicks(1)));
  72. }
  73. [DataTestMethod]
  74. [DataRow("\r\n")]
  75. [DataRow("\r")]
  76. [DataRow("\n")]
  77. public void Read_MultipleLines(string newLine)
  78. {
  79. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("Hello "));
  80. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("World!"));
  81. _channelSessionStub.Receive(Encoding.UTF8.GetBytes(newLine));
  82. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("Second line!" + newLine + "Third line!" + newLine));
  83. Assert.AreEqual("Hello World!" + newLine + "Second line!" + newLine + "Third line!" + newLine, _shellStream.Read());
  84. }
  85. [TestMethod]
  86. [Ignore] // Currently returns 0 immediately
  87. public void Read_NonEmptyArray_OnlyReturnsZeroAfterClose()
  88. {
  89. Task closeTask = Task.Run(async () =>
  90. {
  91. // For the test to have meaning, we should be in
  92. // the call to Read before closing the channel.
  93. // Impose a short delay to make that more likely.
  94. await Task.Delay(50);
  95. _channelSessionStub.Close();
  96. });
  97. Assert.AreEqual(0, _shellStream.Read(new byte[16], 0, 16));
  98. Assert.AreEqual(TaskStatus.RanToCompletion, closeTask.Status);
  99. }
  100. [TestMethod]
  101. [Ignore] // Currently returns 0 immediately
  102. public void Read_EmptyArray_OnlyReturnsZeroWhenDataAvailable()
  103. {
  104. Task receiveTask = Task.Run(async () =>
  105. {
  106. // For the test to have meaning, we should be in
  107. // the call to Read before receiving the data.
  108. // Impose a short delay to make that more likely.
  109. await Task.Delay(50);
  110. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("Hello World!"));
  111. });
  112. Assert.AreEqual(0, _shellStream.Read(Array.Empty<byte>(), 0, 0));
  113. Assert.AreEqual(TaskStatus.RanToCompletion, receiveTask.Status);
  114. }
  115. [TestMethod]
  116. [Ignore] // Currently hangs
  117. public void ReadLine_NoData_ReturnsNullAfterClose()
  118. {
  119. Task closeTask = Task.Run(async () =>
  120. {
  121. await Task.Delay(50);
  122. _channelSessionStub.Close();
  123. });
  124. Assert.IsNull(_shellStream.ReadLine());
  125. Assert.AreEqual(TaskStatus.RanToCompletion, closeTask.Status);
  126. }
  127. [TestMethod]
  128. [Ignore] // Fails because it returns the whole buffer i.e. "Hello World!\r\n12345"
  129. // We might actually want to keep that behaviour, but just make the documentation clearer.
  130. // The Expect documentation says:
  131. // "The text available in the shell that contains all the text that ends with expected expression."
  132. // Does that mean
  133. // 1. the returned string ends with the expected expression; or
  134. // 2. the returned string is all the text in the buffer, which is guaranteed to contain the expected expression?
  135. // The current behaviour is closer to 2. I think the documentation implies 1.
  136. // Either way, there are bugs.
  137. public void Expect()
  138. {
  139. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("Hello "));
  140. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("World!"));
  141. Assert.IsNull(_shellStream.Expect("123", TimeSpan.FromTicks(1)));
  142. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("\r\n12345"));
  143. // Both of these cases fail
  144. // Case 1 above.
  145. Assert.AreEqual("Hello World!\r\n123", _shellStream.Expect("123")); // Fails, returns "Hello World!\r\n12345"
  146. Assert.AreEqual("45", _shellStream.Read()); // Passes, but should probably fail and return ""
  147. // Case 2 above.
  148. Assert.AreEqual("Hello World!\r\n12345", _shellStream.Expect("123")); // Passes
  149. Assert.AreEqual("", _shellStream.Read()); // Fails, returns "45"
  150. }
  151. [TestMethod]
  152. public void Read_MultiByte()
  153. {
  154. _channelSessionStub.Receive(new byte[] { 0xF0 });
  155. _channelSessionStub.Receive(new byte[] { 0x9F });
  156. _channelSessionStub.Receive(new byte[] { 0x91 });
  157. _channelSessionStub.Receive(new byte[] { 0x8D });
  158. Assert.AreEqual("👍", _shellStream.Read());
  159. }
  160. [TestMethod]
  161. public void ReadLine_MultiByte()
  162. {
  163. _channelSessionStub.Receive(new byte[] { 0xF0 });
  164. _channelSessionStub.Receive(new byte[] { 0x9F });
  165. _channelSessionStub.Receive(new byte[] { 0x91 });
  166. _channelSessionStub.Receive(new byte[] { 0x8D });
  167. _channelSessionStub.Receive(new byte[] { 0x0D });
  168. _channelSessionStub.Receive(new byte[] { 0x0A });
  169. Assert.AreEqual("👍", _shellStream.ReadLine());
  170. Assert.AreEqual("", _shellStream.Read());
  171. }
  172. [TestMethod]
  173. [Ignore]
  174. public void Expect_Regex_MultiByte()
  175. {
  176. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("𐓏𐓘𐓻𐓘𐓻𐓟 𐒻𐓟"));
  177. Assert.AreEqual("𐓏𐓘𐓻𐓘𐓻𐓟 ", _shellStream.Expect(new Regex(@"\s")));
  178. Assert.AreEqual("𐒻𐓟", _shellStream.Read());
  179. }
  180. [TestMethod]
  181. [Ignore]
  182. public void Expect_String_MultiByte()
  183. {
  184. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("hello 你好"));
  185. Assert.AreEqual("hello 你好", _shellStream.Expect("你好"));
  186. Assert.AreEqual("", _shellStream.Read());
  187. }
  188. [TestMethod]
  189. public void Expect_Timeout()
  190. {
  191. Stopwatch stopwatch = Stopwatch.StartNew();
  192. Assert.IsNull(_shellStream.Expect("Hello World!", TimeSpan.FromMilliseconds(200)));
  193. TimeSpan elapsed = stopwatch.Elapsed;
  194. // Account for variance in system timer resolution.
  195. Assert.IsTrue(elapsed > TimeSpan.FromMilliseconds(180), elapsed.ToString());
  196. }
  197. private class ChannelSessionStub : IChannelSession
  198. {
  199. public void Receive(byte[] data)
  200. {
  201. DataReceived.Invoke(this, new ChannelDataEventArgs(channelNumber: 0, data));
  202. }
  203. public void Close()
  204. {
  205. Closed.Invoke(this, new ChannelEventArgs(channelNumber: 0));
  206. }
  207. public bool SendShellRequest()
  208. {
  209. return true;
  210. }
  211. public bool SendPseudoTerminalRequest(string environmentVariable, uint columns, uint rows, uint width, uint height, IDictionary<TerminalModes, uint> terminalModeValues)
  212. {
  213. return true;
  214. }
  215. public void Dispose()
  216. {
  217. }
  218. public void Open()
  219. {
  220. }
  221. public event EventHandler<ChannelDataEventArgs> DataReceived;
  222. public event EventHandler<ChannelEventArgs> Closed;
  223. #pragma warning disable 0067
  224. public event EventHandler<ExceptionEventArgs> Exception;
  225. public event EventHandler<ChannelExtendedDataEventArgs> ExtendedDataReceived;
  226. public event EventHandler<ChannelRequestEventArgs> RequestReceived;
  227. #pragma warning restore 0067
  228. #pragma warning disable IDE0025 // Use block body for property
  229. #pragma warning disable IDE0022 // Use block body for method
  230. public uint LocalChannelNumber => throw new NotImplementedException();
  231. public uint LocalPacketSize => throw new NotImplementedException();
  232. public uint RemotePacketSize => throw new NotImplementedException();
  233. public bool IsOpen => throw new NotImplementedException();
  234. public bool SendBreakRequest(uint breakLength) => throw new NotImplementedException();
  235. public void SendData(byte[] data) => throw new NotImplementedException();
  236. public void SendData(byte[] data, int offset, int size) => throw new NotImplementedException();
  237. public bool SendEndOfWriteRequest() => throw new NotImplementedException();
  238. public bool SendEnvironmentVariableRequest(string variableName, string variableValue) => throw new NotImplementedException();
  239. public void SendEof() => throw new NotImplementedException();
  240. public bool SendExecRequest(string command) => throw new NotImplementedException();
  241. public bool SendExitSignalRequest(string signalName, bool coreDumped, string errorMessage, string language) => throw new NotImplementedException();
  242. public bool SendExitStatusRequest(uint exitStatus) => throw new NotImplementedException();
  243. public bool SendKeepAliveRequest() => throw new NotImplementedException();
  244. public bool SendLocalFlowRequest(bool clientCanDo) => throw new NotImplementedException();
  245. public bool SendSignalRequest(string signalName) => throw new NotImplementedException();
  246. public bool SendSubsystemRequest(string subsystem) => throw new NotImplementedException();
  247. public bool SendWindowChangeRequest(uint columns, uint rows, uint width, uint height) => throw new NotImplementedException();
  248. public bool SendX11ForwardingRequest(bool isSingleConnection, string protocol, byte[] cookie, uint screenNumber) => throw new NotImplementedException();
  249. #pragma warning restore IDE0022 // Use block body for method
  250. #pragma warning restore IDE0025 // Use block body for property
  251. }
  252. }
  253. }