SftpFileStreamTest.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. using System;
  2. using System.IO;
  3. using System.Linq;
  4. using System.Threading;
  5. using System.Threading.Tasks;
  6. using Microsoft.VisualStudio.TestTools.UnitTesting;
  7. using Moq;
  8. using Renci.SshNet.Common;
  9. using Renci.SshNet.Sftp;
  10. using Renci.SshNet.Sftp.Responses;
  11. namespace Renci.SshNet.Tests.Classes.Sftp
  12. {
  13. [TestClass]
  14. public class SftpFileStreamTest
  15. {
  16. [DataTestMethod]
  17. [DataRow(false)]
  18. [DataRow(true)]
  19. public async Task BadFileMode_ThrowsArgumentOutOfRangeException(bool isAsync)
  20. {
  21. ArgumentOutOfRangeException ex;
  22. if (isAsync)
  23. {
  24. ex = await Assert.ThrowsAsync<ArgumentOutOfRangeException>(() =>
  25. SftpFileStream.OpenAsync(new Mock<ISftpSession>().Object, "file.txt", mode: 0, FileAccess.Read, bufferSize: 1024, CancellationToken.None));
  26. }
  27. else
  28. {
  29. ex = Assert.Throws<ArgumentOutOfRangeException>(() =>
  30. SftpFileStream.Open(new Mock<ISftpSession>().Object, "file.txt", mode: 0, FileAccess.Read, bufferSize: 1024));
  31. }
  32. Assert.AreEqual("mode", ex.ParamName);
  33. }
  34. [DataTestMethod]
  35. [DataRow(false)]
  36. [DataRow(true)]
  37. public async Task BadFileAccess_ThrowsArgumentOutOfRangeException(bool isAsync)
  38. {
  39. ArgumentOutOfRangeException ex;
  40. if (isAsync)
  41. {
  42. ex = await Assert.ThrowsAsync<ArgumentOutOfRangeException>(() =>
  43. SftpFileStream.OpenAsync(new Mock<ISftpSession>().Object, "file.txt", FileMode.Open, access: 0, bufferSize: 1024, CancellationToken.None));
  44. }
  45. else
  46. {
  47. ex = Assert.Throws<ArgumentOutOfRangeException>(() =>
  48. SftpFileStream.Open(new Mock<ISftpSession>().Object, "file.txt", FileMode.Open, access: 0, bufferSize: 1024));
  49. }
  50. Assert.AreEqual("access", ex.ParamName);
  51. }
  52. [TestMethod]
  53. [DataRow(FileMode.Append, FileAccess.Read, false)]
  54. [DataRow(FileMode.Append, FileAccess.Read, true)]
  55. [DataRow(FileMode.Append, FileAccess.ReadWrite, false)]
  56. [DataRow(FileMode.Append, FileAccess.ReadWrite, true)]
  57. [DataRow(FileMode.Create, FileAccess.Read, false)]
  58. [DataRow(FileMode.Create, FileAccess.Read, true)]
  59. [DataRow(FileMode.CreateNew, FileAccess.Read, false)]
  60. [DataRow(FileMode.CreateNew, FileAccess.Read, true)]
  61. [DataRow(FileMode.Truncate, FileAccess.Read, false)]
  62. [DataRow(FileMode.Truncate, FileAccess.Read, true)]
  63. public async Task InvalidModeAccessCombination_ThrowsArgumentException(FileMode mode, FileAccess access, bool isAsync)
  64. {
  65. ArgumentException ex;
  66. if (isAsync)
  67. {
  68. ex = await Assert.ThrowsAsync<ArgumentException>(() =>
  69. SftpFileStream.OpenAsync(new Mock<ISftpSession>().Object, "file.txt", mode, access, bufferSize: 1024, CancellationToken.None));
  70. }
  71. else
  72. {
  73. ex = Assert.Throws<ArgumentException>(() =>
  74. SftpFileStream.Open(new Mock<ISftpSession>().Object, "file.txt", mode, access, bufferSize: 1024));
  75. }
  76. Assert.AreEqual("mode", ex.ParamName);
  77. }
  78. [TestMethod]
  79. public void ReadWithWriteAccess_ThrowsNotSupportedException()
  80. {
  81. var sessionMock = new Mock<ISftpSession>();
  82. sessionMock.Setup(s => s.IsOpen).Returns(true);
  83. SetupRemoteSize(sessionMock, 128);
  84. var s = SftpFileStream.Open(sessionMock.Object, "file.txt", FileMode.Create, FileAccess.Write, bufferSize: 1024);
  85. Assert.IsFalse(s.CanRead);
  86. Assert.Throws<NotSupportedException>(() => _ = s.Read(new byte[4], 0, 4));
  87. Assert.Throws<NotSupportedException>(() => _ = s.ReadByte());
  88. Assert.Throws<NotSupportedException>(() => _ = s.ReadAsync(new byte[4], 0, 4).GetAwaiter().GetResult());
  89. Assert.Throws<NotSupportedException>(() => _ = s.EndRead(s.BeginRead(new byte[4], 0, 4, null, null)));
  90. #if NET
  91. Assert.Throws<NotSupportedException>(() => _ = s.Read(new byte[4]));
  92. Assert.Throws<NotSupportedException>(() => _ = s.ReadAsync(new byte[4]).AsTask().GetAwaiter().GetResult());
  93. #endif
  94. Assert.Throws<NotSupportedException>(() => s.CopyTo(Stream.Null));
  95. Assert.Throws<NotSupportedException>(() => s.CopyToAsync(Stream.Null).GetAwaiter().GetResult());
  96. }
  97. [TestMethod]
  98. public void WriteWithReadAccess_ThrowsNotSupportedException()
  99. {
  100. var sessionMock = new Mock<ISftpSession>();
  101. sessionMock.Setup(s => s.IsOpen).Returns(true);
  102. var s = SftpFileStream.Open(sessionMock.Object, "file.txt", FileMode.Open, FileAccess.Read, bufferSize: 1024);
  103. Assert.IsFalse(s.CanWrite);
  104. Assert.Throws<NotSupportedException>(() => s.Write(new byte[4], 0, 4));
  105. Assert.Throws<NotSupportedException>(() => s.WriteByte(0xf));
  106. Assert.Throws<NotSupportedException>(() => s.WriteAsync(new byte[4], 0, 4).GetAwaiter().GetResult());
  107. Assert.Throws<NotSupportedException>(() => s.EndWrite(s.BeginWrite(new byte[4], 0, 4, null, null)));
  108. #if NET
  109. Assert.Throws<NotSupportedException>(() => s.Write(new byte[4]));
  110. Assert.Throws<NotSupportedException>(() => s.WriteAsync(new byte[4]).AsTask().GetAwaiter().GetResult());
  111. #endif
  112. Assert.Throws<NotSupportedException>(() => s.SetLength(1024));
  113. }
  114. [Ignore("TODO Currently throws EndOfStreamException in all cases.")]
  115. [TestMethod]
  116. [DataRow(-1, SeekOrigin.Begin)]
  117. [DataRow(-1, SeekOrigin.Current)]
  118. [DataRow(-1000, SeekOrigin.End)]
  119. public void SeekBeforeBeginning_ThrowsIOException(long offset, SeekOrigin origin)
  120. {
  121. var sessionMock = new Mock<ISftpSession>();
  122. sessionMock.Setup(s => s.IsOpen).Returns(true);
  123. SetupRemoteSize(sessionMock, 128);
  124. var s = SftpFileStream.Open(sessionMock.Object, "file.txt", FileMode.Open, FileAccess.Read, bufferSize: 1024);
  125. Assert.Throws<IOException>(() => s.Seek(offset, origin));
  126. }
  127. private static void SetupRemoteSize(Mock<ISftpSession> sessionMock, long size)
  128. {
  129. sessionMock.Setup(s => s.RequestFStat(It.IsAny<byte[]>(), It.IsAny<bool>())).Returns(new SftpFileAttributes(
  130. default, default, size: size, default, default, default, default
  131. ));
  132. }
  133. // Operations which should cause writes to be flushed because they depend on
  134. // the remote file being up to date.
  135. // Most of these are already implicitly covered by integration tests and may
  136. // not be so valuable here.
  137. [TestMethod]
  138. public void Flush_SendsBufferedWrites()
  139. {
  140. TestSendsBufferedWrites(s => s.Flush());
  141. }
  142. [TestMethod]
  143. public void Read_SendsBufferedWrites()
  144. {
  145. TestSendsBufferedWrites(s => _ = s.Read(new byte[16], 0, 16));
  146. }
  147. [TestMethod]
  148. public void Seek_SendsBufferedWrites()
  149. {
  150. TestSendsBufferedWrites(s => _ = s.Seek(-1, SeekOrigin.Current));
  151. }
  152. [TestMethod]
  153. public void SetPosition_SendsBufferedWrites()
  154. {
  155. TestSendsBufferedWrites(s => s.Position++);
  156. }
  157. [TestMethod]
  158. public void SetLength_SendsBufferedWrites()
  159. {
  160. TestSendsBufferedWrites(s => s.SetLength(256));
  161. }
  162. [TestMethod]
  163. public void GetLength_SendsBufferedWrites()
  164. {
  165. TestSendsBufferedWrites(s => _ = s.Length);
  166. }
  167. [TestMethod]
  168. public void Dispose_SendsBufferedWrites()
  169. {
  170. TestSendsBufferedWrites(s => s.Dispose());
  171. }
  172. private void TestSendsBufferedWrites(Action<SftpFileStream> flushAction)
  173. {
  174. var sessionMock = new Mock<ISftpSession>();
  175. sessionMock.Setup(s => s.CalculateOptimalWriteLength(It.IsAny<uint>(), It.IsAny<byte[]>())).Returns<uint, byte[]>((x, _) => x);
  176. sessionMock.Setup(s => s.IsOpen).Returns(true);
  177. SetupRemoteSize(sessionMock, 0);
  178. var s = SftpFileStream.Open(sessionMock.Object, "file.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite, bufferSize: 1024);
  179. // Buffer some data
  180. byte[] newData = "Some new bytes"u8.ToArray();
  181. s.Write(newData, 0, newData.Length);
  182. byte[] newData2 = "Some more bytes"u8.ToArray();
  183. s.Write(newData2, 0, newData2.Length);
  184. // The written data does not exceed bufferSize so we do not expect
  185. // it to have been sent.
  186. sessionMock.Verify(s => s.RequestWrite(
  187. It.IsAny<byte[]>(),
  188. It.IsAny<ulong>(),
  189. It.IsAny<byte[]>(),
  190. It.IsAny<int>(),
  191. It.IsAny<int>(),
  192. It.IsAny<AutoResetEvent>(),
  193. It.IsAny<Action<SftpStatusResponse>>()),
  194. Times.Never);
  195. // Whatever is called here should trigger the bytes to be sent
  196. flushAction(s);
  197. VerifyRequestWrite(sessionMock, newData.Concat(newData2), serverOffset: 0);
  198. }
  199. [TestMethod]
  200. public void Dispose()
  201. {
  202. var sessionMock = new Mock<ISftpSession>();
  203. sessionMock.Setup(s => s.IsOpen).Returns(true);
  204. var s = SftpFileStream.Open(sessionMock.Object, "file.txt", FileMode.Create, FileAccess.ReadWrite, bufferSize: 1024);
  205. Assert.IsTrue(s.CanRead);
  206. Assert.IsTrue(s.CanSeek);
  207. Assert.IsTrue(s.CanWrite);
  208. s.Dispose();
  209. sessionMock.Verify(p => p.RequestClose(It.IsAny<byte[]>()), Times.Once);
  210. Assert.IsFalse(s.CanRead);
  211. Assert.IsFalse(s.CanSeek);
  212. Assert.IsFalse(s.CanWrite);
  213. Assert.Throws<ObjectDisposedException>(() => s.Read(new byte[16], 0, 16));
  214. Assert.Throws<ObjectDisposedException>(() => s.ReadByte());
  215. Assert.Throws<ObjectDisposedException>(() => s.Write(new byte[16], 0, 16));
  216. Assert.Throws<ObjectDisposedException>(() => s.WriteByte(0xf));
  217. Assert.Throws<ObjectDisposedException>(() => s.CopyTo(Stream.Null));
  218. Assert.Throws<ObjectDisposedException>(s.Flush);
  219. Assert.Throws<ObjectDisposedException>(() => s.Seek(0, SeekOrigin.Begin));
  220. Assert.Throws<ObjectDisposedException>(() => s.SetLength(128));
  221. Assert.Throws<ObjectDisposedException>(() => _ = s.Length);
  222. // Test no-op second dispose
  223. s.Dispose();
  224. sessionMock.Verify(p => p.RequestClose(It.IsAny<byte[]>()), Times.Once);
  225. }
  226. private static void VerifyRequestWrite(Mock<ISftpSession> sessionMock, ReadOnlyMemory<byte> newData, int serverOffset)
  227. {
  228. sessionMock.Verify(s => s.RequestWrite(
  229. /* handle: */ It.IsAny<byte[]>(),
  230. /* serverOffset: */ (ulong)serverOffset,
  231. /* data: */ It.Is<byte[]>(x => IndexOf(x, newData) >= 0),
  232. /* offset: */ It.IsAny<int>(),
  233. /* length: */ newData.Length,
  234. /* wait: */ It.IsAny<AutoResetEvent>(),
  235. /* writeCompleted: */ It.IsAny<Action<SftpStatusResponse>>()),
  236. Times.Once);
  237. }
  238. private static int IndexOf(byte[] searchSpace, ReadOnlyMemory<byte> searchValue)
  239. {
  240. // Needed in a (non-local) function because expression lambdas can't contain spans
  241. return searchSpace.AsSpan().IndexOf(searchValue.Span);
  242. }
  243. }
  244. }