ShellStreamTest_ReadExpect.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  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. expectSize: 2048);
  37. }
  38. [TestMethod]
  39. public void Read_String()
  40. {
  41. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("Hello "));
  42. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("World!"));
  43. Assert.AreEqual("Hello World!", _shellStream.Read());
  44. }
  45. [TestMethod]
  46. public void Read_Bytes()
  47. {
  48. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("Hello "));
  49. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("World!"));
  50. byte[] buffer = new byte[12];
  51. Assert.AreEqual(7, _shellStream.Read(buffer, 3, 7));
  52. CollectionAssert.AreEqual(Encoding.UTF8.GetBytes("\0\0\0Hello W\0\0"), buffer);
  53. Assert.AreEqual(5, _shellStream.Read(buffer, 0, 12));
  54. CollectionAssert.AreEqual(Encoding.UTF8.GetBytes("orld!llo W\0\0"), buffer);
  55. }
  56. [DataTestMethod]
  57. [DataRow("\r\n")]
  58. //[DataRow("\r")] These currently fail.
  59. //[DataRow("\n")]
  60. public void ReadLine(string newLine)
  61. {
  62. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("Hello "));
  63. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("World!"));
  64. // We specify a nonzero timeout to avoid waiting infinitely.
  65. Assert.IsNull(_shellStream.ReadLine(TimeSpan.FromTicks(1)));
  66. _channelSessionStub.Receive(Encoding.UTF8.GetBytes(newLine));
  67. Assert.AreEqual("Hello World!", _shellStream.ReadLine(TimeSpan.FromTicks(1)));
  68. Assert.IsNull(_shellStream.ReadLine(TimeSpan.FromTicks(1)));
  69. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("Second line!" + newLine + "Third line!" + newLine));
  70. Assert.AreEqual("Second line!", _shellStream.ReadLine(TimeSpan.FromTicks(1)));
  71. Assert.AreEqual("Third line!", _shellStream.ReadLine(TimeSpan.FromTicks(1)));
  72. Assert.IsNull(_shellStream.ReadLine(TimeSpan.FromTicks(1)));
  73. }
  74. [DataTestMethod]
  75. [DataRow("\r\n")]
  76. [DataRow("\r")]
  77. [DataRow("\n")]
  78. public void Read_MultipleLines(string newLine)
  79. {
  80. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("Hello "));
  81. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("World!"));
  82. _channelSessionStub.Receive(Encoding.UTF8.GetBytes(newLine));
  83. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("Second line!" + newLine + "Third line!" + newLine));
  84. Assert.AreEqual("Hello World!" + newLine + "Second line!" + newLine + "Third line!" + newLine, _shellStream.Read());
  85. }
  86. [TestMethod]
  87. [Ignore] // Currently returns 0 immediately
  88. public void Read_NonEmptyArray_OnlyReturnsZeroAfterClose()
  89. {
  90. Task closeTask = Task.Run(async () =>
  91. {
  92. // For the test to have meaning, we should be in
  93. // the call to Read before closing the channel.
  94. // Impose a short delay to make that more likely.
  95. await Task.Delay(50);
  96. _channelSessionStub.Close();
  97. });
  98. Assert.AreEqual(0, _shellStream.Read(new byte[16], 0, 16));
  99. Assert.AreEqual(TaskStatus.RanToCompletion, closeTask.Status);
  100. }
  101. [TestMethod]
  102. [Ignore] // Currently returns 0 immediately
  103. public void Read_EmptyArray_OnlyReturnsZeroWhenDataAvailable()
  104. {
  105. Task receiveTask = Task.Run(async () =>
  106. {
  107. // For the test to have meaning, we should be in
  108. // the call to Read before receiving the data.
  109. // Impose a short delay to make that more likely.
  110. await Task.Delay(50);
  111. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("Hello World!"));
  112. });
  113. Assert.AreEqual(0, _shellStream.Read(Array.Empty<byte>(), 0, 0));
  114. Assert.AreEqual(TaskStatus.RanToCompletion, receiveTask.Status);
  115. }
  116. [TestMethod]
  117. [Ignore] // Currently hangs
  118. public void ReadLine_NoData_ReturnsNullAfterClose()
  119. {
  120. Task closeTask = Task.Run(async () =>
  121. {
  122. await Task.Delay(50);
  123. _channelSessionStub.Close();
  124. });
  125. Assert.IsNull(_shellStream.ReadLine());
  126. Assert.AreEqual(TaskStatus.RanToCompletion, closeTask.Status);
  127. }
  128. [TestMethod]
  129. public void Expect()
  130. {
  131. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("Hello "));
  132. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("World!"));
  133. Assert.IsNull(_shellStream.Expect("123", TimeSpan.FromTicks(1)));
  134. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("\r\n12345"));
  135. // Both of these cases fail
  136. // Case 1 above.
  137. Assert.AreEqual("Hello World!\r\n123", _shellStream.Expect("123")); // Fails, returns "Hello World!\r\n12345"
  138. Assert.AreEqual("45", _shellStream.Read()); // Passes, but should probably fail and return ""
  139. }
  140. [TestMethod]
  141. public void Read_MultiByte()
  142. {
  143. _channelSessionStub.Receive(new byte[] { 0xF0 });
  144. _channelSessionStub.Receive(new byte[] { 0x9F });
  145. _channelSessionStub.Receive(new byte[] { 0x91 });
  146. _channelSessionStub.Receive(new byte[] { 0x8D });
  147. Assert.AreEqual("👍", _shellStream.Read());
  148. }
  149. [TestMethod]
  150. public void ReadLine_MultiByte()
  151. {
  152. _channelSessionStub.Receive(new byte[] { 0xF0 });
  153. _channelSessionStub.Receive(new byte[] { 0x9F });
  154. _channelSessionStub.Receive(new byte[] { 0x91 });
  155. _channelSessionStub.Receive(new byte[] { 0x8D });
  156. _channelSessionStub.Receive(new byte[] { 0x0D });
  157. _channelSessionStub.Receive(new byte[] { 0x0A });
  158. Assert.AreEqual("👍", _shellStream.ReadLine());
  159. Assert.AreEqual("", _shellStream.Read());
  160. }
  161. [TestMethod]
  162. public void Expect_Regex_MultiByte()
  163. {
  164. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("𐓏𐓘𐓻𐓘𐓻𐓟 𐒻𐓟"));
  165. Assert.AreEqual("𐓏𐓘𐓻𐓘𐓻𐓟 ", _shellStream.Expect(new Regex(@"\s")));
  166. Assert.AreEqual("𐒻𐓟", _shellStream.Read());
  167. }
  168. [TestMethod]
  169. public void Expect_String_MultiByte()
  170. {
  171. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("hello 你好"));
  172. Assert.AreEqual("hello 你好", _shellStream.Expect("你好"));
  173. Assert.AreEqual("", _shellStream.Read());
  174. }
  175. [TestMethod]
  176. public void Expect_String_non_ASCII_characters()
  177. {
  178. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("Hello, こんにちは, Bonjour"));
  179. Assert.AreEqual("Hello, こ", _shellStream.Expect(new Regex(@"[^\u0000-\u007F]")));
  180. Assert.AreEqual("んにちは, Bonjour", _shellStream.Read());
  181. }
  182. [TestMethod]
  183. public void Expect_String_LargeExpect()
  184. {
  185. _channelSessionStub.Receive(Encoding.UTF8.GetBytes(new string('a', 100)));
  186. for (var i = 0; i < 10; i++)
  187. {
  188. _channelSessionStub.Receive(Encoding.UTF8.GetBytes(new string('b', 100)));
  189. }
  190. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("Hello, こんにちは, Bonjour"));
  191. _channelSessionStub.Receive(Encoding.UTF8.GetBytes(new string('c', 100)));
  192. Assert.AreEqual($"{new string('a', 100)}{new string('b', 1000)}Hello, こんにちは, Bonjour", _shellStream.Expect($"{new string('b', 1000)}Hello, こんにちは, Bonjour"));
  193. Assert.AreEqual($"{new string('c', 100)}", _shellStream.Read());
  194. }
  195. [TestMethod]
  196. public void Expect_Timeout()
  197. {
  198. Stopwatch stopwatch = Stopwatch.StartNew();
  199. Assert.IsNull(_shellStream.Expect("Hello World!", TimeSpan.FromMilliseconds(200)));
  200. TimeSpan elapsed = stopwatch.Elapsed;
  201. // Account for variance in system timer resolution.
  202. Assert.IsTrue(elapsed > TimeSpan.FromMilliseconds(180), elapsed.ToString());
  203. }
  204. private class ChannelSessionStub : IChannelSession
  205. {
  206. public void Receive(byte[] data)
  207. {
  208. DataReceived.Invoke(this, new ChannelDataEventArgs(channelNumber: 0, data));
  209. }
  210. public void Close()
  211. {
  212. Closed.Invoke(this, new ChannelEventArgs(channelNumber: 0));
  213. }
  214. public bool SendShellRequest()
  215. {
  216. return true;
  217. }
  218. public bool SendPseudoTerminalRequest(string environmentVariable, uint columns, uint rows, uint width, uint height, IDictionary<TerminalModes, uint> terminalModeValues)
  219. {
  220. return true;
  221. }
  222. public void Dispose()
  223. {
  224. }
  225. public void Open()
  226. {
  227. }
  228. public event EventHandler<ChannelDataEventArgs> DataReceived;
  229. public event EventHandler<ChannelEventArgs> Closed;
  230. #pragma warning disable 0067
  231. public event EventHandler<ExceptionEventArgs> Exception;
  232. public event EventHandler<ChannelExtendedDataEventArgs> ExtendedDataReceived;
  233. public event EventHandler<ChannelRequestEventArgs> RequestReceived;
  234. #pragma warning restore 0067
  235. #pragma warning disable IDE0025 // Use block body for property
  236. #pragma warning disable IDE0022 // Use block body for method
  237. public uint LocalChannelNumber => throw new NotImplementedException();
  238. public uint LocalPacketSize => throw new NotImplementedException();
  239. public uint RemotePacketSize => throw new NotImplementedException();
  240. public bool IsOpen => throw new NotImplementedException();
  241. public bool SendBreakRequest(uint breakLength) => throw new NotImplementedException();
  242. public void SendData(byte[] data) => throw new NotImplementedException();
  243. public void SendData(byte[] data, int offset, int size) => throw new NotImplementedException();
  244. public bool SendEndOfWriteRequest() => throw new NotImplementedException();
  245. public bool SendEnvironmentVariableRequest(string variableName, string variableValue) => throw new NotImplementedException();
  246. public void SendEof() => throw new NotImplementedException();
  247. public bool SendExecRequest(string command) => throw new NotImplementedException();
  248. public bool SendExitSignalRequest(string signalName, bool coreDumped, string errorMessage, string language) => throw new NotImplementedException();
  249. public bool SendExitStatusRequest(uint exitStatus) => throw new NotImplementedException();
  250. public bool SendKeepAliveRequest() => throw new NotImplementedException();
  251. public bool SendLocalFlowRequest(bool clientCanDo) => throw new NotImplementedException();
  252. public bool SendSignalRequest(string signalName) => throw new NotImplementedException();
  253. public bool SendSubsystemRequest(string subsystem) => throw new NotImplementedException();
  254. public bool SendWindowChangeRequest(uint columns, uint rows, uint width, uint height) => throw new NotImplementedException();
  255. public bool SendX11ForwardingRequest(bool isSingleConnection, string protocol, byte[] cookie, uint screenNumber) => throw new NotImplementedException();
  256. #pragma warning restore IDE0022 // Use block body for method
  257. #pragma warning restore IDE0025 // Use block body for property
  258. }
  259. }
  260. }