ShellStreamTest_ReadExpect.cs 14 KB

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