SftpFileReaderTest_ReadAheadEndInvokeException_DiscardsFurtherReadAheads.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. using System;
  2. using System.Diagnostics;
  3. using System.Threading;
  4. using Microsoft.VisualStudio.TestTools.UnitTesting;
  5. using Moq;
  6. using Renci.SshNet.Abstractions;
  7. using Renci.SshNet.Common;
  8. using Renci.SshNet.Sftp;
  9. using BufferedRead = Renci.SshNet.Sftp.SftpFileReader.BufferedRead;
  10. namespace Renci.SshNet.Tests.Classes.Sftp
  11. {
  12. /// <summary>
  13. /// Runs a reader with max. 2 pending reads.
  14. /// The read-ahead of chunk1 starts followed by the read-ahead of chunk2.
  15. /// The read-ahead of chunk1 completes successfully and the resulting chunk is read.
  16. /// The read of this first chunk allows a third ahead-head to start.
  17. /// The second read-ahead uses signals to forcefully block a failure completion until the read
  18. /// ahead of the third chunk has completed and the semaphore is waiting for a slot to start
  19. /// the read-ahead of chunk4.
  20. /// The second read does not consume check3 as it is out of order, but instead waits for
  21. /// the outcome of the read-ahead of chunk2.
  22. ///
  23. /// The completion with exception of chunk2 causes the second read to throw that same exception, and
  24. /// signals the semaphore that was waiting to start the read-ahead of chunk4. However, due to the fact
  25. /// that chunk2 completed with an exception, the read-ahead loop is stopped.
  26. /// </summary>
  27. [TestClass]
  28. public class SftpFileReaderTest_ReadAheadEndInvokeException_DiscardsFurtherReadAheads : SftpFileReaderTestBase
  29. {
  30. private const int ChunkLength = 32 * 1024;
  31. private MockSequence _seq;
  32. private byte[] _handle;
  33. private int _fileSize;
  34. private WaitHandle[] _waitHandleArray;
  35. private int _operationTimeout;
  36. private SftpCloseAsyncResult _closeAsyncResult;
  37. private byte[] _chunk1;
  38. private byte[] _chunk3;
  39. private ManualResetEvent _readAheadChunk2Completed;
  40. private ManualResetEvent _readAheadChunk3Completed;
  41. private ManualResetEvent _waitingForSemaphoreAfterCompletingChunk3;
  42. private SftpFileReader _reader;
  43. private SshException _exception;
  44. private SshException _actualException;
  45. protected override void SetupData()
  46. {
  47. var random = new Random();
  48. _handle = CreateByteArray(random, 5);
  49. _chunk1 = CreateByteArray(random, ChunkLength);
  50. _chunk3 = CreateByteArray(random, ChunkLength);
  51. _fileSize = 4 * ChunkLength;
  52. _waitHandleArray = new WaitHandle[2];
  53. _operationTimeout = random.Next(10000, 20000);
  54. _closeAsyncResult = new SftpCloseAsyncResult(null, null);
  55. _readAheadChunk2Completed = new ManualResetEvent(false);
  56. _readAheadChunk3Completed = new ManualResetEvent(false);
  57. _waitingForSemaphoreAfterCompletingChunk3 = new ManualResetEvent(false);
  58. _exception = new SshException();
  59. }
  60. protected override void SetupMocks()
  61. {
  62. _seq = new MockSequence();
  63. SftpSessionMock.InSequence(_seq)
  64. .Setup(p => p.CreateWaitHandleArray(It.IsNotNull<WaitHandle>(), It.IsNotNull<WaitHandle>()))
  65. .Returns<WaitHandle, WaitHandle>((disposingWaitHandle, semaphoreAvailableWaitHandle) =>
  66. {
  67. _waitHandleArray[0] = disposingWaitHandle;
  68. _waitHandleArray[1] = semaphoreAvailableWaitHandle;
  69. return _waitHandleArray;
  70. });
  71. SftpSessionMock.InSequence(_seq).Setup(p => p.OperationTimeout).Returns(_operationTimeout);
  72. SftpSessionMock.InSequence(_seq)
  73. .Setup(p => p.WaitAny(_waitHandleArray, _operationTimeout))
  74. .Returns(() => WaitAny(_waitHandleArray, _operationTimeout));
  75. SftpSessionMock.InSequence(_seq)
  76. .Setup(p => p.BeginRead(_handle, 0, ChunkLength, It.IsNotNull<AsyncCallback>(), It.IsAny<BufferedRead>()))
  77. .Callback<byte[], ulong, uint, AsyncCallback, object>((handle, offset, length, callback, state) =>
  78. {
  79. var asyncResult = new SftpReadAsyncResult(callback, state);
  80. asyncResult.SetAsCompleted(_chunk1, false);
  81. })
  82. .Returns((SftpReadAsyncResult)null);
  83. SftpSessionMock.InSequence(_seq).Setup(p => p.OperationTimeout).Returns(_operationTimeout);
  84. SftpSessionMock.InSequence(_seq)
  85. .Setup(p => p.WaitAny(_waitHandleArray, _operationTimeout))
  86. .Returns(() => WaitAny(_waitHandleArray, _operationTimeout));
  87. SftpSessionMock.InSequence(_seq)
  88. .Setup(p => p.BeginRead(_handle, ChunkLength, ChunkLength, It.IsNotNull<AsyncCallback>(), It.IsAny<BufferedRead>()))
  89. .Callback<byte[], ulong, uint, AsyncCallback, object>((handle, offset, length, callback, state) =>
  90. {
  91. ThreadAbstraction.ExecuteThread(() =>
  92. {
  93. // wait until the read-ahead for chunk3 has completed; this should allow
  94. // the read-ahead of chunk4 to start
  95. _readAheadChunk3Completed.WaitOne(TimeSpan.FromSeconds(3));
  96. // wait until the semaphore wait to start with chunk4 has started
  97. _waitingForSemaphoreAfterCompletingChunk3.WaitOne(TimeSpan.FromSeconds(7));
  98. // complete async read of chunk2 with exception
  99. var asyncResult = new SftpReadAsyncResult(callback, state);
  100. asyncResult.SetAsCompleted(_exception, false);
  101. // signal that read-ahead of chunk 2 has completed
  102. _readAheadChunk2Completed.Set();
  103. });
  104. })
  105. .Returns((SftpReadAsyncResult)null);
  106. SftpSessionMock.InSequence(_seq).Setup(p => p.OperationTimeout).Returns(_operationTimeout);
  107. SftpSessionMock.InSequence(_seq)
  108. .Setup(p => p.WaitAny(_waitHandleArray, _operationTimeout))
  109. .Returns(() => WaitAny(_waitHandleArray, _operationTimeout));
  110. SftpSessionMock.InSequence(_seq)
  111. .Setup(p => p.BeginRead(_handle, 2 * ChunkLength, ChunkLength, It.IsNotNull<AsyncCallback>(), It.IsAny<BufferedRead>()))
  112. .Callback<byte[], ulong, uint, AsyncCallback, object>((handle, offset, length, callback, state) =>
  113. {
  114. var asyncResult = new SftpReadAsyncResult(callback, state);
  115. asyncResult.SetAsCompleted(_chunk3, false);
  116. // signal that we've completed the read-ahead for chunk3
  117. _readAheadChunk3Completed.Set();
  118. })
  119. .Returns((SftpReadAsyncResult)null);
  120. SftpSessionMock.InSequence(_seq).Setup(p => p.OperationTimeout).Returns(_operationTimeout);
  121. SftpSessionMock.InSequence(_seq)
  122. .Setup(p => p.WaitAny(_waitHandleArray, _operationTimeout))
  123. .Callback(() => _waitingForSemaphoreAfterCompletingChunk3.Set())
  124. .Returns(() => WaitAny(_waitHandleArray, _operationTimeout));
  125. }
  126. protected override void Arrange()
  127. {
  128. base.Arrange();
  129. _reader = new SftpFileReader(_handle, SftpSessionMock.Object, ChunkLength, 2, _fileSize);
  130. }
  131. protected override void Act()
  132. {
  133. _reader.Read();
  134. try
  135. {
  136. _reader.Read();
  137. Assert.Fail();
  138. }
  139. catch (SshException ex)
  140. {
  141. _actualException = ex;
  142. }
  143. }
  144. [TestMethod]
  145. public void ReadOfSecondChunkShouldThrowExceptionThatOccurredInReadAhead()
  146. {
  147. Assert.IsNotNull(_actualException);
  148. Assert.AreSame(_exception, _actualException);
  149. }
  150. [TestMethod]
  151. public void ReahAheadOfChunk3ShouldHaveStarted()
  152. {
  153. SftpSessionMock.Verify(p => p.BeginRead(_handle, 2 * ChunkLength, ChunkLength, It.IsNotNull<AsyncCallback>(), It.IsAny<BufferedRead>()), Times.Once);
  154. }
  155. [TestMethod]
  156. public void ReadAfterReadAheadExceptionShouldRethrowExceptionThatOccurredInReadAhead()
  157. {
  158. try
  159. {
  160. _reader.Read();
  161. Assert.Fail();
  162. }
  163. catch (SshException ex)
  164. {
  165. Assert.AreSame(_exception, ex);
  166. }
  167. }
  168. [TestMethod]
  169. public void WaitAnyOFSftpSessionShouldHaveBeenInvokedFourTimes()
  170. {
  171. SftpSessionMock.Verify(p => p.WaitAny(_waitHandleArray, _operationTimeout), Times.Exactly(4));
  172. }
  173. [TestMethod]
  174. public void DisposeShouldCloseHandleAndCompleteImmediately()
  175. {
  176. SftpSessionMock.InSequence(_seq).Setup(p => p.IsOpen).Returns(true);
  177. SftpSessionMock.InSequence(_seq).Setup(p => p.BeginClose(_handle, null, null)).Returns(_closeAsyncResult);
  178. SftpSessionMock.InSequence(_seq).Setup(p => p.EndClose(_closeAsyncResult));
  179. var stopwatch = Stopwatch.StartNew();
  180. _reader.Dispose();
  181. stopwatch.Stop();
  182. Assert.IsTrue(stopwatch.ElapsedMilliseconds < 200, "Dispose took too long to complete: " + stopwatch.ElapsedMilliseconds);
  183. SftpSessionMock.Verify(p => p.IsOpen, Times.Once);
  184. SftpSessionMock.Verify(p => p.BeginClose(_handle, null, null), Times.Once);
  185. SftpSessionMock.Verify(p => p.EndClose(_closeAsyncResult), Times.Once);
  186. }
  187. }
  188. }