2
0

ShellStreamTest_ReadExpect.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  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 ShellStream _shellStream;
  18. private ChannelSessionStub _channelSessionStub;
  19. [TestInitialize]
  20. public void Initialize()
  21. {
  22. _channelSessionStub = new ChannelSessionStub();
  23. var connectionInfoMock = new Mock<IConnectionInfo>();
  24. connectionInfoMock.Setup(p => p.Encoding).Returns(Encoding.UTF8);
  25. var sessionMock = new Mock<ISession>();
  26. sessionMock.Setup(p => p.ConnectionInfo).Returns(connectionInfoMock.Object);
  27. sessionMock.Setup(p => p.CreateChannelSession()).Returns(_channelSessionStub);
  28. _shellStream = new ShellStream(
  29. sessionMock.Object,
  30. "terminalName",
  31. columns: 80,
  32. rows: 24,
  33. width: 800,
  34. height: 600,
  35. terminalModeValues: null,
  36. bufferSize: BufferSize);
  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")]
  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 timeout to avoid waiting infinitely.
  65. Assert.IsNull(_shellStream.ReadLine(TimeSpan.Zero));
  66. _channelSessionStub.Receive(Encoding.UTF8.GetBytes(newLine));
  67. Assert.AreEqual("Hello World!", _shellStream.ReadLine(TimeSpan.Zero));
  68. Assert.IsNull(_shellStream.ReadLine(TimeSpan.Zero));
  69. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("Second line!" + newLine + "Third line!" + newLine));
  70. Assert.AreEqual("Second line!", _shellStream.ReadLine(TimeSpan.Zero));
  71. Assert.AreEqual("Third line!", _shellStream.ReadLine(TimeSpan.Zero));
  72. Assert.IsNull(_shellStream.ReadLine(TimeSpan.Zero));
  73. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("Last line!")); // no newLine at the end
  74. Assert.IsNull(_shellStream.ReadLine(TimeSpan.Zero));
  75. _channelSessionStub.Close();
  76. Assert.AreEqual("Last line!", _shellStream.ReadLine(TimeSpan.Zero));
  77. }
  78. [TestMethod]
  79. public void ReadLine_DifferentTerminators()
  80. {
  81. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("Hello\rWorld!\nWhat's\r\ngoing\n\ron?\n"));
  82. Assert.AreEqual("Hello", _shellStream.ReadLine());
  83. Assert.AreEqual("World!", _shellStream.ReadLine());
  84. Assert.AreEqual("What's", _shellStream.ReadLine());
  85. Assert.AreEqual("going", _shellStream.ReadLine());
  86. Assert.AreEqual("", _shellStream.ReadLine());
  87. Assert.AreEqual("on?", _shellStream.ReadLine());
  88. Assert.IsNull(_shellStream.ReadLine(TimeSpan.Zero));
  89. }
  90. [DataTestMethod]
  91. [DataRow("\r\n")]
  92. [DataRow("\r")]
  93. [DataRow("\n")]
  94. public void Read_MultipleLines(string newLine)
  95. {
  96. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("Hello "));
  97. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("World!"));
  98. _channelSessionStub.Receive(Encoding.UTF8.GetBytes(newLine));
  99. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("Second line!" + newLine + "Third line!" + newLine));
  100. Assert.AreEqual("Hello World!" + newLine + "Second line!" + newLine + "Third line!" + newLine, _shellStream.Read());
  101. }
  102. [TestMethod]
  103. public async Task Read_NonEmptyArray_OnlyReturnsZeroAfterClose()
  104. {
  105. Task<int> readTask = _shellStream.ReadAsync(new byte[16], 0, 16);
  106. await Task.Delay(50);
  107. Assert.IsFalse(readTask.IsCompleted);
  108. _channelSessionStub.Close();
  109. Assert.AreEqual(0, await readTask);
  110. }
  111. [TestMethod]
  112. public async Task Read_EmptyArray_OnlyReturnsZeroWhenDataAvailable()
  113. {
  114. Task<int> readTask = _shellStream.ReadAsync(Array.Empty<byte>(), 0, 0);
  115. await Task.Delay(50);
  116. Assert.IsFalse(readTask.IsCompleted);
  117. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("Hello World!"));
  118. Assert.AreEqual(0, await readTask);
  119. }
  120. [TestMethod]
  121. public void Expect()
  122. {
  123. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("Hello "));
  124. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("World!"));
  125. Assert.IsNull(_shellStream.Expect("123", TimeSpan.Zero));
  126. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("\r\n12345"));
  127. Assert.AreEqual("Hello World!\r\n123", _shellStream.Expect("123"));
  128. Assert.AreEqual("45", _shellStream.Read());
  129. }
  130. [TestMethod]
  131. public void Read_AfterDispose_StillWorks()
  132. {
  133. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("Hello World!"));
  134. _shellStream.Dispose();
  135. _shellStream.Dispose(); // Check that multiple Dispose is OK.
  136. Assert.AreEqual("Hello World!", _shellStream.ReadLine());
  137. Assert.IsNull(_shellStream.ReadLine());
  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_Regex_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_String_LargeExpect()
  183. {
  184. _channelSessionStub.Receive(Encoding.UTF8.GetBytes(new string('a', 100)));
  185. for (var i = 0; i < 10; i++)
  186. {
  187. _channelSessionStub.Receive(Encoding.UTF8.GetBytes(new string('b', 100)));
  188. }
  189. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("Hello, こんにちは, Bonjour"));
  190. _channelSessionStub.Receive(Encoding.UTF8.GetBytes(new string('c', 100)));
  191. Assert.AreEqual($"{new string('a', 100)}{new string('b', 1000)}Hello, こんにちは, Bonjour", _shellStream.Expect($"{new string('b', 1000)}Hello, こんにちは, Bonjour"));
  192. Assert.AreEqual($"{new string('c', 100)}", _shellStream.Read());
  193. }
  194. [TestMethod]
  195. public void Expect_String_WithLookback()
  196. {
  197. const string expected = "ccccc";
  198. // Prime buffer
  199. _channelSessionStub.Receive(Encoding.UTF8.GetBytes(new string(' ', BufferSize)));
  200. // Test data
  201. _channelSessionStub.Receive(Encoding.UTF8.GetBytes(new string('a', 100)));
  202. _channelSessionStub.Receive(Encoding.UTF8.GetBytes(new string('b', 100)));
  203. _channelSessionStub.Receive(Encoding.UTF8.GetBytes(expected));
  204. _channelSessionStub.Receive(Encoding.UTF8.GetBytes(new string('d', 100)));
  205. _channelSessionStub.Receive(Encoding.UTF8.GetBytes(new string('e', 100)));
  206. // Expected result
  207. var expectedResult = $"{new string(' ', BufferSize)}{new string('a', 100)}{new string('b', 100)}{expected}";
  208. var expectedRead = $"{new string('d', 100)}{new string('e', 100)}";
  209. Assert.AreEqual(expectedResult, _shellStream.Expect(expected, TimeSpan.Zero, lookback: 250));
  210. Assert.AreEqual(expectedRead, _shellStream.Read());
  211. }
  212. [TestMethod]
  213. public void Expect_Regex_WithLookback()
  214. {
  215. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("0123456789"));
  216. Assert.AreEqual("01234567", _shellStream.Expect(new Regex(@"\d"), TimeSpan.Zero, lookback: 3));
  217. Assert.AreEqual("89", _shellStream.Read());
  218. }
  219. [TestMethod]
  220. public void Expect_Regex_WithLookback_non_ASCII_characters()
  221. {
  222. _channelSessionStub.Receive(Encoding.UTF8.GetBytes("Hello, こんにちは, Bonjour"));
  223. Assert.AreEqual("Hello, こんにち", _shellStream.Expect(new Regex(@"[^\u0000-\u007F]"), TimeSpan.Zero, lookback: 11));
  224. Assert.AreEqual("は, Bonjour", _shellStream.Read());
  225. }
  226. [TestMethod]
  227. public void Expect_Timeout()
  228. {
  229. Stopwatch stopwatch = Stopwatch.StartNew();
  230. Assert.IsNull(_shellStream.Expect("Hello World!", TimeSpan.FromMilliseconds(200)));
  231. TimeSpan elapsed = stopwatch.Elapsed;
  232. // Account for variance in system timer resolution.
  233. Assert.IsTrue(elapsed > TimeSpan.FromMilliseconds(180), elapsed.ToString());
  234. }
  235. private class ChannelSessionStub : IChannelSession
  236. {
  237. public void Receive(byte[] data)
  238. {
  239. DataReceived.Invoke(this, new ChannelDataEventArgs(channelNumber: 0, data));
  240. }
  241. public void Close()
  242. {
  243. Closed.Invoke(this, new ChannelEventArgs(channelNumber: 0));
  244. }
  245. public bool SendShellRequest()
  246. {
  247. return true;
  248. }
  249. public bool SendPseudoTerminalRequest(string environmentVariable, uint columns, uint rows, uint width, uint height, IDictionary<TerminalModes, uint> terminalModeValues)
  250. {
  251. return true;
  252. }
  253. public void Dispose()
  254. {
  255. }
  256. public void Open()
  257. {
  258. }
  259. public event EventHandler<ChannelDataEventArgs> DataReceived;
  260. public event EventHandler<ChannelEventArgs> Closed;
  261. #pragma warning disable 0067
  262. public event EventHandler<ExceptionEventArgs> Exception;
  263. public event EventHandler<ChannelExtendedDataEventArgs> ExtendedDataReceived;
  264. public event EventHandler<ChannelRequestEventArgs> RequestReceived;
  265. #pragma warning restore 0067
  266. #pragma warning disable IDE0025 // Use block body for property
  267. #pragma warning disable IDE0022 // Use block body for method
  268. public uint LocalChannelNumber => throw new NotImplementedException();
  269. public uint LocalPacketSize => throw new NotImplementedException();
  270. public uint RemotePacketSize => throw new NotImplementedException();
  271. public bool IsOpen => throw new NotImplementedException();
  272. public bool SendBreakRequest(uint breakLength) => throw new NotImplementedException();
  273. public void SendData(byte[] data) => throw new NotImplementedException();
  274. public void SendData(byte[] data, int offset, int size) => throw new NotImplementedException();
  275. public bool SendEndOfWriteRequest() => throw new NotImplementedException();
  276. public bool SendEnvironmentVariableRequest(string variableName, string variableValue) => throw new NotImplementedException();
  277. public void SendEof() => throw new NotImplementedException();
  278. public bool SendExecRequest(string command) => throw new NotImplementedException();
  279. public bool SendExitSignalRequest(string signalName, bool coreDumped, string errorMessage, string language) => throw new NotImplementedException();
  280. public bool SendExitStatusRequest(uint exitStatus) => throw new NotImplementedException();
  281. public bool SendKeepAliveRequest() => throw new NotImplementedException();
  282. public bool SendLocalFlowRequest(bool clientCanDo) => throw new NotImplementedException();
  283. public bool SendSignalRequest(string signalName) => throw new NotImplementedException();
  284. public bool SendSubsystemRequest(string subsystem) => throw new NotImplementedException();
  285. public bool SendWindowChangeRequest(uint columns, uint rows, uint width, uint height) => throw new NotImplementedException();
  286. public bool SendX11ForwardingRequest(bool isSingleConnection, string protocol, byte[] cookie, uint screenNumber) => throw new NotImplementedException();
  287. #pragma warning restore IDE0022 // Use block body for method
  288. #pragma warning restore IDE0025 // Use block body for property
  289. }
  290. }
  291. }