ShellStreamTest_ReadExpect.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  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. public void Expect()
  129. {
  130. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("Hello "));
  131. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("World!"));
  132. Assert.IsNull(_shellStream.Expect("123", TimeSpan.FromTicks(1)));
  133. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("\r\n12345"));
  134. // Both of these cases fail
  135. // Case 1 above.
  136. Assert.AreEqual("Hello World!\r\n123", _shellStream.Expect("123")); // Fails, returns "Hello World!\r\n12345"
  137. Assert.AreEqual("45", _shellStream.Read()); // Passes, but should probably fail and return ""
  138. }
  139. [TestMethod]
  140. public void Read_MultiByte()
  141. {
  142. _channelSessionStub.Receive(new byte[] { 0xF0 });
  143. _channelSessionStub.Receive(new byte[] { 0x9F });
  144. _channelSessionStub.Receive(new byte[] { 0x91 });
  145. _channelSessionStub.Receive(new byte[] { 0x8D });
  146. Assert.AreEqual("👍", _shellStream.Read());
  147. }
  148. [TestMethod]
  149. public void ReadLine_MultiByte()
  150. {
  151. _channelSessionStub.Receive(new byte[] { 0xF0 });
  152. _channelSessionStub.Receive(new byte[] { 0x9F });
  153. _channelSessionStub.Receive(new byte[] { 0x91 });
  154. _channelSessionStub.Receive(new byte[] { 0x8D });
  155. _channelSessionStub.Receive(new byte[] { 0x0D });
  156. _channelSessionStub.Receive(new byte[] { 0x0A });
  157. Assert.AreEqual("👍", _shellStream.ReadLine());
  158. Assert.AreEqual("", _shellStream.Read());
  159. }
  160. [TestMethod]
  161. public void Expect_Regex_MultiByte()
  162. {
  163. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("𐓏𐓘𐓻𐓘𐓻𐓟 𐒻𐓟"));
  164. Assert.AreEqual("𐓏𐓘𐓻𐓘𐓻𐓟 ", _shellStream.Expect(new Regex(@"\s")));
  165. Assert.AreEqual("𐒻𐓟", _shellStream.Read());
  166. }
  167. [TestMethod]
  168. public void Expect_String_MultiByte()
  169. {
  170. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("hello 你好"));
  171. Assert.AreEqual("hello 你好", _shellStream.Expect("你好"));
  172. Assert.AreEqual("", _shellStream.Read());
  173. }
  174. [TestMethod]
  175. public void Expect_String_non_ASCII_characters()
  176. {
  177. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("Hello, こんにちは, Bonjour"));
  178. Assert.AreEqual("Hello, こ", _shellStream.Expect(new Regex(@"[^\u0000-\u007F]")));
  179. Assert.AreEqual("んにちは, Bonjour", _shellStream.Read());
  180. }
  181. [TestMethod]
  182. public void Expect_Timeout()
  183. {
  184. Stopwatch stopwatch = Stopwatch.StartNew();
  185. Assert.IsNull(_shellStream.Expect("Hello World!", TimeSpan.FromMilliseconds(200)));
  186. TimeSpan elapsed = stopwatch.Elapsed;
  187. // Account for variance in system timer resolution.
  188. Assert.IsTrue(elapsed > TimeSpan.FromMilliseconds(180), elapsed.ToString());
  189. }
  190. private class ChannelSessionStub : IChannelSession
  191. {
  192. public void Receive(byte[] data)
  193. {
  194. DataReceived.Invoke(this, new ChannelDataEventArgs(channelNumber: 0, data));
  195. }
  196. public void Close()
  197. {
  198. Closed.Invoke(this, new ChannelEventArgs(channelNumber: 0));
  199. }
  200. public bool SendShellRequest()
  201. {
  202. return true;
  203. }
  204. public bool SendPseudoTerminalRequest(string environmentVariable, uint columns, uint rows, uint width, uint height, IDictionary<TerminalModes, uint> terminalModeValues)
  205. {
  206. return true;
  207. }
  208. public void Dispose()
  209. {
  210. }
  211. public void Open()
  212. {
  213. }
  214. public event EventHandler<ChannelDataEventArgs> DataReceived;
  215. public event EventHandler<ChannelEventArgs> Closed;
  216. #pragma warning disable 0067
  217. public event EventHandler<ExceptionEventArgs> Exception;
  218. public event EventHandler<ChannelExtendedDataEventArgs> ExtendedDataReceived;
  219. public event EventHandler<ChannelRequestEventArgs> RequestReceived;
  220. #pragma warning restore 0067
  221. #pragma warning disable IDE0025 // Use block body for property
  222. #pragma warning disable IDE0022 // Use block body for method
  223. public uint LocalChannelNumber => throw new NotImplementedException();
  224. public uint LocalPacketSize => throw new NotImplementedException();
  225. public uint RemotePacketSize => throw new NotImplementedException();
  226. public bool IsOpen => throw new NotImplementedException();
  227. public bool SendBreakRequest(uint breakLength) => throw new NotImplementedException();
  228. public void SendData(byte[] data) => throw new NotImplementedException();
  229. public void SendData(byte[] data, int offset, int size) => throw new NotImplementedException();
  230. public bool SendEndOfWriteRequest() => throw new NotImplementedException();
  231. public bool SendEnvironmentVariableRequest(string variableName, string variableValue) => throw new NotImplementedException();
  232. public void SendEof() => throw new NotImplementedException();
  233. public bool SendExecRequest(string command) => throw new NotImplementedException();
  234. public bool SendExitSignalRequest(string signalName, bool coreDumped, string errorMessage, string language) => throw new NotImplementedException();
  235. public bool SendExitStatusRequest(uint exitStatus) => throw new NotImplementedException();
  236. public bool SendKeepAliveRequest() => throw new NotImplementedException();
  237. public bool SendLocalFlowRequest(bool clientCanDo) => throw new NotImplementedException();
  238. public bool SendSignalRequest(string signalName) => throw new NotImplementedException();
  239. public bool SendSubsystemRequest(string subsystem) => throw new NotImplementedException();
  240. public bool SendWindowChangeRequest(uint columns, uint rows, uint width, uint height) => throw new NotImplementedException();
  241. public bool SendX11ForwardingRequest(bool isSingleConnection, string protocol, byte[] cookie, uint screenNumber) => throw new NotImplementedException();
  242. #pragma warning restore IDE0022 // Use block body for method
  243. #pragma warning restore IDE0025 // Use block body for property
  244. }
  245. }
  246. }