diff --git a/.editorconfig_soon b/.editorconfig similarity index 99% rename from .editorconfig_soon rename to .editorconfig index d0edd58e3..62aefca2e 100644 --- a/.editorconfig_soon +++ b/.editorconfig @@ -535,6 +535,11 @@ dotnet_diagnostic.IDE0045.severity = none # Configured using 'dotnet_style_prefer_conditional_expression_over_return' dotnet_diagnostic.IDE0046.severity = suggestion +# IDE0047: Remove unnecessary parentheses +# +# Removing "unnecessary" parentheses is not always a clear win for readability. +dotnet_diagnostic.IDE0047.severity = suggestion + # IDE0055: Fix formatting # # When enabled, diagnostics are reported for indented object initializers. @@ -547,6 +552,12 @@ dotnet_diagnostic.IDE0046.severity = suggestion # There are no settings to configure this correctly, unless https://github.com/dotnet/roslyn/issues/63256 (or similar) is ever implemented. dotnet_diagnostic.IDE0055.severity = none +# IDE0130: Namespace does not match folder structure +# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0130 +# +# TODO: Remove when https://github.com/sshnet/SSH.NET/issues/1129 is fixed +dotnet_diagnostic.IDE0130.severity = none + # IDE0270: Null check can be simplified # # var inputPath = originalDossierPathList.Find(x => x.id == updatedPath.id); diff --git a/Directory.Build.props b/Directory.Build.props index 4fd6964ad..a4f567fdb 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -9,10 +9,8 @@ $(MSBuildThisFileDirectory)src\Renci.SshNet.snk true latest - false diff --git a/src/Renci.SshNet.Tests/.editorconfig b/src/Renci.SshNet.Tests/.editorconfig new file mode 100644 index 000000000..b94e29112 --- /dev/null +++ b/src/Renci.SshNet.Tests/.editorconfig @@ -0,0 +1,32 @@ +[*.cs] + +#### SYSLIB diagnostics #### + +# SYSLIB1045: Use 'GeneratedRegexAttribute' to generate the regular expression implementation at compile-time +# +# TODO: Remove this when https://github.com/sshnet/SSH.NET/issues/1131 is implemented. +dotnet_diagnostic.SYSLIB1045.severity = none + +### StyleCop Analyzers rules ### + +#### .NET Compiler Platform analysers rules #### + +# IDE0007: Use var instead of explicit type +# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0007 +dotnet_diagnostic.IDE0007.severity = suggestion + +# IDE0028: Use collection initializers +# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0028 +dotnet_diagnostic.IDE0028.severity = suggestion + +# IDE0058: Remove unnecessary expression value +# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0058 +dotnet_diagnostic.IDE0058.severity = suggestion + +# IDE0059: Remove unnecessary value assignment +# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0059 +dotnet_diagnostic.IDE0059.severity = suggestion + +# IDE0230: Use UTF-8 string literal +# https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/ide0230 +dotnet_diagnostic.IDE0230.severity = suggestion diff --git a/src/Renci.SshNet.Tests/Classes/BaseClientTestBase.cs b/src/Renci.SshNet.Tests/Classes/BaseClientTestBase.cs index 2cce2e918..7c6c58388 100644 --- a/src/Renci.SshNet.Tests/Classes/BaseClientTestBase.cs +++ b/src/Renci.SshNet.Tests/Classes/BaseClientTestBase.cs @@ -6,15 +6,15 @@ namespace Renci.SshNet.Tests.Classes { public abstract class BaseClientTestBase : TripleATestBase { - internal Mock _serviceFactoryMock { get; private set; } - internal Mock _socketFactoryMock { get; private set; } - internal Mock _sessionMock { get; private set; } + internal Mock ServiceFactoryMock { get; private set; } + internal Mock SocketFactoryMock { get; private set; } + internal Mock SessionMock { get; private set; } protected virtual void CreateMocks() { - _serviceFactoryMock = new Mock(MockBehavior.Strict); - _socketFactoryMock = new Mock(MockBehavior.Strict); - _sessionMock = new Mock(MockBehavior.Strict); + ServiceFactoryMock = new Mock(MockBehavior.Strict); + SocketFactoryMock = new Mock(MockBehavior.Strict); + SessionMock = new Mock(MockBehavior.Strict); } protected virtual void SetupData() diff --git a/src/Renci.SshNet.Tests/Classes/BaseClientTest_Connect_OnConnectedThrowsException.cs b/src/Renci.SshNet.Tests/Classes/BaseClientTest_Connect_OnConnectedThrowsException.cs index e21f516dc..f2a30bbe2 100644 --- a/src/Renci.SshNet.Tests/Classes/BaseClientTest_Connect_OnConnectedThrowsException.cs +++ b/src/Renci.SshNet.Tests/Classes/BaseClientTest_Connect_OnConnectedThrowsException.cs @@ -24,20 +24,20 @@ protected override void SetupData() protected override void SetupMocks() { - _serviceFactoryMock.Setup(p => p.CreateSocketFactory()) - .Returns(_socketFactoryMock.Object); - _serviceFactoryMock.Setup(p => p.CreateSession(_connectionInfo, _socketFactoryMock.Object)) - .Returns(_sessionMock.Object); - _sessionMock.Setup(p => p.Connect()); - _sessionMock.Setup(p => p.Dispose()); + ServiceFactoryMock.Setup(p => p.CreateSocketFactory()) + .Returns(SocketFactoryMock.Object); + ServiceFactoryMock.Setup(p => p.CreateSession(_connectionInfo, SocketFactoryMock.Object)) + .Returns(SessionMock.Object); + SessionMock.Setup(p => p.Connect()); + SessionMock.Setup(p => p.Dispose()); } protected override void TearDown() { if (_client != null) { - _sessionMock.Setup(p => p.OnDisconnecting()); - _sessionMock.Setup(p => p.Dispose()); + SessionMock.Setup(p => p.OnDisconnecting()); + SessionMock.Setup(p => p.Dispose()); _client.Dispose(); } } @@ -46,7 +46,7 @@ protected override void Arrange() { base.Arrange(); - _client = new MyClient(_connectionInfo, false, _serviceFactoryMock.Object) + _client = new MyClient(_connectionInfo, false, ServiceFactoryMock.Object) { OnConnectedException = _onConnectException }; @@ -75,26 +75,26 @@ public void ConnectShouldRethrowExceptionThrownByOnConnect() [TestMethod] public void CreateSocketFactoryOnServiceFactoryShouldBeInvokedOnce() { - _serviceFactoryMock.Verify(p => p.CreateSocketFactory(), Times.Once); + ServiceFactoryMock.Verify(p => p.CreateSocketFactory(), Times.Once); } [TestMethod] public void CreateSessionOnServiceFactoryShouldBeInvokedOnce() { - _serviceFactoryMock.Verify(p => p.CreateSession(_connectionInfo, _socketFactoryMock.Object), + ServiceFactoryMock.Verify(p => p.CreateSession(_connectionInfo, SocketFactoryMock.Object), Times.Once); } [TestMethod] public void ConnectOnSessionShouldBeInvokedOnce() { - _sessionMock.Verify(p => p.Connect(), Times.Once); + SessionMock.Verify(p => p.Connect(), Times.Once); } [TestMethod] public void DisposeOnSessionShouldBeInvokedOnce() { - _sessionMock.Verify(p => p.Dispose(), Times.Once); + SessionMock.Verify(p => p.Dispose(), Times.Once); } [TestMethod] @@ -104,7 +104,7 @@ public void ErrorOccuredOnSessionShouldNoLongerBeSignaledViaErrorOccurredOnBaseC _client.ErrorOccurred += (sender, args) => Interlocked.Increment(ref errorOccurredSignalCount); - _sessionMock.Raise(p => p.ErrorOccured += null, new ExceptionEventArgs(new Exception())); + SessionMock.Raise(p => p.ErrorOccured += null, new ExceptionEventArgs(new Exception())); Assert.AreEqual(0, errorOccurredSignalCount); } @@ -116,7 +116,7 @@ public void HostKeyReceivedOnSessionShouldNoLongerBeSignaledViaHostKeyReceivedOn _client.HostKeyReceived += (sender, args) => Interlocked.Increment(ref hostKeyReceivedSignalCount); - _sessionMock.Raise(p => p.HostKeyReceived += null, new HostKeyEventArgs(GetKeyHostAlgorithm())); + SessionMock.Raise(p => p.HostKeyReceived += null, new HostKeyEventArgs(GetKeyHostAlgorithm())); Assert.AreEqual(0, hostKeyReceivedSignalCount); } diff --git a/src/Renci.SshNet.Tests/Classes/BaseClientTest_Connected_KeepAliveInterval_NegativeOne.cs b/src/Renci.SshNet.Tests/Classes/BaseClientTest_Connected_KeepAliveInterval_NegativeOne.cs index 46d730119..4f98bde82 100644 --- a/src/Renci.SshNet.Tests/Classes/BaseClientTest_Connected_KeepAliveInterval_NegativeOne.cs +++ b/src/Renci.SshNet.Tests/Classes/BaseClientTest_Connected_KeepAliveInterval_NegativeOne.cs @@ -1,8 +1,10 @@ using System; using System.Threading; + using Microsoft.VisualStudio.TestTools.UnitTesting; + using Moq; -using Renci.SshNet.Connection; + using Renci.SshNet.Messages.Transport; namespace Renci.SshNet.Tests.Classes @@ -24,22 +26,23 @@ protected override void SetupData() protected override void SetupMocks() { - _serviceFactoryMock.Setup(p => p.CreateSocketFactory()) - .Returns(_socketFactoryMock.Object); - _serviceFactoryMock.Setup(p => p.CreateSession(_connectionInfo, _socketFactoryMock.Object)) - .Returns(_sessionMock.Object); - _sessionMock.Setup(p => p.Connect()); - _sessionMock.Setup(p => p.IsConnected).Returns(true); - _sessionMock.Setup(p => p.TrySendMessage(It.IsAny())) - .Returns(true) - .Callback(() => Interlocked.Increment(ref _keepAliveCount)); + _ = ServiceFactoryMock.Setup(p => p.CreateSocketFactory()) + .Returns(SocketFactoryMock.Object); + _ = ServiceFactoryMock.Setup(p => p.CreateSession(_connectionInfo, SocketFactoryMock.Object)) + .Returns(SessionMock.Object); + _ = SessionMock.Setup(p => p.Connect()); + _ = SessionMock.Setup(p => p.IsConnected) + .Returns(true); + _ = SessionMock.Setup(p => p.TrySendMessage(It.IsAny())) + .Returns(true) + .Callback(() => Interlocked.Increment(ref _keepAliveCount)); } protected override void Arrange() { base.Arrange(); - _client = new MyClient(_connectionInfo, false, _serviceFactoryMock.Object); + _client = new MyClient(_connectionInfo, false, ServiceFactoryMock.Object); _client.Connect(); _client.KeepAliveInterval = _keepAliveInterval; } @@ -48,8 +51,8 @@ protected override void TearDown() { if (_client != null) { - _sessionMock.Setup(p => p.OnDisconnecting()); - _sessionMock.Setup(p => p.Dispose()); + SessionMock.Setup(p => p.OnDisconnecting()); + SessionMock.Setup(p => p.Dispose()); _client.Dispose(); } } @@ -72,25 +75,25 @@ public void KeepAliveIntervalShouldReturnConfiguredValue() [TestMethod] public void CreateSocketFactoryOnServiceFactoryShouldBeInvokedOnce() { - _serviceFactoryMock.Verify(p => p.CreateSocketFactory(), Times.Once); + ServiceFactoryMock.Verify(p => p.CreateSocketFactory(), Times.Once); } [TestMethod] public void CreateSessionOnServiceFactoryShouldBeInvokedOnce() { - _serviceFactoryMock.Verify(p => p.CreateSession(_connectionInfo, _socketFactoryMock.Object), Times.Once); + ServiceFactoryMock.Verify(p => p.CreateSession(_connectionInfo, SocketFactoryMock.Object), Times.Once); } [TestMethod] public void ConnectOnSessionShouldBeInvokedOnce() { - _sessionMock.Verify(p => p.Connect(), Times.Once); + SessionMock.Verify(p => p.Connect(), Times.Once); } [TestMethod] public void IsConnectedOnSessionShouldBeInvokedOnce() { - _sessionMock.Verify(p => p.IsConnected, Times.Once); + SessionMock.Verify(p => p.IsConnected, Times.Once); } [TestMethod] @@ -99,7 +102,7 @@ public void SendMessageOnSessionShouldBeInvokedOneTime() // allow keep-alive to be sent once Thread.Sleep(100); - _sessionMock.Verify(p => p.TrySendMessage(It.IsAny()), Times.Exactly(1)); + SessionMock.Verify(p => p.TrySendMessage(It.IsAny()), Times.Exactly(1)); } private class MyClient : BaseClient diff --git a/src/Renci.SshNet.Tests/Classes/BaseClientTest_Connected_KeepAliveInterval_NotNegativeOne.cs b/src/Renci.SshNet.Tests/Classes/BaseClientTest_Connected_KeepAliveInterval_NotNegativeOne.cs index b9c50e76d..2afb84609 100644 --- a/src/Renci.SshNet.Tests/Classes/BaseClientTest_Connected_KeepAliveInterval_NotNegativeOne.cs +++ b/src/Renci.SshNet.Tests/Classes/BaseClientTest_Connected_KeepAliveInterval_NotNegativeOne.cs @@ -23,13 +23,13 @@ protected override void SetupData() protected override void SetupMocks() { - _serviceFactoryMock.Setup(p => p.CreateSocketFactory()) - .Returns(_socketFactoryMock.Object); - _serviceFactoryMock.Setup(p => p.CreateSession(_connectionInfo, _socketFactoryMock.Object)) - .Returns(_sessionMock.Object); - _sessionMock.Setup(p => p.Connect()); - _sessionMock.Setup(p => p.IsConnected).Returns(true); - _sessionMock.Setup(p => p.TrySendMessage(It.IsAny())) + ServiceFactoryMock.Setup(p => p.CreateSocketFactory()) + .Returns(SocketFactoryMock.Object); + ServiceFactoryMock.Setup(p => p.CreateSession(_connectionInfo, SocketFactoryMock.Object)) + .Returns(SessionMock.Object); + SessionMock.Setup(p => p.Connect()); + SessionMock.Setup(p => p.IsConnected).Returns(true); + SessionMock.Setup(p => p.TrySendMessage(It.IsAny())) .Returns(true) .Callback(() => Interlocked.Increment(ref _keepAliveCount)); } @@ -38,7 +38,7 @@ protected override void Arrange() { base.Arrange(); - _client = new MyClient(_connectionInfo, false, _serviceFactoryMock.Object); + _client = new MyClient(_connectionInfo, false, ServiceFactoryMock.Object); _client.Connect(); } @@ -46,8 +46,8 @@ protected override void TearDown() { if (_client != null) { - _sessionMock.Setup(p => p.OnDisconnecting()); - _sessionMock.Setup(p => p.Dispose()); + SessionMock.Setup(p => p.OnDisconnecting()); + SessionMock.Setup(p => p.Dispose()); _client.Dispose(); } } @@ -74,32 +74,32 @@ public void KeepAliveIntervalShouldReturnConfiguredValue() [TestMethod] public void CreateSocketFactoryOnServiceFactoryShouldBeInvokedOnce() { - _serviceFactoryMock.Verify(p => p.CreateSocketFactory(), Times.Once); + ServiceFactoryMock.Verify(p => p.CreateSocketFactory(), Times.Once); } [TestMethod] public void CreateSessionOnServiceFactoryShouldBeInvokedOnce() { - _serviceFactoryMock.Verify(p => p.CreateSession(_connectionInfo, _socketFactoryMock.Object), + ServiceFactoryMock.Verify(p => p.CreateSession(_connectionInfo, SocketFactoryMock.Object), Times.Once); } [TestMethod] public void ConnectOnSessionShouldBeInvokedOnce() { - _sessionMock.Verify(p => p.Connect(), Times.Once); + SessionMock.Verify(p => p.Connect(), Times.Once); } [TestMethod] public void IsConnectedOnSessionShouldBeInvokedOnce() { - _sessionMock.Verify(p => p.IsConnected, Times.Once); + SessionMock.Verify(p => p.IsConnected, Times.Once); } [TestMethod] public void SendMessageOnSessionShouldBeInvokedThreeTimes() { - _sessionMock.Verify(p => p.TrySendMessage(It.IsAny()), Times.Exactly(3)); + SessionMock.Verify(p => p.TrySendMessage(It.IsAny()), Times.Exactly(3)); } private class MyClient : BaseClient diff --git a/src/Renci.SshNet.Tests/Classes/BaseClientTest_Connected_KeepAlivesNotSentConcurrently.cs b/src/Renci.SshNet.Tests/Classes/BaseClientTest_Connected_KeepAlivesNotSentConcurrently.cs index 25d6ec7c0..ac0539e98 100644 --- a/src/Renci.SshNet.Tests/Classes/BaseClientTest_Connected_KeepAlivesNotSentConcurrently.cs +++ b/src/Renci.SshNet.Tests/Classes/BaseClientTest_Connected_KeepAlivesNotSentConcurrently.cs @@ -24,15 +24,15 @@ protected override void SetupMocks() { _mockSequence = new MockSequence(); - _serviceFactoryMock.InSequence(_mockSequence) + ServiceFactoryMock.InSequence(_mockSequence) .Setup(p => p.CreateSocketFactory()) - .Returns(_socketFactoryMock.Object); - _serviceFactoryMock.InSequence(_mockSequence) - .Setup(p => p.CreateSession(_connectionInfo, _socketFactoryMock.Object)) - .Returns(_sessionMock.Object); - _sessionMock.InSequence(_mockSequence) + .Returns(SocketFactoryMock.Object); + ServiceFactoryMock.InSequence(_mockSequence) + .Setup(p => p.CreateSession(_connectionInfo, SocketFactoryMock.Object)) + .Returns(SessionMock.Object); + SessionMock.InSequence(_mockSequence) .Setup(p => p.Connect()); - _sessionMock.InSequence(_mockSequence) + SessionMock.InSequence(_mockSequence) .Setup(p => p.TrySendMessage(It.IsAny())) .Returns(true) .Callback(() => @@ -46,7 +46,7 @@ protected override void Arrange() { base.Arrange(); - _client = new MyClient(_connectionInfo, false, _serviceFactoryMock.Object) + _client = new MyClient(_connectionInfo, false, ServiceFactoryMock.Object) { KeepAliveInterval = TimeSpan.FromMilliseconds(50d) }; @@ -57,8 +57,8 @@ protected override void TearDown() { if (_client != null) { - _sessionMock.InSequence(_mockSequence).Setup(p => p.OnDisconnecting()); - _sessionMock.InSequence(_mockSequence).Setup(p => p.Dispose()); + SessionMock.InSequence(_mockSequence).Setup(p => p.OnDisconnecting()); + SessionMock.InSequence(_mockSequence).Setup(p => p.Dispose()); _client.Dispose(); } } @@ -79,7 +79,7 @@ protected override void Act() [TestMethod] public void SendMessageOnSessionShouldBeInvokedOnce() { - _sessionMock.Verify(p => p.TrySendMessage(It.IsAny()), Times.Once); + SessionMock.Verify(p => p.TrySendMessage(It.IsAny()), Times.Once); } private class MyClient : BaseClient diff --git a/src/Renci.SshNet.Tests/Classes/BaseClientTest_Disconnected_Connect.cs b/src/Renci.SshNet.Tests/Classes/BaseClientTest_Disconnected_Connect.cs index 51cd2d81e..ebde0c20c 100644 --- a/src/Renci.SshNet.Tests/Classes/BaseClientTest_Disconnected_Connect.cs +++ b/src/Renci.SshNet.Tests/Classes/BaseClientTest_Disconnected_Connect.cs @@ -29,22 +29,22 @@ protected override void SetupMocks() { var sequence = new MockSequence(); - _serviceFactoryMock.InSequence(sequence) + ServiceFactoryMock.InSequence(sequence) .Setup(p => p.CreateSocketFactory()) - .Returns(_socketFactoryMock.Object); - _serviceFactoryMock.InSequence(sequence) - .Setup(p => p.CreateSession(_connectionInfo, _socketFactoryMock.Object)) - .Returns(_sessionMock.Object); - _sessionMock.InSequence(sequence) + .Returns(SocketFactoryMock.Object); + ServiceFactoryMock.InSequence(sequence) + .Setup(p => p.CreateSession(_connectionInfo, SocketFactoryMock.Object)) + .Returns(SessionMock.Object); + SessionMock.InSequence(sequence) .Setup(p => p.Connect()); - _sessionMock.InSequence(sequence) + SessionMock.InSequence(sequence) .Setup(p => p.OnDisconnecting()); - _sessionMock.InSequence(sequence) + SessionMock.InSequence(sequence) .Setup(p => p.Dispose()); - _serviceFactoryMock.InSequence(sequence) + ServiceFactoryMock.InSequence(sequence) .Setup(p => p.CreateSocketFactory()) .Returns(_socketFactory2Mock.Object); - _serviceFactoryMock.InSequence(sequence) + ServiceFactoryMock.InSequence(sequence) .Setup(p => p.CreateSession(_connectionInfo, _socketFactory2Mock.Object)) .Returns(_session2Mock.Object); _session2Mock.InSequence(sequence) @@ -55,7 +55,7 @@ protected override void Arrange() { base.Arrange(); - _client = new MyClient(_connectionInfo, false, _serviceFactoryMock.Object); + _client = new MyClient(_connectionInfo, false, ServiceFactoryMock.Object); _client.Connect(); _client.Disconnect(); } @@ -78,22 +78,22 @@ protected override void Act() [TestMethod] public void CreateSocketFactoryOnServiceFactoryShouldBeInvokedTwic() { - _serviceFactoryMock.Verify(p => p.CreateSocketFactory(), Times.Exactly(2)); + ServiceFactoryMock.Verify(p => p.CreateSocketFactory(), Times.Exactly(2)); } [TestMethod] public void CreateSessionOnServiceFactoryShouldBeInvokedTwice() { - _serviceFactoryMock.Verify(p => p.CreateSession(_connectionInfo, _socketFactoryMock.Object), + ServiceFactoryMock.Verify(p => p.CreateSession(_connectionInfo, SocketFactoryMock.Object), Times.Once); - _serviceFactoryMock.Verify(p => p.CreateSession(_connectionInfo, _socketFactory2Mock.Object), + ServiceFactoryMock.Verify(p => p.CreateSession(_connectionInfo, _socketFactory2Mock.Object), Times.Once); } [TestMethod] public void ConnectOnSessionShouldBeInvokedTwice() { - _sessionMock.Verify(p => p.Connect(), Times.Once); + SessionMock.Verify(p => p.Connect(), Times.Once); _session2Mock.Verify(p => p.Connect(), Times.Once); } diff --git a/src/Renci.SshNet.Tests/Classes/BaseClientTest_Disconnected_KeepAliveInterval_NotNegativeOne.cs b/src/Renci.SshNet.Tests/Classes/BaseClientTest_Disconnected_KeepAliveInterval_NotNegativeOne.cs index 1ca4b19d5..e026d09b8 100644 --- a/src/Renci.SshNet.Tests/Classes/BaseClientTest_Disconnected_KeepAliveInterval_NotNegativeOne.cs +++ b/src/Renci.SshNet.Tests/Classes/BaseClientTest_Disconnected_KeepAliveInterval_NotNegativeOne.cs @@ -21,13 +21,13 @@ protected override void SetupData() protected override void SetupMocks() { - _serviceFactoryMock.Setup(p => p.CreateSocketFactory()) - .Returns(_socketFactoryMock.Object); - _serviceFactoryMock.Setup(p => p.CreateSession(_connectionInfo, _socketFactoryMock.Object)) - .Returns(_sessionMock.Object); - _sessionMock.Setup(p => p.Connect()); - _sessionMock.Setup(p => p.IsConnected).Returns(false); - _sessionMock.Setup(p => p.TrySendMessage(It.IsAny())) + ServiceFactoryMock.Setup(p => p.CreateSocketFactory()) + .Returns(SocketFactoryMock.Object); + ServiceFactoryMock.Setup(p => p.CreateSession(_connectionInfo, SocketFactoryMock.Object)) + .Returns(SessionMock.Object); + SessionMock.Setup(p => p.Connect()); + SessionMock.Setup(p => p.IsConnected).Returns(false); + SessionMock.Setup(p => p.TrySendMessage(It.IsAny())) .Returns(true); } @@ -35,7 +35,7 @@ protected override void Arrange() { base.Arrange(); - _client = new MyClient(_connectionInfo, false, _serviceFactoryMock.Object); + _client = new MyClient(_connectionInfo, false, ServiceFactoryMock.Object); _client.Connect(); } @@ -43,8 +43,8 @@ protected override void TearDown() { if (_client != null) { - _sessionMock.Setup(p => p.OnDisconnecting()); - _sessionMock.Setup(p => p.Dispose()); + SessionMock.Setup(p => p.OnDisconnecting()); + SessionMock.Setup(p => p.Dispose()); _client.Dispose(); } } @@ -66,32 +66,32 @@ public void KeepAliveIntervalShouldReturnConfiguredValue() [TestMethod] public void CreateSocketFactoryOnServiceFactoryShouldBeInvokedOnce() { - _serviceFactoryMock.Verify(p => p.CreateSocketFactory(), Times.Once); + ServiceFactoryMock.Verify(p => p.CreateSocketFactory(), Times.Once); } [TestMethod] public void CreateSessionOnServiceFactoryShouldBeInvokedOnce() { - _serviceFactoryMock.Verify(p => p.CreateSession(_connectionInfo, _socketFactoryMock.Object), + ServiceFactoryMock.Verify(p => p.CreateSession(_connectionInfo, SocketFactoryMock.Object), Times.Once); } [TestMethod] public void ConnectOnSessionShouldBeInvokedOnce() { - _sessionMock.Verify(p => p.Connect(), Times.Once); + SessionMock.Verify(p => p.Connect(), Times.Once); } [TestMethod] public void IsConnectedOnSessionShouldBeInvokedOnce() { - _sessionMock.Verify(p => p.IsConnected, Times.Once); + SessionMock.Verify(p => p.IsConnected, Times.Once); } [TestMethod] public void SendMessageOnSessionShouldNeverBeInvoked() { - _sessionMock.Verify(p => p.TrySendMessage(It.IsAny()), Times.Never); + SessionMock.Verify(p => p.TrySendMessage(It.IsAny()), Times.Never); } private class MyClient : BaseClient diff --git a/src/Renci.SshNet.Tests/Classes/BaseClientTest_NotConnected_KeepAliveInterval_NotNegativeOne.cs b/src/Renci.SshNet.Tests/Classes/BaseClientTest_NotConnected_KeepAliveInterval_NotNegativeOne.cs index 0f449c82d..e0720e422 100644 --- a/src/Renci.SshNet.Tests/Classes/BaseClientTest_NotConnected_KeepAliveInterval_NotNegativeOne.cs +++ b/src/Renci.SshNet.Tests/Classes/BaseClientTest_NotConnected_KeepAliveInterval_NotNegativeOne.cs @@ -25,15 +25,15 @@ protected override void Arrange() { base.Arrange(); - _client = new MyClient(_connectionInfo, false, _serviceFactoryMock.Object); + _client = new MyClient(_connectionInfo, false, ServiceFactoryMock.Object); } protected override void TearDown() { if (_client != null) { - _sessionMock.Setup(p => p.OnDisconnecting()); - _sessionMock.Setup(p => p.Dispose()); + SessionMock.Setup(p => p.OnDisconnecting()); + SessionMock.Setup(p => p.Dispose()); _client.Dispose(); } } @@ -55,12 +55,12 @@ public void KeepAliveIntervalShouldReturnConfiguredValue() [TestMethod] public void ConnectShouldActivateKeepAliveIfSessionIs() { - _serviceFactoryMock.Setup(p => p.CreateSocketFactory()) - .Returns(_socketFactoryMock.Object); - _serviceFactoryMock.Setup(p => p.CreateSession(_connectionInfo, _socketFactoryMock.Object)) - .Returns(_sessionMock.Object); - _sessionMock.Setup(p => p.Connect()); - _sessionMock.Setup(p => p.TrySendMessage(It.IsAny())) + ServiceFactoryMock.Setup(p => p.CreateSocketFactory()) + .Returns(SocketFactoryMock.Object); + ServiceFactoryMock.Setup(p => p.CreateSession(_connectionInfo, SocketFactoryMock.Object)) + .Returns(SessionMock.Object); + SessionMock.Setup(p => p.Connect()); + SessionMock.Setup(p => p.TrySendMessage(It.IsAny())) .Returns(true) .Callback(() => Interlocked.Increment(ref _keepAliveCount)); @@ -70,7 +70,7 @@ public void ConnectShouldActivateKeepAliveIfSessionIs() Thread.Sleep(250); // Exactly two keep-alives should be sent - _sessionMock.Verify(p => p.TrySendMessage(It.IsAny()), Times.Exactly(2)); + SessionMock.Verify(p => p.TrySendMessage(It.IsAny()), Times.Exactly(2)); } private class MyClient : BaseClient diff --git a/src/Renci.SshNet.Tests/Classes/Channels/ChannelDirectTcpipTest.cs b/src/Renci.SshNet.Tests/Classes/Channels/ChannelDirectTcpipTest.cs index 1dce239e5..649f6a4f1 100644 --- a/src/Renci.SshNet.Tests/Classes/Channels/ChannelDirectTcpipTest.cs +++ b/src/Renci.SshNet.Tests/Classes/Channels/ChannelDirectTcpipTest.cs @@ -3,8 +3,11 @@ using System.Net; using System.Net.Sockets; using System.Threading; + using Microsoft.VisualStudio.TestTools.UnitTesting; + using Moq; + using Renci.SshNet.Channels; using Renci.SshNet.Common; using Renci.SshNet.Messages; @@ -53,16 +56,17 @@ protected override void OnInit() [TestMethod] public void SocketShouldBeClosedAndBindShouldEndWhenForwardedPortSignalsClosingEvent() { - _sessionMock.Setup(p => p.IsConnected).Returns(true); - _sessionMock.Setup(p => p.SendMessage(It.IsAny())) - .Callback(m => _sessionMock.Raise(p => p.ChannelOpenConfirmationReceived += null, + _ = _sessionMock.Setup(p => p.IsConnected) + .Returns(true); + _ = _sessionMock.Setup(p => p.SendMessage(It.IsAny())) + .Callback(m => _sessionMock.Raise(p => p.ChannelOpenConfirmationReceived += null, new MessageEventArgs( new ChannelOpenConfirmationMessage(((ChannelOpenMessage) m).LocalChannelNumber, _remoteWindowSize, _remotePacketSize, _remoteChannelNumber)))); - _sessionMock.Setup(p => p.WaitOnHandle(It.IsAny())) - .Callback(p => p.WaitOne(Session.Infinite)); + _ = _sessionMock.Setup(p => p.WaitOnHandle(It.IsAny())) + .Callback(p => p.WaitOne(Session.Infinite)); var localPortEndPoint = new IPEndPoint(IPAddress.Loopback, 8122); using (var localPortListener = new AsyncSocketListener(localPortEndPoint)) @@ -108,16 +112,17 @@ public void SocketShouldBeClosedAndBindShouldEndWhenForwardedPortSignalsClosingE [TestMethod] public void SocketShouldBeClosedAndBindShouldEndWhenOnErrorOccurredIsInvoked() { - _sessionMock.Setup(p => p.IsConnected).Returns(true); - _sessionMock.Setup(p => p.SendMessage(It.IsAny())) - .Callback(m => _sessionMock.Raise(p => p.ChannelOpenConfirmationReceived += null, + _ = _sessionMock.Setup(p => p.IsConnected) + .Returns(true); + _ = _sessionMock.Setup(p => p.SendMessage(It.IsAny())) + .Callback(m => _sessionMock.Raise(p => p.ChannelOpenConfirmationReceived += null, new MessageEventArgs( new ChannelOpenConfirmationMessage(((ChannelOpenMessage) m).LocalChannelNumber, _remoteWindowSize, _remotePacketSize, _remoteChannelNumber)))); - _sessionMock.Setup(p => p.WaitOnHandle(It.IsAny())) - .Callback(p => p.WaitOne(Session.Infinite)); + _ = _sessionMock.Setup(p => p.WaitOnHandle(It.IsAny())) + .Callback(p => p.WaitOne(Session.Infinite)); var localPortEndPoint = new IPEndPoint(IPAddress.Loopback, 8122); using (var localPortListener = new AsyncSocketListener(localPortEndPoint)) @@ -166,46 +171,53 @@ public void SocketShouldBeClosedAndEofShouldBeSentToServerWhenClientShutsDownSoc { var sequence = new MockSequence(); - _sessionMock.InSequence(sequence).Setup(p => p.IsConnected).Returns(true); - _sessionMock.InSequence(sequence) - .Setup(p => p.SendMessage(It.IsAny())) - .Callback(m => _sessionMock.Raise(p => p.ChannelOpenConfirmationReceived += null, + _ = _sessionMock.InSequence(sequence).Setup(p => p.IsConnected) + .Returns(true); + _ = _sessionMock.InSequence(sequence) + .Setup(p => p.SendMessage(It.IsAny())) + .Callback(m => _sessionMock.Raise(p => p.ChannelOpenConfirmationReceived += null, new MessageEventArgs( new ChannelOpenConfirmationMessage(((ChannelOpenMessage) m).LocalChannelNumber, _remoteWindowSize, _remotePacketSize, _remoteChannelNumber)))); - _sessionMock.InSequence(sequence) - .Setup(p => p.WaitOnHandle(It.IsAny())) - .Callback(p => p.WaitOne(Session.Infinite)); - _sessionMock.InSequence(sequence).Setup(p => p.IsConnected).Returns(true); - _sessionMock.InSequence(sequence) - .Setup(p => p.TrySendMessage(It.IsAny())) - .Returns(true) - .Callback( - m => new Thread(() => - { - Thread.Sleep(50); - _sessionMock.Raise(s => s.ChannelEofReceived += null, - new MessageEventArgs(new ChannelEofMessage(_localChannelNumber))); - }).Start()); - _sessionMock.InSequence(sequence).Setup(p => p.IsConnected).Returns(true); - _sessionMock.InSequence(sequence) - .Setup(p => p.TrySendMessage(It.IsAny())) - .Returns(true) - .Callback( - m => new Thread(() => - { - Thread.Sleep(50); - _sessionMock.Raise(s => s.ChannelCloseReceived += null, - new MessageEventArgs(new ChannelCloseMessage(_localChannelNumber))); - }).Start()); - _sessionMock.InSequence(sequence).Setup(p => p.ConnectionInfo).Returns(_connectionInfoMock.Object); - _connectionInfoMock.InSequence(sequence).Setup(p => p.ChannelCloseTimeout).Returns(_channelCloseTimeout); - _sessionMock.InSequence(sequence) - .Setup(p => p.TryWait(It.IsAny(), _channelCloseTimeout)) - .Callback((waitHandle, channelCloseTimeout) => waitHandle.WaitOne()) - .Returns(WaitResult.Success); + _ = _sessionMock.InSequence(sequence) + .Setup(p => p.WaitOnHandle(It.IsAny())) + .Callback(p => p.WaitOne(Session.Infinite)); + _ = _sessionMock.InSequence(sequence) + .Setup(p => p.IsConnected) + .Returns(true); + _ = _sessionMock.InSequence(sequence) + .Setup(p => p.TrySendMessage(It.IsAny())) + .Returns(true) + .Callback(m => new Thread(() => + { + Thread.Sleep(50); + _sessionMock.Raise(s => s.ChannelEofReceived += null, + new MessageEventArgs(new ChannelEofMessage(_localChannelNumber))); + }).Start()); + _ = _sessionMock.InSequence(sequence) + .Setup(p => p.IsConnected) + .Returns(true); + _ = _sessionMock.InSequence(sequence) + .Setup(p => p.TrySendMessage(It.IsAny())) + .Returns(true) + .Callback(m => new Thread(() => + { + Thread.Sleep(50); + _sessionMock.Raise(s => s.ChannelCloseReceived += null, + new MessageEventArgs(new ChannelCloseMessage(_localChannelNumber))); + }).Start()); + _ = _sessionMock.InSequence(sequence) + .Setup(p => p.ConnectionInfo) + .Returns(_connectionInfoMock.Object); + _ = _connectionInfoMock.InSequence(sequence) + .Setup(p => p.ChannelCloseTimeout) + .Returns(_channelCloseTimeout); + _ = _sessionMock.InSequence(sequence) + .Setup(p => p.TryWait(It.IsAny(), _channelCloseTimeout)) + .Callback((waitHandle, channelCloseTimeout) => waitHandle.WaitOne()) + .Returns(WaitResult.Success); var channelBindFinishedWaitHandle = new ManualResetEvent(false); Socket handler = null; @@ -217,26 +229,26 @@ public void SocketShouldBeClosedAndEofShouldBeSentToServerWhenClientShutsDownSoc localPortListener.Start(); localPortListener.Connected += socket => - { - channel = new ChannelDirectTcpip(_sessionMock.Object, - _localChannelNumber, - _localWindowSize, - _localPacketSize); - channel.Open(_remoteHost, _port, _forwardedPortMock.Object, socket); - channel.Bind(); - channel.Dispose(); + { + channel = new ChannelDirectTcpip(_sessionMock.Object, + _localChannelNumber, + _localWindowSize, + _localPacketSize); + channel.Open(_remoteHost, _port, _forwardedPortMock.Object, socket); + channel.Bind(); + channel.Dispose(); - handler = socket; + handler = socket; - channelBindFinishedWaitHandle.Set(); - }; + _ = channelBindFinishedWaitHandle.Set(); + }; var client = new Socket(localPortEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); client.Connect(localPortEndPoint); client.Shutdown(SocketShutdown.Send); Assert.IsFalse(client.Connected); - channelBindFinishedWaitHandle.WaitOne(); + _ = channelBindFinishedWaitHandle.WaitOne(); Assert.IsNotNull(handler); Assert.IsFalse(handler.Connected); @@ -251,4 +263,4 @@ public void SocketShouldBeClosedAndEofShouldBeSentToServerWhenClientShutsDownSoc } } } -} \ No newline at end of file +} diff --git a/src/Renci.SshNet.Tests/Classes/Channels/ChannelDirectTcpipTest_Dispose_SessionIsConnectedAndChannelIsOpen.cs b/src/Renci.SshNet.Tests/Classes/Channels/ChannelDirectTcpipTest_Dispose_SessionIsConnectedAndChannelIsOpen.cs index da7739694..6ccda5c82 100644 --- a/src/Renci.SshNet.Tests/Classes/Channels/ChannelDirectTcpipTest_Dispose_SessionIsConnectedAndChannelIsOpen.cs +++ b/src/Renci.SshNet.Tests/Classes/Channels/ChannelDirectTcpipTest_Dispose_SessionIsConnectedAndChannelIsOpen.cs @@ -79,45 +79,53 @@ private void Arrange() _forwardedPortMock = new Mock(MockBehavior.Strict); var sequence = new MockSequence(); - _sessionMock.InSequence(sequence).Setup(p => p.IsConnected).Returns(true); - _sessionMock.InSequence(sequence) - .Setup(p => p.SendMessage(It.Is(m => AssertExpectedMessage(m)))); - _sessionMock.InSequence(sequence) - .Setup(p => p.WaitOnHandle(It.IsNotNull())) - .Callback( - w => - { - _sessionMock.Raise( - s => s.ChannelOpenConfirmationReceived += null, - new MessageEventArgs( - new ChannelOpenConfirmationMessage( - _localChannelNumber, - _remoteWindowSize, - _remotePacketSize, - _remoteChannelNumber))); - w.WaitOne(); - }); - _sessionMock.InSequence(sequence).Setup(p => p.IsConnected).Returns(true); - _sessionMock.InSequence(sequence) - .Setup( - p => p.TrySendMessage(It.Is(m => m.LocalChannelNumber == _remoteChannelNumber))) - .Returns(true); - _sessionMock.InSequence(sequence).Setup(p => p.IsConnected).Returns(true); - _sessionMock.InSequence(sequence) - .Setup(p => p.TrySendMessage(It.Is(m => m.LocalChannelNumber == _remoteChannelNumber))) - .Returns(true); - _sessionMock.InSequence(sequence).Setup(p => p.ConnectionInfo).Returns(_connectionInfoMock.Object); - _connectionInfoMock.InSequence(sequence).Setup(p => p.ChannelCloseTimeout).Returns(_channelCloseTimeout); - _sessionMock.InSequence(sequence) - .Setup(p => p.TryWait(It.IsAny(), _channelCloseTimeout)) - .Callback((waitHandle, channelCloseTimeout) => - { - _sessionMock.Raise( - s => s.ChannelCloseReceived += null, - new MessageEventArgs(new ChannelCloseMessage(_localChannelNumber))); - waitHandle.WaitOne(); - }) - .Returns(WaitResult.Success); + + _ = _sessionMock.InSequence(sequence).Setup(p => p.IsConnected).Returns(true); + _ = _sessionMock.InSequence(sequence) + .Setup(p => p.SendMessage(It.Is(m => AssertExpectedMessage(m)))); + _ = _sessionMock.InSequence(sequence) + .Setup(p => p.WaitOnHandle(It.IsNotNull())) + .Callback( + w => + { + _sessionMock.Raise( + s => s.ChannelOpenConfirmationReceived += null, + new MessageEventArgs( + new ChannelOpenConfirmationMessage( + _localChannelNumber, + _remoteWindowSize, + _remotePacketSize, + _remoteChannelNumber))); + _ = w.WaitOne(); + }); + _ = _sessionMock.InSequence(sequence) + .Setup(p => p.IsConnected) + .Returns(true); + _ = _sessionMock.InSequence(sequence) + .Setup(p => p.TrySendMessage(It.Is(m => m.LocalChannelNumber == _remoteChannelNumber))) + .Returns(true); + _ = _sessionMock.InSequence(sequence) + .Setup(p => p.IsConnected) + .Returns(true); + _ = _sessionMock.InSequence(sequence) + .Setup(p => p.TrySendMessage(It.Is(m => m.LocalChannelNumber == _remoteChannelNumber))) + .Returns(true); + _ = _sessionMock.InSequence(sequence) + .Setup(p => p.ConnectionInfo) + .Returns(_connectionInfoMock.Object); + _ = _connectionInfoMock.InSequence(sequence) + .Setup(p => p.ChannelCloseTimeout) + .Returns(_channelCloseTimeout); + _ = _sessionMock.InSequence(sequence) + .Setup(p => p.TryWait(It.IsAny(), _channelCloseTimeout)) + .Callback((waitHandle, channelCloseTimeout) => + { + _sessionMock.Raise( + s => s.ChannelCloseReceived += null, + new MessageEventArgs(new ChannelCloseMessage(_localChannelNumber))); + _ = waitHandle.WaitOne(); + }) + .Returns(WaitResult.Success); var localEndpoint = new IPEndPoint(IPAddress.Loopback, 8122); _listener = new AsyncSocketListener(localEndpoint); @@ -138,7 +146,7 @@ private void Arrange() } finally { - _channelBindFinishedWaitHandle.Set(); + _ = _channelBindFinishedWaitHandle.Set(); } }; _listener.Start(); @@ -154,7 +162,7 @@ private void Arrange() if (bytesReceived == 0) { _client.Shutdown(SocketShutdown.Send); - _clientReceivedFinishedWaitHandle.Set(); + _ = _clientReceivedFinishedWaitHandle.Set(); } } ); @@ -166,17 +174,14 @@ private void Arrange() private void Act() { - if (_channel != null) - { - _channel.Dispose(); - } + _channel?.Dispose(); } [TestMethod] public void BindShouldHaveFinishedWithoutException() { Assert.IsTrue(_channelBindFinishedWaitHandle.WaitOne(0)); - Assert.IsNull(_channelException, _channelException != null ? _channelException.ToString() : null); + Assert.IsNull(_channelException, _channelException?.ToString()); } [TestMethod] @@ -206,29 +211,54 @@ public void IsOpenShouldReturnFalse() private bool AssertExpectedMessage(ChannelOpenMessage channelOpenMessage) { if (channelOpenMessage == null) + { return false; + } + if (channelOpenMessage.LocalChannelNumber != _localChannelNumber) + { return false; + } + if (channelOpenMessage.InitialWindowSize != _localWindowSize) + { return false; + } + if (channelOpenMessage.MaximumPacketSize != _localPacketSize) + { return false; + } - var directTcpipChannelInfo = channelOpenMessage.Info as DirectTcpipChannelInfo; - if (directTcpipChannelInfo == null) + if (channelOpenMessage.Info is not DirectTcpipChannelInfo directTcpipChannelInfo) + { return false; + } + if (directTcpipChannelInfo.HostToConnect != _remoteHost) + { return false; + } + if (directTcpipChannelInfo.PortToConnect != _port) + { return false; + } - var clientEndpoint = _client.LocalEndPoint as IPEndPoint; - if (clientEndpoint == null) + if (_client.LocalEndPoint is not IPEndPoint clientEndpoint) + { return false; + } + if (directTcpipChannelInfo.OriginatorAddress != clientEndpoint.Address.ToString()) + { return false; + } + if (directTcpipChannelInfo.OriginatorPort != clientEndpoint.Port) + { return false; + } return true; } diff --git a/src/Renci.SshNet.Tests/Classes/Channels/ChannelForwardedTcpipTest_Dispose_SessionIsConnectedAndChannelIsOpen.cs b/src/Renci.SshNet.Tests/Classes/Channels/ChannelForwardedTcpipTest_Dispose_SessionIsConnectedAndChannelIsOpen.cs index bbbff6d37..393eae093 100644 --- a/src/Renci.SshNet.Tests/Classes/Channels/ChannelForwardedTcpipTest_Dispose_SessionIsConnectedAndChannelIsOpen.cs +++ b/src/Renci.SshNet.Tests/Classes/Channels/ChannelForwardedTcpipTest_Dispose_SessionIsConnectedAndChannelIsOpen.cs @@ -1,11 +1,13 @@ using System; -using System.Collections; using System.Collections.Generic; using System.Net; using System.Net.Sockets; using System.Threading; + using Microsoft.VisualStudio.TestTools.UnitTesting; + using Moq; + using Renci.SshNet.Channels; using Renci.SshNet.Messages.Connection; using Renci.SshNet.Tests.Common; @@ -53,10 +55,10 @@ public void CleanUp() if (_channelThread != null) { - if (_channelThread.IsAlive) - _channelThread.Abort(); + _channelThread.Join(); _channelThread = null; } + if (_channel != null) { _channel.Dispose(); @@ -87,56 +89,63 @@ private void Arrange() _forwardedPortMock = new Mock(MockBehavior.Strict); var sequence = new MockSequence(); - _sessionMock.InSequence(sequence).Setup(p => p.IsConnected).Returns(true); - _sessionMock.InSequence(sequence).Setup(p => p.ConnectionInfo).Returns(_connectionInfoMock.Object); - _connectionInfoMock.InSequence(sequence).Setup(p => p.Timeout).Returns(_connectionInfoTimeout); - _sessionMock.InSequence(sequence).Setup( - p => p.SendMessage( - It.Is( - m => m.LocalChannelNumber == _remoteChannelNumber - && - m.InitialWindowSize == _localWindowSize - && - m.MaximumPacketSize == _localPacketSize - && - m.RemoteChannelNumber == _localChannelNumber) - )); - _sessionMock.InSequence(sequence).Setup(p => p.IsConnected).Returns(true); - _sessionMock.InSequence(sequence) - .Setup( - p => p.TrySendMessage(It.Is(m => m.LocalChannelNumber == _remoteChannelNumber))) - .Returns(true); - _sessionMock.InSequence(sequence).Setup(p => p.IsConnected).Returns(true); - _sessionMock.InSequence(sequence) - .Setup( - p => p.TrySendMessage(It.Is(m => m.LocalChannelNumber == _remoteChannelNumber))) - .Returns(true); - _sessionMock.InSequence(sequence).Setup(p => p.ConnectionInfo).Returns(_connectionInfoMock.Object); - _connectionInfoMock.InSequence(sequence).Setup(p => p.ChannelCloseTimeout).Returns(_channelCloseTimeout); - _sessionMock.InSequence(sequence) - .Setup(p => p.TryWait(It.IsAny(), _channelCloseTimeout)) - .Callback((waitHandle, channelCloseTimeout) => - { - _sessionMock.Raise( - s => s.ChannelCloseReceived += null, - new MessageEventArgs(new ChannelCloseMessage(_localChannelNumber))); - waitHandle.WaitOne(); - }) - .Returns(WaitResult.Success); + + _ = _sessionMock.InSequence(sequence) + .Setup(p => p.IsConnected) + .Returns(true); + _ = _sessionMock.InSequence(sequence) + .Setup(p => p.ConnectionInfo) + .Returns(_connectionInfoMock.Object); + _ = _connectionInfoMock.InSequence(sequence) + .Setup(p => p.Timeout) + .Returns(_connectionInfoTimeout); + _ = _sessionMock.InSequence(sequence) + .Setup(p => p.SendMessage(It.Is(m => + m.LocalChannelNumber == _remoteChannelNumber && + m.InitialWindowSize == _localWindowSize && + m.MaximumPacketSize == _localPacketSize && + m.RemoteChannelNumber == _localChannelNumber))); + _ = _sessionMock.InSequence(sequence) + .Setup(p => p.IsConnected) + .Returns(true); + _ = _sessionMock.InSequence(sequence) + .Setup(p => p.TrySendMessage(It.Is(m => m.LocalChannelNumber == _remoteChannelNumber))) + .Returns(true); + _ = _sessionMock.InSequence(sequence) + .Setup(p => p.IsConnected) + .Returns(true); + _ = _sessionMock.InSequence(sequence) + .Setup(p => p.TrySendMessage(It.Is(m => m.LocalChannelNumber == _remoteChannelNumber))) + .Returns(true); + _ = _sessionMock.InSequence(sequence) + .Setup(p => p.ConnectionInfo) + .Returns(_connectionInfoMock.Object); + _ = _connectionInfoMock.InSequence(sequence) + .Setup(p => p.ChannelCloseTimeout) + .Returns(_channelCloseTimeout); + _ = _sessionMock.InSequence(sequence) + .Setup(p => p.TryWait(It.IsAny(), _channelCloseTimeout)) + .Callback((waitHandle, channelCloseTimeout) => + { + _sessionMock.Raise( + s => s.ChannelCloseReceived += null, + new MessageEventArgs(new ChannelCloseMessage(_localChannelNumber))); + _ = waitHandle.WaitOne(); + }) + .Returns(WaitResult.Success); _remoteListener = new AsyncSocketListener(_remoteEndpoint); - _remoteListener.Connected += socket => _connectedRegister.Add(socket); - _remoteListener.Disconnected += socket => _disconnectedRegister.Add(socket); + _remoteListener.Connected += _connectedRegister.Add; + _remoteListener.Disconnected += _disconnectedRegister.Add; _remoteListener.Start(); - _channel = new ChannelForwardedTcpip( - _sessionMock.Object, - _localChannelNumber, - _localWindowSize, - _localPacketSize, - _remoteChannelNumber, - _remoteWindowSize, - _remotePacketSize); + _channel = new ChannelForwardedTcpip(_sessionMock.Object, + _localChannelNumber, + _localWindowSize, + _localPacketSize, + _remoteChannelNumber, + _remoteWindowSize, + _remotePacketSize); _channelThread = new Thread(() => { @@ -150,7 +159,7 @@ private void Arrange() } finally { - _channelBindFinishedWaitHandle.Set(); + _ = _channelBindFinishedWaitHandle.Set(); } }); _channelThread.Start(); @@ -175,7 +184,7 @@ public void ChannelShouldShutdownSocketToRemoteListener() [TestMethod] public void BindShouldHaveFinishedWithoutException() { - Assert.IsNull(_channelException, _channelException != null ? _channelException.ToString() : null); + Assert.IsNull(_channelException, _channelException?.ToString()); Assert.IsTrue(_channelBindFinishedWaitHandle.WaitOne(0)); } @@ -197,4 +206,4 @@ public void IsOpenShouldReturnFalse() Assert.IsFalse(_channel.IsOpen); } } -} \ No newline at end of file +} diff --git a/src/Renci.SshNet.Tests/Classes/Channels/ChannelSessionTest_Dispose_Disposed.cs b/src/Renci.SshNet.Tests/Classes/Channels/ChannelSessionTest_Dispose_Disposed.cs index 379f7e181..07ba0d53e 100644 --- a/src/Renci.SshNet.Tests/Classes/Channels/ChannelSessionTest_Dispose_Disposed.cs +++ b/src/Renci.SshNet.Tests/Classes/Channels/ChannelSessionTest_Dispose_Disposed.cs @@ -1,8 +1,11 @@ using System; using System.Collections.Generic; using System.Threading; + using Microsoft.VisualStudio.TestTools.UnitTesting; + using Moq; + using Renci.SshNet.Channels; using Renci.SshNet.Common; using Renci.SshNet.Messages.Connection; @@ -144,4 +147,4 @@ public void IsOpenShouldReturnFalse() Assert.IsFalse(_channel.IsOpen); } } -} \ No newline at end of file +} diff --git a/src/Renci.SshNet.Tests/Classes/Channels/ChannelStub.cs b/src/Renci.SshNet.Tests/Classes/Channels/ChannelStub.cs index ac141b9b6..6476ec919 100644 --- a/src/Renci.SshNet.Tests/Classes/Channels/ChannelStub.cs +++ b/src/Renci.SshNet.Tests/Classes/Channels/ChannelStub.cs @@ -54,7 +54,7 @@ public void SetIsOpen(bool value) public void InitializeRemoteChannelInfo(uint remoteChannelNumber, uint remoteWindowSize, uint remotePacketSize) { - base.InitializeRemoteInfo(remoteChannelNumber, remoteWindowSize, remotePacketSize); + InitializeRemoteInfo(remoteChannelNumber, remoteWindowSize, remotePacketSize); } protected override void OnClose() @@ -62,7 +62,9 @@ protected override void OnClose() base.OnClose(); if (OnCloseException != null) + { throw OnCloseException; + } } protected override void OnData(byte[] data) @@ -70,7 +72,9 @@ protected override void OnData(byte[] data) base.OnData(data); if (OnDataException != null) + { throw OnDataException; + } } protected override void OnDisconnected() @@ -78,7 +82,9 @@ protected override void OnDisconnected() base.OnDisconnected(); if (OnDisconnectedException != null) + { throw OnDisconnectedException; + } } protected override void OnEof() @@ -86,7 +92,9 @@ protected override void OnEof() base.OnEof(); if (OnEofException != null) + { throw OnEofException; + } } protected override void OnExtendedData(byte[] data, uint dataTypeCode) @@ -94,7 +102,9 @@ protected override void OnExtendedData(byte[] data, uint dataTypeCode) base.OnExtendedData(data, dataTypeCode); if (OnExtendedDataException != null) + { throw OnExtendedDataException; + } } protected override void OnErrorOccured(Exception exp) @@ -102,7 +112,9 @@ protected override void OnErrorOccured(Exception exp) OnErrorOccurredInvocations.Add(exp); if (OnErrorOccurredException != null) + { throw OnErrorOccurredException; + } } protected override void OnFailure() @@ -110,7 +122,9 @@ protected override void OnFailure() base.OnFailure(); if (OnFailureException != null) + { throw OnFailureException; + } } protected override void OnRequest(RequestInfo info) @@ -118,7 +132,9 @@ protected override void OnRequest(RequestInfo info) base.OnRequest(info); if (OnRequestException != null) + { throw OnRequestException; + } } protected override void OnSuccess() @@ -126,7 +142,9 @@ protected override void OnSuccess() base.OnSuccess(); if (OnSuccessException != null) + { throw OnSuccessException; + } } protected override void OnWindowAdjust(uint bytesToAdd) @@ -134,7 +152,9 @@ protected override void OnWindowAdjust(uint bytesToAdd) base.OnWindowAdjust(bytesToAdd); if (OnWindowAdjustException != null) + { throw OnWindowAdjustException; + } } } } diff --git a/src/Renci.SshNet.Tests/Classes/Channels/ChannelTest_Dispose_SessionIsConnectedAndChannelIsOpen_EofReceived.cs b/src/Renci.SshNet.Tests/Classes/Channels/ChannelTest_Dispose_SessionIsConnectedAndChannelIsOpen_EofReceived.cs index 0bb9e862d..23a00ca83 100644 --- a/src/Renci.SshNet.Tests/Classes/Channels/ChannelTest_Dispose_SessionIsConnectedAndChannelIsOpen_EofReceived.cs +++ b/src/Renci.SshNet.Tests/Classes/Channels/ChannelTest_Dispose_SessionIsConnectedAndChannelIsOpen_EofReceived.cs @@ -94,12 +94,10 @@ public void TearDown() _channelClosedReceived = null; } - if (_raiseChannelCloseReceivedThread != null && _raiseChannelCloseReceivedThread.IsAlive) + if (_raiseChannelCloseReceivedThread != null) { - if (!_raiseChannelCloseReceivedThread.Join(1000)) - { - _raiseChannelCloseReceivedThread.Abort(); - } + _raiseChannelCloseReceivedThread.Join(); + _raiseChannelCloseReceivedThread = null; } if (_channelClosedEventHandlerCompleted != null) diff --git a/src/Renci.SshNet.Tests/Classes/Channels/ChannelTest_OnSessionChannelCloseReceived_OnClose_Exception.cs b/src/Renci.SshNet.Tests/Classes/Channels/ChannelTest_OnSessionChannelCloseReceived_OnClose_Exception.cs index 102a57698..8a7368499 100644 --- a/src/Renci.SshNet.Tests/Classes/Channels/ChannelTest_OnSessionChannelCloseReceived_OnClose_Exception.cs +++ b/src/Renci.SshNet.Tests/Classes/Channels/ChannelTest_OnSessionChannelCloseReceived_OnClose_Exception.cs @@ -1,7 +1,8 @@ using System; using System.Collections.Generic; + using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; + using Renci.SshNet.Common; using Renci.SshNet.Messages.Connection; diff --git a/src/Renci.SshNet.Tests/Classes/Channels/ChannelTest_OnSessionChannelDataReceived_OnData_Exception.cs b/src/Renci.SshNet.Tests/Classes/Channels/ChannelTest_OnSessionChannelDataReceived_OnData_Exception.cs index 3c2884f2c..bdb3cadfa 100644 --- a/src/Renci.SshNet.Tests/Classes/Channels/ChannelTest_OnSessionChannelDataReceived_OnData_Exception.cs +++ b/src/Renci.SshNet.Tests/Classes/Channels/ChannelTest_OnSessionChannelDataReceived_OnData_Exception.cs @@ -1,7 +1,8 @@ using System; using System.Collections.Generic; + using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; + using Renci.SshNet.Common; using Renci.SshNet.Messages.Connection; @@ -61,4 +62,4 @@ public void OnErrorOccuredShouldBeInvokedOnce() Assert.AreSame(_onDataException, _channel.OnErrorOccurredInvocations[0]); } } -} \ No newline at end of file +} diff --git a/src/Renci.SshNet.Tests/Classes/Channels/ChannelTest_OnSessionChannelEofReceived_OnEof_Exception.cs b/src/Renci.SshNet.Tests/Classes/Channels/ChannelTest_OnSessionChannelEofReceived_OnEof_Exception.cs index ff4a38bb3..69a5adb47 100644 --- a/src/Renci.SshNet.Tests/Classes/Channels/ChannelTest_OnSessionChannelEofReceived_OnEof_Exception.cs +++ b/src/Renci.SshNet.Tests/Classes/Channels/ChannelTest_OnSessionChannelEofReceived_OnEof_Exception.cs @@ -1,7 +1,8 @@ using System; using System.Collections.Generic; + using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; + using Renci.SshNet.Common; using Renci.SshNet.Messages.Connection; @@ -69,4 +70,4 @@ public void OnErrorOccuredShouldBeInvokedOnce() Assert.AreSame(_onEofException, _channel.OnErrorOccurredInvocations[0]); } } -} \ No newline at end of file +} diff --git a/src/Renci.SshNet.Tests/Classes/Channels/ChannelTest_OnSessionChannelExtendedDataReceived_OnExtendedData_Exception.cs b/src/Renci.SshNet.Tests/Classes/Channels/ChannelTest_OnSessionChannelExtendedDataReceived_OnExtendedData_Exception.cs index 9f582933c..c27f73392 100644 --- a/src/Renci.SshNet.Tests/Classes/Channels/ChannelTest_OnSessionChannelExtendedDataReceived_OnExtendedData_Exception.cs +++ b/src/Renci.SshNet.Tests/Classes/Channels/ChannelTest_OnSessionChannelExtendedDataReceived_OnExtendedData_Exception.cs @@ -1,7 +1,8 @@ using System; using System.Collections.Generic; + using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; + using Renci.SshNet.Common; using Renci.SshNet.Messages.Connection; @@ -61,4 +62,4 @@ public void OnErrorOccuredShouldBeInvokedOnce() Assert.AreSame(_onExtendedDataException, _channel.OnErrorOccurredInvocations[0]); } } -} \ No newline at end of file +} diff --git a/src/Renci.SshNet.Tests/Classes/Channels/ChannelTest_OnSessionChannelFailureReceived_OnFailure_Exception.cs b/src/Renci.SshNet.Tests/Classes/Channels/ChannelTest_OnSessionChannelFailureReceived_OnFailure_Exception.cs index 935048a28..360628ca2 100644 --- a/src/Renci.SshNet.Tests/Classes/Channels/ChannelTest_OnSessionChannelFailureReceived_OnFailure_Exception.cs +++ b/src/Renci.SshNet.Tests/Classes/Channels/ChannelTest_OnSessionChannelFailureReceived_OnFailure_Exception.cs @@ -1,7 +1,8 @@ using System; using System.Collections.Generic; + using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; + using Renci.SshNet.Common; using Renci.SshNet.Messages.Connection; @@ -61,4 +62,4 @@ public void OnErrorOccuredShouldBeInvokedOnce() Assert.AreSame(_onFailureException, _channel.OnErrorOccurredInvocations[0]); } } -} \ No newline at end of file +} diff --git a/src/Renci.SshNet.Tests/Classes/Channels/ChannelTest_OnSessionChannelRequestReceived_OnRequest_Exception.cs b/src/Renci.SshNet.Tests/Classes/Channels/ChannelTest_OnSessionChannelRequestReceived_OnRequest_Exception.cs index d5c82801d..407480dea 100644 --- a/src/Renci.SshNet.Tests/Classes/Channels/ChannelTest_OnSessionChannelRequestReceived_OnRequest_Exception.cs +++ b/src/Renci.SshNet.Tests/Classes/Channels/ChannelTest_OnSessionChannelRequestReceived_OnRequest_Exception.cs @@ -1,7 +1,8 @@ using System; using System.Collections.Generic; + using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; + using Renci.SshNet.Common; using Renci.SshNet.Messages.Connection; @@ -32,8 +33,8 @@ protected override void SetupData() protected override void SetupMocks() { - SessionMock.Setup(p => p.ConnectionInfo) - .Returns(new ConnectionInfo("host", "user", new PasswordAuthenticationMethod("user", "password"))); + _ = SessionMock.Setup(p => p.ConnectionInfo) + .Returns(new ConnectionInfo("host", "user", new PasswordAuthenticationMethod("user", "password"))); } protected override void Arrange() @@ -65,4 +66,4 @@ public void OnErrorOccuredShouldBeInvokedOnce() Assert.AreSame(_onRequestException, _channel.OnErrorOccurredInvocations[0]); } } -} \ No newline at end of file +} diff --git a/src/Renci.SshNet.Tests/Classes/Channels/ChannelTest_OnSessionChannelSuccessReceived_OnSuccess_Exception.cs b/src/Renci.SshNet.Tests/Classes/Channels/ChannelTest_OnSessionChannelSuccessReceived_OnSuccess_Exception.cs index 2caa91f1b..09a9e1ea2 100644 --- a/src/Renci.SshNet.Tests/Classes/Channels/ChannelTest_OnSessionChannelSuccessReceived_OnSuccess_Exception.cs +++ b/src/Renci.SshNet.Tests/Classes/Channels/ChannelTest_OnSessionChannelSuccessReceived_OnSuccess_Exception.cs @@ -1,7 +1,8 @@ using System; using System.Collections.Generic; + using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; + using Renci.SshNet.Common; using Renci.SshNet.Messages.Connection; @@ -61,4 +62,4 @@ public void OnErrorOccuredShouldBeInvokedOnce() Assert.AreSame(_onSuccessException, _channel.OnErrorOccurredInvocations[0]); } } -} \ No newline at end of file +} diff --git a/src/Renci.SshNet.Tests/Classes/Channels/ChannelTest_OnSessionChannelWindowAdjustReceived_OnWindowAdjust_Exception.cs b/src/Renci.SshNet.Tests/Classes/Channels/ChannelTest_OnSessionChannelWindowAdjustReceived_OnWindowAdjust_Exception.cs index ba223ad91..1019204b2 100644 --- a/src/Renci.SshNet.Tests/Classes/Channels/ChannelTest_OnSessionChannelWindowAdjustReceived_OnWindowAdjust_Exception.cs +++ b/src/Renci.SshNet.Tests/Classes/Channels/ChannelTest_OnSessionChannelWindowAdjustReceived_OnWindowAdjust_Exception.cs @@ -1,7 +1,8 @@ using System; using System.Collections.Generic; + using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; + using Renci.SshNet.Common; using Renci.SshNet.Messages.Connection; @@ -70,4 +71,4 @@ public void OnErrorOccuredShouldBeInvokedOnce() Assert.AreSame(_onWindowAdjustException, _channel.OnErrorOccurredInvocations[0]); } } -} \ No newline at end of file +} diff --git a/src/Renci.SshNet.Tests/Classes/Channels/ChannelTest_OnSessionDisconnected_OnDisconnected_Exception.cs b/src/Renci.SshNet.Tests/Classes/Channels/ChannelTest_OnSessionDisconnected_OnDisconnected_Exception.cs index 4796c4e6f..989ea952c 100644 --- a/src/Renci.SshNet.Tests/Classes/Channels/ChannelTest_OnSessionDisconnected_OnDisconnected_Exception.cs +++ b/src/Renci.SshNet.Tests/Classes/Channels/ChannelTest_OnSessionDisconnected_OnDisconnected_Exception.cs @@ -1,7 +1,8 @@ using System; using System.Collections.Generic; + using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; + using Renci.SshNet.Common; namespace Renci.SshNet.Tests.Classes.Channels @@ -59,4 +60,4 @@ public void OnErrorOccuredShouldBeInvokedOnce() Assert.AreSame(_onDisconnectedException, _channel.OnErrorOccurredInvocations[0]); } } -} \ No newline at end of file +} diff --git a/src/Renci.SshNet.Tests/Classes/Channels/ChannelTest_OnSessionDisconnected_SessionIsConnectedAndChannelIsOpen.cs b/src/Renci.SshNet.Tests/Classes/Channels/ChannelTest_OnSessionDisconnected_SessionIsConnectedAndChannelIsOpen.cs index e228c36bc..327aa1268 100644 --- a/src/Renci.SshNet.Tests/Classes/Channels/ChannelTest_OnSessionDisconnected_SessionIsConnectedAndChannelIsOpen.cs +++ b/src/Renci.SshNet.Tests/Classes/Channels/ChannelTest_OnSessionDisconnected_SessionIsConnectedAndChannelIsOpen.cs @@ -1,7 +1,8 @@ using System; using System.Collections.Generic; + using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; + using Renci.SshNet.Common; namespace Renci.SshNet.Tests.Classes.Channels @@ -35,7 +36,8 @@ protected override void SetupData() protected override void SetupMocks() { - SessionMock.Setup(p => p.IsConnected).Returns(true); + _ = SessionMock.Setup(p => p.IsConnected) + .Returns(true); } protected override void Arrange() @@ -72,4 +74,4 @@ public void ExceptionShouldNeverHaveFired() Assert.AreEqual(0, _channelExceptionRegister.Count); } } -} \ No newline at end of file +} diff --git a/src/Renci.SshNet.Tests/Classes/Channels/ClientChannelStub.cs b/src/Renci.SshNet.Tests/Classes/Channels/ClientChannelStub.cs index 621c47002..05c52f2ac 100644 --- a/src/Renci.SshNet.Tests/Classes/Channels/ClientChannelStub.cs +++ b/src/Renci.SshNet.Tests/Classes/Channels/ClientChannelStub.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; + using Renci.SshNet.Channels; using Renci.SshNet.Messages.Connection; @@ -58,7 +59,7 @@ public void SetIsOpen(bool value) public void InitializeRemoteChannelInfo(uint remoteChannelNumber, uint remoteWindowSize, uint remotePacketSize) { - base.InitializeRemoteInfo(remoteChannelNumber, remoteWindowSize, remotePacketSize); + InitializeRemoteInfo(remoteChannelNumber, remoteWindowSize, remotePacketSize); } protected override void OnClose() @@ -66,7 +67,9 @@ protected override void OnClose() base.OnClose(); if (OnCloseException != null) + { throw OnCloseException; + } } protected override void OnData(byte[] data) @@ -74,7 +77,9 @@ protected override void OnData(byte[] data) base.OnData(data); if (OnDataException != null) + { throw OnDataException; + } } protected override void OnDisconnected() @@ -82,7 +87,9 @@ protected override void OnDisconnected() base.OnDisconnected(); if (OnDisconnectedException != null) + { throw OnDisconnectedException; + } } protected override void OnEof() @@ -90,7 +97,9 @@ protected override void OnEof() base.OnEof(); if (OnEofException != null) + { throw OnEofException; + } } protected override void OnExtendedData(byte[] data, uint dataTypeCode) @@ -98,7 +107,9 @@ protected override void OnExtendedData(byte[] data, uint dataTypeCode) base.OnExtendedData(data, dataTypeCode); if (OnExtendedDataException != null) + { throw OnExtendedDataException; + } } protected override void OnErrorOccured(Exception exp) @@ -106,7 +117,9 @@ protected override void OnErrorOccured(Exception exp) OnErrorOccurredInvocations.Add(exp); if (OnErrorOccurredException != null) + { throw OnErrorOccurredException; + } } protected override void OnFailure() @@ -114,7 +127,9 @@ protected override void OnFailure() base.OnFailure(); if (OnFailureException != null) + { throw OnFailureException; + } } protected override void OnRequest(RequestInfo info) @@ -122,7 +137,9 @@ protected override void OnRequest(RequestInfo info) base.OnRequest(info); if (OnRequestException != null) + { throw OnRequestException; + } } protected override void OnSuccess() @@ -130,7 +147,9 @@ protected override void OnSuccess() base.OnSuccess(); if (OnSuccessException != null) + { throw OnSuccessException; + } } protected override void OnWindowAdjust(uint bytesToAdd) @@ -138,7 +157,9 @@ protected override void OnWindowAdjust(uint bytesToAdd) base.OnWindowAdjust(bytesToAdd); if (OnWindowAdjustException != null) + { throw OnWindowAdjustException; + } } protected override void OnOpenConfirmation(uint remoteChannelNumber, uint initialWindowSize, uint maximumPacketSize) @@ -146,7 +167,9 @@ protected override void OnOpenConfirmation(uint remoteChannelNumber, uint initia base.OnOpenConfirmation(remoteChannelNumber, initialWindowSize, maximumPacketSize); if (OnOpenConfirmationException != null) + { throw OnOpenConfirmationException; + } } protected override void OnOpenFailure(uint reasonCode, string description, string language) @@ -154,7 +177,9 @@ protected override void OnOpenFailure(uint reasonCode, string description, strin base.OnOpenFailure(reasonCode, description, language); if (OnOpenFailureException != null) + { throw OnOpenFailureException; + } } } } diff --git a/src/Renci.SshNet.Tests/Classes/CipherInfoTest.cs b/src/Renci.SshNet.Tests/Classes/CipherInfoTest.cs index 4014fc3ce..832c92f8b 100644 --- a/src/Renci.SshNet.Tests/Classes/CipherInfoTest.cs +++ b/src/Renci.SshNet.Tests/Classes/CipherInfoTest.cs @@ -1,7 +1,8 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using Renci.SshNet.Common; + using Renci.SshNet.Security.Cryptography; using Renci.SshNet.Tests.Common; + using System; namespace Renci.SshNet.Tests.Classes @@ -19,10 +20,10 @@ public class CipherInfoTest : TestBase [Ignore] // placeholder public void CipherInfoConstructorTest() { - int keySize = 0; // TODO: Initialize to an appropriate value + var keySize = 0; // TODO: Initialize to an appropriate value Func cipher = null; // TODO: Initialize to an appropriate value - CipherInfo target = new CipherInfo(keySize, cipher); + var target = new CipherInfo(keySize, cipher); Assert.Inconclusive("TODO: Implement code to verify target"); } } -} \ No newline at end of file +} diff --git a/src/Renci.SshNet.Tests/Classes/ClientAuthenticationTest_Success_MultiList_PartialSuccessLimitReachedFollowedBySuccessInAlternateBranch.cs b/src/Renci.SshNet.Tests/Classes/ClientAuthenticationTest_Success_MultiList_PartialSuccessLimitReachedFollowedBySuccessInAlternateBranch.cs index 16f08ba92..877874145 100644 --- a/src/Renci.SshNet.Tests/Classes/ClientAuthenticationTest_Success_MultiList_PartialSuccessLimitReachedFollowedBySuccessInAlternateBranch.cs +++ b/src/Renci.SshNet.Tests/Classes/ClientAuthenticationTest_Success_MultiList_PartialSuccessLimitReachedFollowedBySuccessInAlternateBranch.cs @@ -1,7 +1,8 @@ using System.Collections.Generic; + using Microsoft.VisualStudio.TestTools.UnitTesting; + using Moq; -using Renci.SshNet.Common; namespace Renci.SshNet.Tests.Classes { diff --git a/src/Renci.SshNet.Tests/Classes/ClientAuthenticationTest_Success_MultiList_PostponePartialAccessAuthenticationMethod.cs b/src/Renci.SshNet.Tests/Classes/ClientAuthenticationTest_Success_MultiList_PostponePartialAccessAuthenticationMethod.cs index dd7c14c32..4a0d5fc24 100644 --- a/src/Renci.SshNet.Tests/Classes/ClientAuthenticationTest_Success_MultiList_PostponePartialAccessAuthenticationMethod.cs +++ b/src/Renci.SshNet.Tests/Classes/ClientAuthenticationTest_Success_MultiList_PostponePartialAccessAuthenticationMethod.cs @@ -1,5 +1,7 @@ using System.Collections.Generic; + using Microsoft.VisualStudio.TestTools.UnitTesting; + using Moq; namespace Renci.SshNet.Tests.Classes @@ -19,52 +21,68 @@ protected override void SetupMocks() { var seq = new MockSequence(); - SessionMock.InSequence(seq).Setup(p => p.RegisterMessage("SSH_MSG_USERAUTH_FAILURE")); - SessionMock.InSequence(seq).Setup(p => p.RegisterMessage("SSH_MSG_USERAUTH_SUCCESS")); - SessionMock.InSequence(seq).Setup(p => p.RegisterMessage("SSH_MSG_USERAUTH_BANNER")); - - ConnectionInfoMock.InSequence(seq).Setup(p => p.CreateNoneAuthenticationMethod()) - .Returns(NoneAuthenticationMethodMock.Object); - - NoneAuthenticationMethodMock.InSequence(seq) - .Setup(p => p.Authenticate(SessionMock.Object)) - .Returns(AuthenticationResult.Failure); - ConnectionInfoMock.InSequence(seq) - .Setup(p => p.AuthenticationMethods) - .Returns(new List - { - KeyboardInteractiveAuthenticationMethodMock.Object, - PasswordAuthenticationMethodMock.Object, - PublicKeyAuthenticationMethodMock.Object - }); - NoneAuthenticationMethodMock.InSequence(seq).Setup(p => p.AllowedAuthentications).Returns(new[] { "password" }); - KeyboardInteractiveAuthenticationMethodMock.InSequence(seq).Setup(p => p.Name).Returns("keyboard-interactive"); - PasswordAuthenticationMethodMock.InSequence(seq).Setup(p => p.Name).Returns("password"); - PublicKeyAuthenticationMethodMock.InSequence(seq).Setup(p => p.Name).Returns("publickey"); - - PasswordAuthenticationMethodMock.InSequence(seq) + _ = SessionMock.InSequence(seq) + .Setup(p => p.RegisterMessage("SSH_MSG_USERAUTH_FAILURE")); + _ = SessionMock.InSequence(seq) + .Setup(p => p.RegisterMessage("SSH_MSG_USERAUTH_SUCCESS")); + _ = SessionMock.InSequence(seq) + .Setup(p => p.RegisterMessage("SSH_MSG_USERAUTH_BANNER")); + _ = ConnectionInfoMock.InSequence(seq) + .Setup(p => p.CreateNoneAuthenticationMethod()) + .Returns(NoneAuthenticationMethodMock.Object); + _ = NoneAuthenticationMethodMock.InSequence(seq) .Setup(p => p.Authenticate(SessionMock.Object)) - .Returns(AuthenticationResult.PartialSuccess); - PasswordAuthenticationMethodMock.InSequence(seq) + .Returns(AuthenticationResult.Failure); + _ = ConnectionInfoMock.InSequence(seq) + .Setup(p => p.AuthenticationMethods) + .Returns(new List + { + KeyboardInteractiveAuthenticationMethodMock.Object, + PasswordAuthenticationMethodMock.Object, + PublicKeyAuthenticationMethodMock.Object + }); + _ = NoneAuthenticationMethodMock.InSequence(seq) .Setup(p => p.AllowedAuthentications) - .Returns(new[] {"password", "publickey"}); - KeyboardInteractiveAuthenticationMethodMock.InSequence(seq).Setup(p => p.Name).Returns("keyboard-interactive"); - PasswordAuthenticationMethodMock.InSequence(seq).Setup(p => p.Name).Returns("password"); - PublicKeyAuthenticationMethodMock.InSequence(seq).Setup(p => p.Name).Returns("publickey"); - - PublicKeyAuthenticationMethodMock.InSequence(seq) - .Setup(p => p.Authenticate(SessionMock.Object)) - .Returns(AuthenticationResult.Failure); - PublicKeyAuthenticationMethodMock.InSequence(seq) - .Setup(p => p.Name) - .Returns("publickey"); - PasswordAuthenticationMethodMock.InSequence(seq) - .Setup(p => p.Authenticate(SessionMock.Object)) - .Returns(AuthenticationResult.Success); - - SessionMock.InSequence(seq).Setup(p => p.UnRegisterMessage("SSH_MSG_USERAUTH_FAILURE")); - SessionMock.InSequence(seq).Setup(p => p.UnRegisterMessage("SSH_MSG_USERAUTH_SUCCESS")); - SessionMock.InSequence(seq).Setup(p => p.UnRegisterMessage("SSH_MSG_USERAUTH_BANNER")); + .Returns(new[] { "password" }); + _ = KeyboardInteractiveAuthenticationMethodMock.InSequence(seq) + .Setup(p => p.Name) + .Returns("keyboard-interactive"); + _ = PasswordAuthenticationMethodMock.InSequence(seq) + .Setup(p => p.Name) + .Returns("password"); + _ = PublicKeyAuthenticationMethodMock.InSequence(seq) + .Setup(p => p.Name) + .Returns("publickey"); + _ = PasswordAuthenticationMethodMock.InSequence(seq) + .Setup(p => p.Authenticate(SessionMock.Object)) + .Returns(AuthenticationResult.PartialSuccess); + _ = PasswordAuthenticationMethodMock.InSequence(seq) + .Setup(p => p.AllowedAuthentications) + .Returns(new[] {"password", "publickey"}); + _ = KeyboardInteractiveAuthenticationMethodMock.InSequence(seq) + .Setup(p => p.Name) + .Returns("keyboard-interactive"); + _ = PasswordAuthenticationMethodMock.InSequence(seq) + .Setup(p => p.Name) + .Returns("password"); + _ = PublicKeyAuthenticationMethodMock.InSequence(seq) + .Setup(p => p.Name) + .Returns("publickey"); + _ = PublicKeyAuthenticationMethodMock.InSequence(seq) + .Setup(p => p.Authenticate(SessionMock.Object)) + .Returns(AuthenticationResult.Failure); + _ = PublicKeyAuthenticationMethodMock.InSequence(seq) + .Setup(p => p.Name) + .Returns("publickey"); + _ = PasswordAuthenticationMethodMock.InSequence(seq) + .Setup(p => p.Authenticate(SessionMock.Object)) + .Returns(AuthenticationResult.Success); + _ = SessionMock.InSequence(seq) + .Setup(p => p.UnRegisterMessage("SSH_MSG_USERAUTH_FAILURE")); + _ = SessionMock.InSequence(seq) + .Setup(p => p.UnRegisterMessage("SSH_MSG_USERAUTH_SUCCESS")); + _ = SessionMock.InSequence(seq) + .Setup(p => p.UnRegisterMessage("SSH_MSG_USERAUTH_BANNER")); } protected override void Arrange() diff --git a/src/Renci.SshNet.Tests/Classes/CommandAsyncResultTest.cs b/src/Renci.SshNet.Tests/Classes/CommandAsyncResultTest.cs index c04b83d72..c340f40f4 100644 --- a/src/Renci.SshNet.Tests/Classes/CommandAsyncResultTest.cs +++ b/src/Renci.SshNet.Tests/Classes/CommandAsyncResultTest.cs @@ -11,7 +11,7 @@ public class CommandAsyncResultTest : TestBase public void BytesSentTest() { var target = new CommandAsyncResult(); - int expected = new Random().Next(); + var expected = new Random().Next(); target.BytesSent = expected; diff --git a/src/Renci.SshNet.Tests/Classes/Common/AsyncResultTest.cs b/src/Renci.SshNet.Tests/Classes/Common/AsyncResultTest.cs index e000fbe6f..5a972e69f 100644 --- a/src/Renci.SshNet.Tests/Classes/Common/AsyncResultTest.cs +++ b/src/Renci.SshNet.Tests/Classes/Common/AsyncResultTest.cs @@ -1,6 +1,7 @@ using System; -using System.Threading; + using Microsoft.VisualStudio.TestTools.UnitTesting; + using Renci.SshNet.Common; using Renci.SshNet.Tests.Common; @@ -19,10 +20,9 @@ public class AsyncResultTest : TestBase /// public void EndInvokeTest1Helper() { - AsyncResult target = CreateAsyncResult(); // TODO: Initialize to an appropriate value - TResult expected = default(TResult); // TODO: Initialize to an appropriate value - TResult actual; - actual = target.EndInvoke(); + var target = CreateAsyncResult(); // TODO: Initialize to an appropriate value + var expected = default(TResult); // TODO: Initialize to an appropriate value + var actual = target.EndInvoke(); Assert.AreEqual(expected, actual); Assert.Inconclusive("Verify the correctness of this test method."); } @@ -45,9 +45,9 @@ public void EndInvokeTest1() /// public void SetAsCompletedTest1Helper() { - AsyncResult target = CreateAsyncResult(); // TODO: Initialize to an appropriate value - TResult result = default(TResult); // TODO: Initialize to an appropriate value - bool completedSynchronously = false; // TODO: Initialize to an appropriate value + var target = CreateAsyncResult(); // TODO: Initialize to an appropriate value + TResult result = default; // TODO: Initialize to an appropriate value + var completedSynchronously = false; // TODO: Initialize to an appropriate value target.SetAsCompleted(result, completedSynchronously); Assert.Inconclusive("A method that does not return a value cannot be verified."); } @@ -71,7 +71,7 @@ internal virtual AsyncResult CreateAsyncResult() [TestMethod] public void EndInvokeTest() { - AsyncResult target = CreateAsyncResult(); // TODO: Initialize to an appropriate value + var target = CreateAsyncResult(); // TODO: Initialize to an appropriate value target.EndInvoke(); Assert.Inconclusive("A method that does not return a value cannot be verified."); } @@ -82,9 +82,9 @@ public void EndInvokeTest() [TestMethod] public void SetAsCompletedTest() { - AsyncResult target = CreateAsyncResult(); // TODO: Initialize to an appropriate value + var target = CreateAsyncResult(); // TODO: Initialize to an appropriate value Exception exception = null; // TODO: Initialize to an appropriate value - bool completedSynchronously = false; // TODO: Initialize to an appropriate value + var completedSynchronously = false; // TODO: Initialize to an appropriate value target.SetAsCompleted(exception, completedSynchronously); Assert.Inconclusive("A method that does not return a value cannot be verified."); } @@ -95,9 +95,8 @@ public void SetAsCompletedTest() [TestMethod] public void AsyncStateTest() { - AsyncResult target = CreateAsyncResult(); // TODO: Initialize to an appropriate value - object actual; - actual = target.AsyncState; + var target = CreateAsyncResult(); // TODO: Initialize to an appropriate value + var actual = target.AsyncState; Assert.Inconclusive("Verify the correctness of this test method."); } @@ -107,9 +106,8 @@ public void AsyncStateTest() [TestMethod] public void AsyncWaitHandleTest() { - AsyncResult target = CreateAsyncResult(); // TODO: Initialize to an appropriate value - WaitHandle actual; - actual = target.AsyncWaitHandle; + var target = CreateAsyncResult(); // TODO: Initialize to an appropriate value + var actual = target.AsyncWaitHandle; Assert.Inconclusive("Verify the correctness of this test method."); } @@ -119,9 +117,8 @@ public void AsyncWaitHandleTest() [TestMethod] public void CompletedSynchronouslyTest() { - AsyncResult target = CreateAsyncResult(); // TODO: Initialize to an appropriate value - bool actual; - actual = target.CompletedSynchronously; + var target = CreateAsyncResult(); // TODO: Initialize to an appropriate value + var actual = target.CompletedSynchronously; Assert.Inconclusive("Verify the correctness of this test method."); } @@ -131,9 +128,8 @@ public void CompletedSynchronouslyTest() [TestMethod] public void IsCompletedTest() { - AsyncResult target = CreateAsyncResult(); // TODO: Initialize to an appropriate value - bool actual; - actual = target.IsCompleted; + var target = CreateAsyncResult(); // TODO: Initialize to an appropriate value + var actual = target.IsCompleted; Assert.Inconclusive("Verify the correctness of this test method."); } } diff --git a/src/Renci.SshNet.Tests/Classes/Common/AuthenticationPasswordChangeEventArgsTest.cs b/src/Renci.SshNet.Tests/Classes/Common/AuthenticationPasswordChangeEventArgsTest.cs index e381cf1b0..9200d2a43 100644 --- a/src/Renci.SshNet.Tests/Classes/Common/AuthenticationPasswordChangeEventArgsTest.cs +++ b/src/Renci.SshNet.Tests/Classes/Common/AuthenticationPasswordChangeEventArgsTest.cs @@ -19,8 +19,8 @@ public class AuthenticationPasswordChangeEventArgsTest : TestBase [TestMethod] public void AuthenticationPasswordChangeEventArgsConstructorTest() { - string username = string.Empty; // TODO: Initialize to an appropriate value - AuthenticationPasswordChangeEventArgs target = new AuthenticationPasswordChangeEventArgs(username); + var username = string.Empty; // TODO: Initialize to an appropriate value + var target = new AuthenticationPasswordChangeEventArgs(username); Assert.Inconclusive("TODO: Implement code to verify target"); } @@ -31,7 +31,7 @@ public void AuthenticationPasswordChangeEventArgsConstructorTest() public void NewPasswordTest() { string username = string.Empty; // TODO: Initialize to an appropriate value - AuthenticationPasswordChangeEventArgs target = new AuthenticationPasswordChangeEventArgs(username); // TODO: Initialize to an appropriate value + var target = new AuthenticationPasswordChangeEventArgs(username); // TODO: Initialize to an appropriate value byte[] expected = null; // TODO: Initialize to an appropriate value byte[] actual; target.NewPassword = expected; diff --git a/src/Renci.SshNet.Tests/Classes/Common/AuthenticationPromptEventArgsTest.cs b/src/Renci.SshNet.Tests/Classes/Common/AuthenticationPromptEventArgsTest.cs index 698d1ab23..47b83126f 100644 --- a/src/Renci.SshNet.Tests/Classes/Common/AuthenticationPromptEventArgsTest.cs +++ b/src/Renci.SshNet.Tests/Classes/Common/AuthenticationPromptEventArgsTest.cs @@ -20,11 +20,11 @@ public class AuthenticationPromptEventArgsTest : TestBase [TestMethod] public void AuthenticationPromptEventArgsConstructorTest() { - string username = string.Empty; // TODO: Initialize to an appropriate value - string instruction = string.Empty; // TODO: Initialize to an appropriate value - string language = string.Empty; // TODO: Initialize to an appropriate value + var username = string.Empty; // TODO: Initialize to an appropriate value + var instruction = string.Empty; // TODO: Initialize to an appropriate value + var language = string.Empty; // TODO: Initialize to an appropriate value IEnumerable prompts = null; // TODO: Initialize to an appropriate value - AuthenticationPromptEventArgs target = new AuthenticationPromptEventArgs(username, instruction, language, prompts); + var target = new AuthenticationPromptEventArgs(username, instruction, language, prompts); Assert.Inconclusive("TODO: Implement code to verify target"); } } diff --git a/src/Renci.SshNet.Tests/Classes/Common/AuthenticationPromptTest.cs b/src/Renci.SshNet.Tests/Classes/Common/AuthenticationPromptTest.cs index 763f74094..5fbf25821 100644 --- a/src/Renci.SshNet.Tests/Classes/Common/AuthenticationPromptTest.cs +++ b/src/Renci.SshNet.Tests/Classes/Common/AuthenticationPromptTest.cs @@ -17,10 +17,10 @@ public class AuthenticationPromptTest : TestBase [TestMethod] public void AuthenticationPromptConstructorTest() { - int id = 0; // TODO: Initialize to an appropriate value - bool isEchoed = false; // TODO: Initialize to an appropriate value - string request = string.Empty; // TODO: Initialize to an appropriate value - AuthenticationPrompt target = new AuthenticationPrompt(id, isEchoed, request); + var id = 0; // TODO: Initialize to an appropriate value + var isEchoed = false; // TODO: Initialize to an appropriate value + var request = string.Empty; // TODO: Initialize to an appropriate value + var target = new AuthenticationPrompt(id, isEchoed, request); Assert.Inconclusive("TODO: Implement code to verify target"); } @@ -30,14 +30,13 @@ public void AuthenticationPromptConstructorTest() [TestMethod] public void ResponseTest() { - int id = 0; // TODO: Initialize to an appropriate value - bool isEchoed = false; // TODO: Initialize to an appropriate value - string request = string.Empty; // TODO: Initialize to an appropriate value - AuthenticationPrompt target = new AuthenticationPrompt(id, isEchoed, request); // TODO: Initialize to an appropriate value - string expected = string.Empty; // TODO: Initialize to an appropriate value - string actual; + var id = 0; // TODO: Initialize to an appropriate value + var isEchoed = false; // TODO: Initialize to an appropriate value + var request = string.Empty; // TODO: Initialize to an appropriate value + var target = new AuthenticationPrompt(id, isEchoed, request); // TODO: Initialize to an appropriate value + var expected = string.Empty; // TODO: Initialize to an appropriate value target.Response = expected; - actual = target.Response; + var actual = target.Response; Assert.AreEqual(expected, actual); Assert.Inconclusive("Verify the correctness of this test method."); } diff --git a/src/Renci.SshNet.Tests/Classes/Common/BigIntegerTest.cs b/src/Renci.SshNet.Tests/Classes/Common/BigIntegerTest.cs index c99fb2a6e..0640697a2 100644 --- a/src/Renci.SshNet.Tests/Classes/Common/BigIntegerTest.cs +++ b/src/Renci.SshNet.Tests/Classes/Common/BigIntegerTest.cs @@ -28,7 +28,7 @@ namespace Renci.SshNet.Tests.Classes.Common [TestClass] public class BigIntegerTest { - private static readonly byte[] huge_a = + private static readonly byte[] Huge_a = { 0x1D, 0x33, 0xFB, 0xFE, 0xB1, 0x2, 0x85, 0x44, 0xCA, 0xDC, 0xFB, 0x70, 0xD, 0x39, 0xB1, 0x47, 0xB6, 0xE6, 0xA2, 0xD1, 0x19, 0x1E, 0x9F, 0xE4, 0x3C, 0x1E, 0x16, 0x56, 0x13, 0x9C, 0x4D, 0xD3, @@ -36,7 +36,7 @@ public class BigIntegerTest 0xF6, 0x8C }; - private static readonly byte[] huge_b = + private static readonly byte[] Huge_b = { 0x96, 0x5, 0xDA, 0xFE, 0x93, 0x17, 0xC1, 0x93, 0xEC, 0x2F, 0x30, 0x2D, 0x8F, 0x28, 0x13, 0x99, 0x70, 0xF4, 0x4C, 0x60, 0xA6, 0x49, 0x24, 0xF9, 0xB3, 0x4A, 0x41, 0x67, 0xDC, 0xDD, 0xB1, @@ -44,7 +44,7 @@ public class BigIntegerTest 0xA8, 0xC8, 0xB0, 0x20, 0x95, 0xE6, 0x4C, 0xE1, 0xE0, 0x4B, 0x49, 0xD5, 0x5A, 0xB7 }; - private static readonly byte[] huge_add = + private static readonly byte[] Huge_add = { 0xB3, 0x38, 0xD5, 0xFD, 0x45, 0x1A, 0x46, 0xD8, 0xB6, 0xC, 0x2C, 0x9E, 0x9C, 0x61, 0xC4, 0xE0, 0x26, 0xDB, 0xEF, 0x31, 0xC0, 0x67, 0xC3, 0xDD, 0xF0, 0x68, 0x57, 0xBD, 0xEF, 0x79, 0xFF, @@ -52,7 +52,7 @@ public class BigIntegerTest 0x16, 0xBF, 0x3D, 0x20, 0x95, 0xE6, 0x4C, 0xE1, 0xE0, 0x4B, 0x49, 0xD5, 0x5A, 0xB7 }; - private static readonly byte[] a_m_b = + private static readonly byte[] A_m_b = { 0x87, 0x2D, 0x21, 0x0, 0x1E, 0xEB, 0xC3, 0xB0, 0xDD, 0xAC, 0xCB, 0x43, 0x7E, 0x10, 0x9E, 0xAE, 0x45, 0xF2, 0x55, 0x71, 0x73, 0xD4, 0x7A, 0xEB, 0x88, 0xD3, 0xD4, 0xEE, 0x36, 0xBE, 0x9B, 0x2D, @@ -60,7 +60,7 @@ public class BigIntegerTest 0x2D, 0xDC, 0xDE, 0x6A, 0x19, 0xB3, 0x1E, 0x1F, 0xB4, 0xB6, 0x2A, 0xA5, 0x48 }; - private static readonly byte[] b_m_a = + private static readonly byte[] B_m_a = { 0x79, 0xD2, 0xDE, 0xFF, 0xE1, 0x14, 0x3C, 0x4F, 0x22, 0x53, 0x34, 0xBC, 0x81, 0xEF, 0x61, 0x51, 0xBA, 0xD, 0xAA, 0x8E, 0x8C, 0x2B, 0x85, 0x14, 0x77, 0x2C, 0x2B, 0x11, 0xC9, 0x41, 0x64, @@ -68,7 +68,7 @@ public class BigIntegerTest 0x3B, 0xD2, 0x23, 0x21, 0x95, 0xE6, 0x4C, 0xE1, 0xE0, 0x4B, 0x49, 0xD5, 0x5A, 0xB7 }; - private static readonly byte[] huge_mul = + private static readonly byte[] Huge_mul = { 0xFE, 0x83, 0xE1, 0x9B, 0x8D, 0x61, 0x40, 0xD1, 0x60, 0x19, 0xBD, 0x38, 0xF0, 0xFF, 0x90, 0xAE, 0xDD, 0xAE, 0x73, 0x2C, 0x20, 0x23, 0xCF, 0x6, 0x7A, 0xB4, 0x1C, 0xE7, 0xD9, 0x64, 0x96, @@ -79,18 +79,18 @@ public class BigIntegerTest 0x57, 0x40, 0x51, 0xB6, 0x5D, 0xC, 0x17, 0xD1, 0x86, 0xE9, 0xA4, 0x20 }; - private static readonly byte[] huge_div = {0x0}; + private static readonly byte[] Huge_div = {0x0}; - private static readonly byte[] huge_rem = + private static readonly byte[] Huge_rem = { 0x1D, 0x33, 0xFB, 0xFE, 0xB1, 0x2, 0x85, 0x44, 0xCA, 0xDC, 0xFB, 0x70, 0xD, 0x39, 0xB1, 0x47, 0xB6, 0xE6, 0xA2, 0xD1, 0x19, 0x1E, 0x9F, 0xE4, 0x3C, 0x1E, 0x16, 0x56, 0x13, 0x9C, 0x4D, 0xD3, 0x5C, 0x74, 0xC9, 0xBD, 0xFA, 0x56, 0x40, 0x58, 0xAC, 0x20, 0x6B, 0x55, 0xA2, 0xD5, 0x41, 0x38, 0xA4, 0x6D, 0xF6, 0x8C }; - private static readonly byte[][] add_a = {new byte[] {1}, new byte[] {0xFF}, huge_a}; - private static readonly byte[][] add_b = {new byte[] {1}, new byte[] {1}, huge_b}; - private static readonly byte[][] add_c = {new byte[] {2}, new byte[] {0}, huge_add}; + private static readonly byte[][] Add_a = { new byte[] { 1 }, new byte[] { 0xFF }, Huge_a }; + private static readonly byte[][] Add_b = { new byte[] { 1 }, new byte[] { 1 }, Huge_b }; + private static readonly byte[][] Add_c = { new byte[] { 2 }, new byte[] { 0 }, Huge_add }; private readonly NumberFormatInfo _nfi = NumberFormatInfo.InvariantInfo; private NumberFormatInfo _nfiUser; @@ -98,22 +98,24 @@ public class BigIntegerTest [TestInitialize] public void SetUpFixture() { - _nfiUser = new NumberFormatInfo(); - _nfiUser.CurrencyDecimalDigits = 3; - _nfiUser.CurrencyDecimalSeparator = ":"; - _nfiUser.CurrencyGroupSeparator = "/"; - _nfiUser.CurrencyGroupSizes = new[] { 2, 1, 0 }; - _nfiUser.CurrencyNegativePattern = 10; // n $- - _nfiUser.CurrencyPositivePattern = 3; // n $ - _nfiUser.CurrencySymbol = "XYZ"; - _nfiUser.PercentDecimalDigits = 1; - _nfiUser.PercentDecimalSeparator = ";"; - _nfiUser.PercentGroupSeparator = "~"; - _nfiUser.PercentGroupSizes = new[] { 1 }; - _nfiUser.PercentNegativePattern = 2; - _nfiUser.PercentPositivePattern = 2; - _nfiUser.PercentSymbol = "%%%"; - _nfiUser.NumberDecimalSeparator = "."; + _nfiUser = new NumberFormatInfo + { + CurrencyDecimalDigits = 3, + CurrencyDecimalSeparator = ":", + CurrencyGroupSeparator = "/", + CurrencyGroupSizes = new[] { 2, 1, 0 }, + CurrencyNegativePattern = 10, // n $- + CurrencyPositivePattern = 3, // n $ + CurrencySymbol = "XYZ", + PercentDecimalDigits = 1, + PercentDecimalSeparator = ";", + PercentGroupSeparator = "~", + PercentGroupSizes = new[] { 1 }, + PercentNegativePattern = 2, + PercentPositivePattern = 2, + PercentSymbol = "%%%", + NumberDecimalSeparator = "." + }; } [TestMethod] @@ -136,10 +138,10 @@ public void Mul() [TestMethod] public void TestHugeMul() { - var a = new BigInteger(huge_a); - var b = new BigInteger(huge_b); + var a = new BigInteger(Huge_a); + var b = new BigInteger(Huge_b); - Assert.IsTrue(huge_mul.IsEqualTo((a * b).ToByteArray())); + Assert.IsTrue(Huge_mul.IsEqualTo((a * b).ToByteArray())); } [TestMethod] @@ -152,11 +154,13 @@ public void DivRem() for (var j = 0; j < values.Length; ++j) { if (values[j] == 0) + { continue; + } + var a = new BigInteger(values[i]); var b = new BigInteger(values[j]); - BigInteger d; - var c = BigInteger.DivRem(a, b, out d); + var c = BigInteger.DivRem(a, b, out var d); Assert.AreEqual(values[i] / values[j], (long)c, "#a_" + i + "_" + j); Assert.AreEqual(values[i] % values[j], (long)d, "#b_" + i + "_" + j); @@ -167,13 +171,12 @@ public void DivRem() [TestMethod] public void TestHugeDivRem() { - var a = new BigInteger(huge_a); - var b = new BigInteger(huge_b); - BigInteger d; - var c = BigInteger.DivRem(a, b, out d); + var a = new BigInteger(Huge_a); + var b = new BigInteger(Huge_b); + var c = BigInteger.DivRem(a, b, out var d); - AssertEqual(huge_div, c.ToByteArray()); - AssertEqual(huge_rem, d.ToByteArray()); + AssertEqual(Huge_div, c.ToByteArray()); + AssertEqual(Huge_rem, d.ToByteArray()); } [TestMethod] @@ -181,7 +184,7 @@ public void Pow() { try { - BigInteger.Pow(1, -1); + _ = BigInteger.Pow(1, -1); Assert.Fail("#1"); } catch (ArgumentOutOfRangeException) { } @@ -198,14 +201,14 @@ public void ModPow() { try { - BigInteger.ModPow(1, -1, 5); + _ = BigInteger.ModPow(1, -1, 5); Assert.Fail("#1"); } catch (ArgumentOutOfRangeException) { } try { - BigInteger.ModPow(1, 5, 0); + _ = BigInteger.ModPow(1, 5, 0); Assert.Fail("#2"); } catch (DivideByZeroException) { } @@ -281,8 +284,7 @@ public void DivRemByZero() { try { - BigInteger d; - BigInteger.DivRem(100, 0, out d); + _ = BigInteger.DivRem(100, 0, out var d); Assert.Fail("#1"); } catch (DivideByZeroException) @@ -293,16 +295,16 @@ public void DivRemByZero() [TestMethod] public void TestAdd() { - for (var i = 0; i < add_a.Length; ++i) + for (var i = 0; i < Add_a.Length; ++i) { - var a = new BigInteger(add_a[i]); - var b = new BigInteger(add_b[i]); - var c = new BigInteger(add_c[i]); + var a = new BigInteger(Add_a[i]); + var b = new BigInteger(Add_b[i]); + var c = new BigInteger(Add_c[i]); Assert.AreEqual(c, a + b, "#" + i + "a"); Assert.AreEqual(c, b + a, "#" + i + "b"); Assert.AreEqual(c, BigInteger.Add(a, b), "#" + i + "c"); - AssertEqual(add_c[i], (a + b).ToByteArray()); + AssertEqual(Add_c[i], (a + b).ToByteArray()); } } @@ -326,11 +328,11 @@ public void TestAdd2() [TestMethod] public void TestHugeSub() { - var a = new BigInteger(huge_a); - var b = new BigInteger(huge_b); + var a = new BigInteger(Huge_a); + var b = new BigInteger(Huge_b); - AssertEqual(a_m_b, (a - b).ToByteArray()); - AssertEqual(b_m_a, (b - a).ToByteArray()); + AssertEqual(A_m_b, (a - b).ToByteArray()); + AssertEqual(B_m_a, (b - a).ToByteArray()); } [TestMethod] @@ -732,7 +734,7 @@ public void ByteArrayCtorRoundTrip() [TestMethod] public void TestIntCtorProperties() { - BigInteger a = new BigInteger(10); + var a = new BigInteger(10); Assert.IsTrue(a.IsEven, "#1"); Assert.IsFalse(a.IsOne, "#2"); Assert.IsFalse(a.IsPowerOfTwo, "#3"); @@ -784,11 +786,11 @@ public void TestToStringFmt() [TestMethod] public void TestToStringFmtProvider() { - NumberFormatInfo info = new NumberFormatInfo - { - NegativeSign = ">", - PositiveSign = "%" - }; + var info = new NumberFormatInfo + { + NegativeSign = ">", + PositiveSign = "%" + }; Assert.AreEqual("10", new BigInteger(10).ToString(info), "#1"); Assert.AreEqual(">10", new BigInteger(-10).ToString(info), "#2"); @@ -801,12 +803,16 @@ public void TestToStringFmtProvider() Assert.AreEqual("10", new BigInteger(10).ToString("R", info), "#9"); Assert.AreEqual(">10", new BigInteger(-10).ToString("R", info), "#10"); - info = new NumberFormatInfo(); - info.NegativeSign = "#$%"; + info = new NumberFormatInfo + { + NegativeSign = "#$%" + }; + Assert.AreEqual("#$%10", new BigInteger(-10).ToString(info), "#2"); Assert.AreEqual("#$%10", new BigInteger(-10).ToString(null, info), "#2"); info = new NumberFormatInfo(); + Assert.AreEqual("-10", new BigInteger(-10).ToString(info), "#2"); } @@ -816,21 +822,21 @@ public void TestToIntOperator() { try { - int v = (int)new BigInteger(huge_a); + _ = (int) new BigInteger(Huge_a); Assert.Fail("#1"); } catch (OverflowException) { } try { - int v = (int)new BigInteger(1L + int.MaxValue); + _ = (int) new BigInteger(1L + int.MaxValue); Assert.Fail("#2"); } catch (OverflowException) { } try { - int v = (int)new BigInteger(-1L + int.MinValue); + _ = (int) new BigInteger(-1L + int.MinValue); Assert.Fail("#3"); } catch (OverflowException) { } @@ -845,7 +851,7 @@ public void TestToLongOperator() { try { - long v = (long)new BigInteger(huge_a); + _ = (long) new BigInteger(Huge_a); Assert.Fail("#1"); } catch (OverflowException) { } @@ -853,7 +859,7 @@ public void TestToLongOperator() //long.MaxValue + 1 try { - long v = (long)new BigInteger(new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00 }); + _ = (long) new BigInteger(new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00 }); Assert.Fail("#2"); } catch (OverflowException) { } @@ -861,7 +867,7 @@ public void TestToLongOperator() //TODO long.MinValue - 1 try { - long v = (long)new BigInteger(new byte[] { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F, 0xFF }); + _ = (long) new BigInteger(new byte[] { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F, 0xFF }); Assert.Fail("#3"); } catch (OverflowException) { } @@ -931,14 +937,14 @@ public void ShortOperators() try { - short x = (short)new BigInteger(10000000); + _ = (short) new BigInteger(10000000); Assert.Fail("#3"); } catch (OverflowException) { } try { - short x = (short)new BigInteger(-10000000); + _ = (short) new BigInteger(-10000000); Assert.Fail("#4"); } catch (OverflowException) { } @@ -949,7 +955,7 @@ public void Ctor_Double_NaN() { try { - new BigInteger(double.NaN); + _ = new BigInteger(double.NaN); Assert.Fail(); } catch (OverflowException) @@ -962,7 +968,7 @@ public void Ctor_Double_NegativeInfinity() { try { - new BigInteger(double.NegativeInfinity); + _ = new BigInteger(double.NegativeInfinity); Assert.Fail(); } catch (OverflowException) @@ -975,7 +981,7 @@ public void Ctor_Double_PositiveInfinity() { try { - new BigInteger(double.PositiveInfinity); + _ = new BigInteger(double.PositiveInfinity); Assert.Fail(); } catch (OverflowException) @@ -1019,9 +1025,9 @@ public void DoubleConversion() Assert.AreEqual(result4, (double)new BigInteger(new byte[] { 0, 0, 0, 0, 48, 128, 208, 159, 60, 46, 59, 3 }), "#13"); Assert.AreEqual(result5, (double)new BigInteger(new byte[] { 0, 0, 0, 0, 64, 128, 208, 159, 60, 46, 59, 3 }), "#14"); - Assert.AreEqual(BitConverter.Int64BitsToDouble(-2748107935317889142), (double)new BigInteger(huge_a), "#15"); - Assert.AreEqual(BitConverter.Int64BitsToDouble(-2354774254443231289), (double)new BigInteger(huge_b), "#16"); - Assert.AreEqual(BitConverter.Int64BitsToDouble(8737073938546854790), (double)new BigInteger(huge_mul), "#17"); + Assert.AreEqual(BitConverter.Int64BitsToDouble(-2748107935317889142), (double)new BigInteger(Huge_a), "#15"); + Assert.AreEqual(BitConverter.Int64BitsToDouble(-2354774254443231289), (double)new BigInteger(Huge_b), "#16"); + Assert.AreEqual(BitConverter.Int64BitsToDouble(8737073938546854790), (double)new BigInteger(Huge_mul), "#17"); Assert.AreEqual(BitConverter.Int64BitsToDouble(6912920136897069886), (double)(2278888483353476799 * BigInteger.Pow(2, 451)), "#18"); Assert.AreEqual(double.PositiveInfinity, (double)(843942696292817306 * BigInteger.Pow(2, 965)), "#19"); @@ -1070,14 +1076,14 @@ public void Parse() { try { - BigInteger.Parse(null); + _ = BigInteger.Parse(null); Assert.Fail("#1"); } catch (ArgumentNullException) { } try { - BigInteger.Parse(""); + _ = BigInteger.Parse(""); Assert.Fail("#2"); } catch (FormatException) { } @@ -1085,28 +1091,28 @@ public void Parse() try { - BigInteger.Parse(" "); + _ = BigInteger.Parse(" "); Assert.Fail("#3"); } catch (FormatException) { } try { - BigInteger.Parse("hh"); + _ = BigInteger.Parse("hh"); Assert.Fail("#4"); } catch (FormatException) { } try { - BigInteger.Parse("-"); + _ = BigInteger.Parse("-"); Assert.Fail("#5"); } catch (FormatException) { } try { - BigInteger.Parse("-+"); + _ = BigInteger.Parse("-+"); Assert.Fail("#6"); } catch (FormatException) { } @@ -1137,7 +1143,7 @@ public void Parse() try { - BigInteger.Parse("2E3.0", NumberStyles.AllowExponent); // decimal notation for the exponent + _ = BigInteger.Parse("2E3.0", NumberStyles.AllowExponent); // decimal notation for the exponent Assert.Fail("#25"); } catch (FormatException) @@ -1146,7 +1152,7 @@ public void Parse() try { - Int32.Parse("2" + dsep + "09E1", NumberStyles.AllowDecimalPoint | NumberStyles.AllowExponent); + _ = int.Parse("2" + dsep + "09E1", NumberStyles.AllowDecimalPoint | NumberStyles.AllowExponent); Assert.Fail("#26"); } catch (OverflowException) @@ -1157,9 +1163,7 @@ public void Parse() [TestMethod] public void TryParse_Value_ShouldReturnFalseWhenValueIsNull() { - BigInteger x; - - var actual = BigInteger.TryParse(null, out x); + var actual = BigInteger.TryParse(null, out var x); Assert.IsFalse(actual); Assert.AreEqual(BigInteger.Zero, x); @@ -1168,9 +1172,7 @@ public void TryParse_Value_ShouldReturnFalseWhenValueIsNull() [TestMethod] public void TryParse_Value() { - BigInteger x; - - Assert.IsFalse(BigInteger.TryParse("", out x)); + Assert.IsFalse(BigInteger.TryParse("", out var x)); Assert.AreEqual(BigInteger.Zero, x); Assert.IsFalse(BigInteger.TryParse(" ", out x)); @@ -1198,9 +1200,7 @@ public void TryParse_Value() [TestMethod] public void TryParse_ValueAndStyleAndProvider() { - BigInteger x; - - Assert.IsFalse(BigInteger.TryParse("null", NumberStyles.None, null, out x)); + Assert.IsFalse(BigInteger.TryParse("null", NumberStyles.None, null, out var x)); Assert.AreEqual(BigInteger.Zero, x); Assert.IsFalse(BigInteger.TryParse("-10", NumberStyles.None, null, out x)); @@ -1252,9 +1252,7 @@ public void TryParse_ValueAndStyleAndProvider() [TestMethod] public void TryParse_ValueAndStyleAndProvider_ShouldReturnFalseWhenValueIsNull() { - BigInteger x; - - var actual = BigInteger.TryParse(null, NumberStyles.Any, CultureInfo.InvariantCulture, out x); + var actual = BigInteger.TryParse(null, NumberStyles.Any, CultureInfo.InvariantCulture, out var x); Assert.IsFalse(actual); Assert.AreEqual(BigInteger.Zero, x); @@ -1284,20 +1282,17 @@ public void TryParseWeirdCulture() { var old = Thread.CurrentThread.CurrentCulture; var cur = (CultureInfo)old.Clone(); - - var ninfo = new NumberFormatInfo - { - NegativeSign = ">", - PositiveSign = "%" - }; - cur.NumberFormat = ninfo; + cur.NumberFormat = new NumberFormatInfo + { + NegativeSign = ">", + PositiveSign = "%" + }; Thread.CurrentThread.CurrentCulture = cur; try { - BigInteger x; - Assert.IsTrue(BigInteger.TryParse("%11", out x)); + Assert.IsTrue(BigInteger.TryParse("%11", out var x)); Assert.AreEqual(11, (int) x); Assert.IsTrue(BigInteger.TryParse(">11", out x)); @@ -1403,7 +1398,7 @@ public void LeftShiftByInt() public void RightShiftByInt() { var v = BigInteger.Parse("230794411440927908251127453634"); - v = v * BigInteger.Pow(2, 70); + v *= BigInteger.Pow(2, 70); Assert.AreEqual("272473948255566133040220955950698177909118065442816", (v >> 0).ToString(), "#0"); Assert.AreEqual("136236974127783066520110477975349088954559032721408", (v >> 1).ToString(), "#1"); @@ -1482,12 +1477,15 @@ public void Bug10887() { BigInteger b = 0; for (var i = 1; i <= 16; i++) - b = b * 256 + i; + { + b = (b * 256) + i; + } + var p = BigInteger.Pow(2, 32); Assert.AreEqual("1339673755198158349044581307228491536", b.ToString()); Assert.AreEqual("1339673755198158349044581307228491536", ((b << 32) / p).ToString()); - Assert.AreEqual("1339673755198158349044581307228491536", (b * p >> 32).ToString()); + Assert.AreEqual("1339673755198158349044581307228491536", ((b * p) >> 32).ToString()); } [TestMethod] @@ -1567,22 +1565,22 @@ public void Bug16526() public void ToArray_Performance() { const int loopCount = 100000000; - var bigInteger = new BigInteger(huge_a); + var bigInteger = new BigInteger(Huge_a); var stopWatch = new Stopwatch(); GC.Collect(); - GC.WaitForFullGCComplete(); + _ = GC.WaitForFullGCComplete(); stopWatch.Start(); for (var i = 0; i < loopCount; i++) { - bigInteger.ToByteArray(); + _ = bigInteger.ToByteArray(); } GC.Collect(); - GC.WaitForFullGCComplete(); + _ = GC.WaitForFullGCComplete(); stopWatch.Stop(); @@ -1599,17 +1597,17 @@ public void Ctor_ByteArray_Performance() var stopWatch = new Stopwatch(); GC.Collect(); - GC.WaitForFullGCComplete(); + _ = GC.WaitForFullGCComplete(); stopWatch.Start(); for (var i = 0; i < loopCount; i++) { - new BigInteger(huge_a); + _ = new BigInteger(Huge_a); } GC.Collect(); - GC.WaitForFullGCComplete(); + _ = GC.WaitForFullGCComplete(); stopWatch.Stop(); @@ -1656,8 +1654,7 @@ public void Zero() public void Random() { var max = "26432534714839143538998938508341375449389492936207135611931371046236385860280414659368073862189301615603000443463893527273703804361856647266218472759410964268979057798543462774631912259980510080575520846081682603934587649566608158932346151315049355432937004801361578344502537300865702429436253728164365180058583916866804254965536833106467354901266304654706123552932560896874808786957654734387252964281680963136344135750381838556467139236094522411774117748615141352874979928570068255439327082539676660277104989857941859821396157749462154431239343148671646397611770487668571604363151098131876313773395912355145689712506"; - BigInteger maxBigInt; - Assert.IsTrue(BigInteger.TryParse(max, NumberStyles.Number, NumberFormatInfo.CurrentInfo, out maxBigInt)); + Assert.IsTrue(BigInteger.TryParse(max, NumberStyles.Number, NumberFormatInfo.CurrentInfo, out var maxBigInt)); var random = BigInteger.One; while (random <= BigInteger.One || random >= maxBigInt) @@ -1670,8 +1667,7 @@ public void Random() public void TestClientExhcangeGenerationItem130() { var test = "1090748135619415929450294929359784500348155124953172211774101106966150168922785639028532473848836817769712164169076432969224698752674677662739994265785437233596157045970922338040698100507861033047312331823982435279475700199860971612732540528796554502867919746776983759391475987142521315878719577519148811830879919426939958487087540965716419167467499326156226529675209172277001377591248147563782880558861083327174154014975134893125116015776318890295960698011614157721282527539468816519319333337503114777192360412281721018955834377615480468479252748867320362385355596601795122806756217713579819870634321561907813255153703950795271232652404894983869492174481652303803498881366210508647263668376514131031102336837488999775744046733651827239395353540348414872854639719294694323450186884189822544540647226987292160693184734654941906936646576130260972193280317171696418971553954161446191759093719524951116705577362073481319296041201283516154269044389257727700289684119460283480452306204130024913879981135908026983868205969318167819680850998649694416907952712904962404937775789698917207356355227455066183815847669135530549755439819480321732925869069136146085326382334628745456398071603058051634209386708703306545903199608523824513729625136659128221100967735450519952404248198262813831097374261650380017277916975324134846574681307337017380830353680623216336949471306191686438249305686413380231046096450953594089375540285037292470929395114028305547452584962074309438151825437902976012891749355198678420603722034900311364893046495761404333938686140037848030916292543273684533640032637639100774502371542479302473698388692892420946478947733800387782741417786484770190108867879778991633218628640533982619322466154883011452291890252336487236086654396093853898628805813177559162076363154436494477507871294119841637867701722166609831201845484078070518041336869808398454625586921201308185638888082699408686536045192649569198110353659943111802300636106509865023943661829436426563007917282050894429388841748885398290707743052973605359277515749619730823773215894755121761467887865327707115573804264519206349215850195195364813387526811742474131549802130246506341207020335797706780705406945275438806265978516209706795702579244075380490231741030862614968783306207869687868108423639971983209077624758080499988275591392787267627182442892809646874228263172435642368588260139161962836121481966092745325488641054238839295138992979335446110090325230955276870524611359124918392740353154294858383359"; - BigInteger prime; - BigInteger.TryParse(test, NumberStyles.Number, NumberFormatInfo.CurrentInfo, out prime); + _ = BigInteger.TryParse(test, NumberStyles.Number, NumberFormatInfo.CurrentInfo, out var prime); BigInteger group = 2; var bitLength = prime.BitLength; @@ -1683,15 +1679,15 @@ public void TestClientExhcangeGenerationItem130() //clientExchangeValue = BigInteger.ModPow(group, randomValue, prime); clientExchangeValue = (group ^ randomValue) % prime; - } while (clientExchangeValue < 1 || clientExchangeValue > (prime - 1)); + } + while (clientExchangeValue < 1 || clientExchangeValue > (prime - 1)); } [TestMethod] public void TestClientExhcangeGenerationGroup1() { var test = "00FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF"; - BigInteger prime; - BigInteger.TryParse(test, NumberStyles.AllowHexSpecifier, NumberFormatInfo.CurrentInfo, out prime); + _ = BigInteger.TryParse(test, NumberStyles.AllowHexSpecifier, NumberFormatInfo.CurrentInfo, out var prime); BigInteger group = 2; var bitLength = prime.BitLength; @@ -1703,15 +1699,15 @@ public void TestClientExhcangeGenerationGroup1() //clientExchangeValue = BigInteger.ModPow(group, randomValue, prime); clientExchangeValue = (group ^ randomValue) % prime; - } while (clientExchangeValue < 1 || clientExchangeValue > (prime - 1)); + } + while (clientExchangeValue < 1 || clientExchangeValue > (prime - 1)); } [TestMethod] public void TestClientExhcangeGenerationGroup14() { var test = "00FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AACAA68FFFFFFFFFFFFFFFF"; - BigInteger prime; - BigInteger.TryParse(test, NumberStyles.AllowHexSpecifier, NumberFormatInfo.CurrentInfo, out prime); + _ = BigInteger.TryParse(test, NumberStyles.AllowHexSpecifier, NumberFormatInfo.CurrentInfo, out var prime); BigInteger group = 2; var bitLength = prime.BitLength; @@ -1723,7 +1719,8 @@ public void TestClientExhcangeGenerationGroup14() //clientExchangeValue = BigInteger.ModPow(group, randomValue, prime); clientExchangeValue = (group ^ randomValue) % prime; - } while (clientExchangeValue < 1 || clientExchangeValue > (prime - 1)); + } + while (clientExchangeValue < 1 || clientExchangeValue > (prime - 1)); } private static void AssertEqual(byte[] a, byte[] b) diff --git a/src/Renci.SshNet.Tests/Classes/Common/ChannelOpenFailedEventArgsTest.cs b/src/Renci.SshNet.Tests/Classes/Common/ChannelOpenFailedEventArgsTest.cs index 8a8efdf27..2265a5f79 100644 --- a/src/Renci.SshNet.Tests/Classes/Common/ChannelOpenFailedEventArgsTest.cs +++ b/src/Renci.SshNet.Tests/Classes/Common/ChannelOpenFailedEventArgsTest.cs @@ -4,10 +4,10 @@ namespace Renci.SshNet.Tests.Classes.Common { /// - /// Provides data for event. + /// Provides data for event. /// [TestClass] public class ChannelOpenFailedEventArgsTest : TestBase { } -} \ No newline at end of file +} diff --git a/src/Renci.SshNet.Tests/Classes/Common/CountdownEventTest.cs b/src/Renci.SshNet.Tests/Classes/Common/CountdownEventTest.cs index 6ab52acef..427e07ccf 100644 --- a/src/Renci.SshNet.Tests/Classes/Common/CountdownEventTest.cs +++ b/src/Renci.SshNet.Tests/Classes/Common/CountdownEventTest.cs @@ -1,6 +1,7 @@ using System; using System.Diagnostics; using System.Threading; + using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Renci.SshNet.Tests.Classes.Common @@ -71,7 +72,7 @@ public void Signal_CurrentCountZero() try { - countdownEvent.Signal(); + _ = countdownEvent.Signal(); Assert.Fail(); } catch (InvalidOperationException) @@ -95,7 +96,9 @@ public void Wait_TimeoutInfinite_ShouldBlockUntilCountdownEventIsSet() var expectedSignalCount = _random.Next(5, 20); for (var i = 0; i < (expectedSignalCount - 1); i++) + { countdownEvent.AddCount(); + } var threads = new Thread[expectedSignalCount]; for (var i = 0; i < expectedSignalCount; i++) @@ -103,8 +106,8 @@ public void Wait_TimeoutInfinite_ShouldBlockUntilCountdownEventIsSet() threads[i] = new Thread(() => { Thread.Sleep(sleep); - Interlocked.Increment(ref signalCount); - countdownEvent.Signal(); + _ = Interlocked.Increment(ref signalCount); + _ = countdownEvent.Signal(); }); threads[i].Start(); } @@ -135,17 +138,19 @@ public void Wait_ShouldReturnTrueWhenCountdownEventIsSetBeforeTimeoutExpires() var expectedSignalCount = _random.Next(5, 20); for (var i = 0; i < (expectedSignalCount - 1); i++) + { countdownEvent.AddCount(); + } var threads = new Thread[expectedSignalCount]; for (var i = 0; i < expectedSignalCount; i++) { threads[i] = new Thread(() => - { - Thread.Sleep(sleep); - Interlocked.Increment(ref signalCount); - countdownEvent.Signal(); - }); + { + Thread.Sleep(sleep); + _ = Interlocked.Increment(ref signalCount); + _ = countdownEvent.Signal(); + }); threads[i].Start(); } @@ -175,17 +180,19 @@ public void Wait_ShouldReturnFalseWhenTimeoutExpiresBeforeCountdownEventIsSet() var expectedSignalCount = _random.Next(5, 20); for (var i = 0; i < (expectedSignalCount - 1); i++) + { countdownEvent.AddCount(); + } var threads = new Thread[expectedSignalCount]; for (var i = 0; i < expectedSignalCount; i++) { threads[i] = new Thread(() => - { - Thread.Sleep(sleep); - countdownEvent.Signal(); - Interlocked.Increment(ref signalCount); - }); + { + Thread.Sleep(sleep); + _ = countdownEvent.Signal(); + _ = Interlocked.Increment(ref signalCount); + }); threads[i].Start(); } @@ -198,7 +205,7 @@ public void Wait_ShouldReturnFalseWhenTimeoutExpiresBeforeCountdownEventIsSet() Assert.IsFalse(countdownEvent.IsSet); Assert.IsFalse(countdownEvent.WaitHandle.WaitOne(0)); - countdownEvent.Wait(Session.InfiniteTimeSpan); + _ = countdownEvent.Wait(Session.InfiniteTimeSpan); countdownEvent.Dispose(); } @@ -225,17 +232,19 @@ public void WaitHandle_WaitOne_TimeoutInfinite_ShouldBlockUntilCountdownEventIsS var expectedSignalCount = _random.Next(5, 20); for (var i = 0; i < (expectedSignalCount - 1); i++) + { countdownEvent.AddCount(); + } var threads = new Thread[expectedSignalCount]; for (var i = 0; i < expectedSignalCount; i++) { threads[i] = new Thread(() => - { - Thread.Sleep(sleep); - Interlocked.Increment(ref signalCount); - countdownEvent.Signal(); - }); + { + Thread.Sleep(sleep); + _ = Interlocked.Increment(ref signalCount); + _ = countdownEvent.Signal(); + }); threads[i].Start(); } @@ -265,17 +274,19 @@ public void WaitHandle_WaitOne_ShouldReturnTrueWhenCountdownEventIsSetBeforeTime var expectedSignalCount = _random.Next(5, 20); for (var i = 0; i < (expectedSignalCount - 1); i++) + { countdownEvent.AddCount(); + } var threads = new Thread[expectedSignalCount]; for (var i = 0; i < expectedSignalCount; i++) { threads[i] = new Thread(() => - { - Thread.Sleep(sleep); - Interlocked.Increment(ref signalCount); - countdownEvent.Signal(); - }); + { + Thread.Sleep(sleep); + _ = Interlocked.Increment(ref signalCount); + _ = countdownEvent.Signal(); + }); threads[i].Start(); } @@ -305,17 +316,19 @@ public void WaitHandle_WaitOne_ShouldReturnFalseWhenTimeoutExpiresBeforeCountdow var expectedSignalCount = _random.Next(5, 20); for (var i = 0; i < (expectedSignalCount - 1); i++) + { countdownEvent.AddCount(); + } var threads = new Thread[expectedSignalCount]; for (var i = 0; i < expectedSignalCount; i++) { threads[i] = new Thread(() => - { - Thread.Sleep(sleep); - countdownEvent.Signal(); - Interlocked.Increment(ref signalCount); - }); + { + Thread.Sleep(sleep); + _ = countdownEvent.Signal(); + _ = Interlocked.Increment(ref signalCount); + }); threads[i].Start(); } @@ -328,7 +341,7 @@ public void WaitHandle_WaitOne_ShouldReturnFalseWhenTimeoutExpiresBeforeCountdow Assert.IsFalse(countdownEvent.IsSet); Assert.IsFalse(countdownEvent.WaitHandle.WaitOne(0)); - countdownEvent.Wait(Session.InfiniteTimeSpan); + _ = countdownEvent.Wait(Session.InfiniteTimeSpan); countdownEvent.Dispose(); } diff --git a/src/Renci.SshNet.Tests/Classes/Common/ExtensionsTest_IsEqualTo_ByteArray.cs b/src/Renci.SshNet.Tests/Classes/Common/ExtensionsTest_IsEqualTo_ByteArray.cs index 42fe8fd54..c59fd5843 100644 --- a/src/Renci.SshNet.Tests/Classes/Common/ExtensionsTest_IsEqualTo_ByteArray.cs +++ b/src/Renci.SshNet.Tests/Classes/Common/ExtensionsTest_IsEqualTo_ByteArray.cs @@ -26,7 +26,7 @@ public void ShouldThrowArgumentNullExceptionWhenLeftIsNull() try { - Extensions.IsEqualTo(left, right); + _ = Extensions.IsEqualTo(left, right); Assert.Fail(); } catch (ArgumentNullException ex) @@ -44,7 +44,7 @@ public void ShouldThrowArgumentNullExceptionWhenRightIsNull() try { - Extensions.IsEqualTo(left, right); + _ = Extensions.IsEqualTo(left, right); Assert.Fail(); } catch (ArgumentNullException ex) @@ -62,7 +62,7 @@ public void ShouldThrowArgumentNullExceptionWhenLeftAndRightAreNull() try { - Extensions.IsEqualTo(left, right); + _ = Extensions.IsEqualTo(left, right); Assert.Fail(); } catch (ArgumentNullException ex) @@ -157,7 +157,7 @@ private static void Performance(byte[] left, byte[] right, int runs) for (var i = 0; i < runs; i++) { - Extensions.IsEqualTo(left, right); + _ = Extensions.IsEqualTo(left, right); } GC.Collect(); diff --git a/src/Renci.SshNet.Tests/Classes/Common/ExtensionsTest_Pad.cs b/src/Renci.SshNet.Tests/Classes/Common/ExtensionsTest_Pad.cs index f39c45ded..ba41dfb39 100644 --- a/src/Renci.SshNet.Tests/Classes/Common/ExtensionsTest_Pad.cs +++ b/src/Renci.SshNet.Tests/Classes/Common/ExtensionsTest_Pad.cs @@ -1,6 +1,7 @@ -using System; -using System.Diagnostics.CodeAnalysis; +using System.Diagnostics.CodeAnalysis; + using Microsoft.VisualStudio.TestTools.UnitTesting; + using Renci.SshNet.Common; namespace Renci.SshNet.Tests.Classes.Common @@ -13,7 +14,7 @@ public class ExtensionsTest_Pad public void ShouldReturnNotPadded() { byte[] value = {0x0a, 0x0d}; - byte[] padded = value.Pad(2); + var padded = value.Pad(2); Assert.AreEqual(value, padded); Assert.AreEqual(value.Length, padded.Length); } @@ -22,7 +23,7 @@ public void ShouldReturnNotPadded() public void ShouldReturnPadded() { byte[] value = { 0x0a, 0x0d }; - byte[] padded = value.Pad(3); + var padded = value.Pad(3); Assert.AreEqual(value.Length + 1, padded.Length); Assert.AreEqual(0x00, padded[0]); Assert.AreEqual(0x0a, padded[1]); diff --git a/src/Renci.SshNet.Tests/Classes/Common/ExtensionsTest_ToBigInteger2.cs b/src/Renci.SshNet.Tests/Classes/Common/ExtensionsTest_ToBigInteger2.cs index 1299f17ad..f9299165e 100644 --- a/src/Renci.SshNet.Tests/Classes/Common/ExtensionsTest_ToBigInteger2.cs +++ b/src/Renci.SshNet.Tests/Classes/Common/ExtensionsTest_ToBigInteger2.cs @@ -1,12 +1,10 @@ -using System; -using System.Diagnostics.CodeAnalysis; -using Microsoft.VisualStudio.TestTools.UnitTesting; +using Microsoft.VisualStudio.TestTools.UnitTesting; + using Renci.SshNet.Common; namespace Renci.SshNet.Tests.Classes.Common { [TestClass] - [SuppressMessage("ReSharper", "InvokeAsExtensionMethod")] public class ExtensionsTest_ToBigInteger2 { [TestMethod] diff --git a/src/Renci.SshNet.Tests/Classes/Common/PacketDumpTest.cs b/src/Renci.SshNet.Tests/Classes/Common/PacketDumpTest.cs index 845f433ba..13c649bde 100644 --- a/src/Renci.SshNet.Tests/Classes/Common/PacketDumpTest.cs +++ b/src/Renci.SshNet.Tests/Classes/Common/PacketDumpTest.cs @@ -15,7 +15,7 @@ public void Create_ByteArrayAndIndentLevel_DataIsNull() try { - PacketDump.Create(data, 0); + _ = PacketDump.Create(data, 0); Assert.Fail(); } catch (ArgumentNullException ex) @@ -32,7 +32,7 @@ public void Create_ByteArrayAndIndentLevel_IndentLevelLessThanZero() try { - PacketDump.Create(data, -1); + _ =PacketDump.Create(data, -1); Assert.Fail(); } catch (ArgumentOutOfRangeException ex) diff --git a/src/Renci.SshNet.Tests/Classes/Common/PipeStreamTest.cs b/src/Renci.SshNet.Tests/Classes/Common/PipeStreamTest.cs index 4c11b432a..6d56807fd 100644 --- a/src/Renci.SshNet.Tests/Classes/Common/PipeStreamTest.cs +++ b/src/Renci.SshNet.Tests/Classes/Common/PipeStreamTest.cs @@ -1,7 +1,9 @@ using System; using System.IO; using System.Threading; + using Microsoft.VisualStudio.TestTools.UnitTesting; + using Renci.SshNet.Common; using Renci.SshNet.Tests.Common; @@ -25,7 +27,7 @@ public void Test_PipeStream_Write_Read_Buffer() Assert.AreEqual(stream.Length, testBuffer.Length); - stream.Read(outputBuffer, 0, outputBuffer.Length); + _ = stream.Read(outputBuffer, 0, outputBuffer.Length); Assert.AreEqual(stream.Length, 0); @@ -44,9 +46,9 @@ public void Test_PipeStream_Write_Read_Byte() { stream.Write(testBuffer, 0, testBuffer.Length); Assert.AreEqual(stream.Length, testBuffer.Length); - stream.ReadByte(); + _ = stream.ReadByte(); Assert.AreEqual(stream.Length, testBuffer.Length - 1); - stream.ReadByte(); + _ = stream.ReadByte(); Assert.AreEqual(stream.Length, testBuffer.Length - 2); } } @@ -92,7 +94,7 @@ public void SeekShouldThrowNotSupportedException() try { - target.Seek(offset, origin); + _ = target.Seek(offset, origin); Assert.Fail(); } catch (NotSupportedException) @@ -169,9 +171,9 @@ public void LengthTest() Assert.AreEqual(2L, target.Length); target.WriteByte(0x0a); Assert.AreEqual(3L, target.Length); - target.Read(new byte[2], 0, 2); + _ = target.Read(new byte[2], 0, 2); Assert.AreEqual(1L, target.Length); - target.ReadByte(); + _ = target.ReadByte(); Assert.AreEqual(0L, target.Length); } @@ -195,7 +197,7 @@ public void Position_GetterAlwaysReturnsZero() Assert.AreEqual(0, target.Position); target.WriteByte(0x0a); Assert.AreEqual(0, target.Position); - target.ReadByte(); + _ = target.ReadByte(); Assert.AreEqual(0, target.Position); } @@ -214,4 +216,4 @@ public void Position_SetterAlwaysThrowsNotSupportedException() } } } -} \ No newline at end of file +} diff --git a/src/Renci.SshNet.Tests/Classes/Common/PipeStream_Close_BlockingRead.cs b/src/Renci.SshNet.Tests/Classes/Common/PipeStream_Close_BlockingRead.cs index fb010c14f..ed25b260a 100644 --- a/src/Renci.SshNet.Tests/Classes/Common/PipeStream_Close_BlockingRead.cs +++ b/src/Renci.SshNet.Tests/Classes/Common/PipeStream_Close_BlockingRead.cs @@ -34,7 +34,7 @@ protected override void Act() _pipeStream.Close(); // give async read time to complete - _readThread.Join(100); + _ = _readThread.Join(100); } [TestMethod] diff --git a/src/Renci.SshNet.Tests/Classes/Common/PipeStream_Close_BlockingWrite.cs b/src/Renci.SshNet.Tests/Classes/Common/PipeStream_Close_BlockingWrite.cs index 0b6210046..eb314d4d7 100644 --- a/src/Renci.SshNet.Tests/Classes/Common/PipeStream_Close_BlockingWrite.cs +++ b/src/Renci.SshNet.Tests/Classes/Common/PipeStream_Close_BlockingWrite.cs @@ -45,7 +45,7 @@ protected override void Act() _pipeStream.Close(); // give write time to complete - _writehread.Join(100); + _ = _writehread.Join(100); } [TestMethod] diff --git a/src/Renci.SshNet.Tests/Classes/Common/PipeStream_Flush_BytesRemainingAfterRead.cs b/src/Renci.SshNet.Tests/Classes/Common/PipeStream_Flush_BytesRemainingAfterRead.cs index 95047cac1..415466af2 100644 --- a/src/Renci.SshNet.Tests/Classes/Common/PipeStream_Flush_BytesRemainingAfterRead.cs +++ b/src/Renci.SshNet.Tests/Classes/Common/PipeStream_Flush_BytesRemainingAfterRead.cs @@ -30,7 +30,7 @@ protected override void Arrange() _readThread.Start(); // ensure we've started reading - _readThread.Join(50); + _ = _readThread.Join(50); } protected override void Act() @@ -38,7 +38,7 @@ protected override void Act() _pipeStream.Flush(); // give async read time to complete - _readThread.Join(100); + _ = _readThread.Join(100); } [TestMethod] diff --git a/src/Renci.SshNet.Tests/Classes/Common/PipeStream_Flush_NoBytesRemainingAfterRead.cs b/src/Renci.SshNet.Tests/Classes/Common/PipeStream_Flush_NoBytesRemainingAfterRead.cs index 44c7f3f71..f306edf1d 100644 --- a/src/Renci.SshNet.Tests/Classes/Common/PipeStream_Flush_NoBytesRemainingAfterRead.cs +++ b/src/Renci.SshNet.Tests/Classes/Common/PipeStream_Flush_NoBytesRemainingAfterRead.cs @@ -34,7 +34,7 @@ protected override void Act() _pipeStream.Flush(); // give async read time to complete - _readThread.Join(100); + _ = _readThread.Join(100); } [TestMethod] diff --git a/src/Renci.SshNet.Tests/Classes/Common/PortForwardEventArgsTest.cs b/src/Renci.SshNet.Tests/Classes/Common/PortForwardEventArgsTest.cs index d0b9860c1..c1f41dd70 100644 --- a/src/Renci.SshNet.Tests/Classes/Common/PortForwardEventArgsTest.cs +++ b/src/Renci.SshNet.Tests/Classes/Common/PortForwardEventArgsTest.cs @@ -18,7 +18,7 @@ public void ConstructorShouldThrowArgumentNullExceptionWhenHostIsNull() { try { - new PortForwardEventArgs(null, 80); + _ = new PortForwardEventArgs(null, 80); } catch (ArgumentNullException ex) { @@ -54,7 +54,7 @@ public void ConstructorShouldThrowArgumentOutOfRangeExceptionWhenPortIsGreaterTh try { - new PortForwardEventArgs(Resources.HOST, port); + _ = new PortForwardEventArgs(Resources.HOST, port); Assert.Fail(); } catch (ArgumentOutOfRangeException ex) @@ -64,4 +64,4 @@ public void ConstructorShouldThrowArgumentOutOfRangeExceptionWhenPortIsGreaterTh } } } -} \ No newline at end of file +} diff --git a/src/Renci.SshNet.Tests/Classes/Common/PosixPathTest_CreateAbsoluteOrRelativeFilePath.cs b/src/Renci.SshNet.Tests/Classes/Common/PosixPathTest_CreateAbsoluteOrRelativeFilePath.cs index 7378a30e3..519c95434 100644 --- a/src/Renci.SshNet.Tests/Classes/Common/PosixPathTest_CreateAbsoluteOrRelativeFilePath.cs +++ b/src/Renci.SshNet.Tests/Classes/Common/PosixPathTest_CreateAbsoluteOrRelativeFilePath.cs @@ -15,7 +15,7 @@ public void Path_Null() try { - PosixPath.CreateAbsoluteOrRelativeFilePath(path); + _ = PosixPath.CreateAbsoluteOrRelativeFilePath(path); Assert.Fail(); } catch (ArgumentNullException ex) @@ -32,7 +32,7 @@ public void Path_Empty() try { - PosixPath.CreateAbsoluteOrRelativeFilePath(path); + _ = PosixPath.CreateAbsoluteOrRelativeFilePath(path); Assert.Fail(); } catch (ArgumentException ex) diff --git a/src/Renci.SshNet.Tests/Classes/Common/PosixPathTest_GetDirectoryName.cs b/src/Renci.SshNet.Tests/Classes/Common/PosixPathTest_GetDirectoryName.cs index db1a38e70..0767c11e7 100644 --- a/src/Renci.SshNet.Tests/Classes/Common/PosixPathTest_GetDirectoryName.cs +++ b/src/Renci.SshNet.Tests/Classes/Common/PosixPathTest_GetDirectoryName.cs @@ -14,7 +14,7 @@ public void Path_Null() try { - PosixPath.GetDirectoryName(path); + _ = PosixPath.GetDirectoryName(path); Assert.Fail(); } catch (ArgumentNullException ex) diff --git a/src/Renci.SshNet.Tests/Classes/Common/PosixPathTest_GetFileName.cs b/src/Renci.SshNet.Tests/Classes/Common/PosixPathTest_GetFileName.cs index 3c7d74e2e..d81a13d2d 100644 --- a/src/Renci.SshNet.Tests/Classes/Common/PosixPathTest_GetFileName.cs +++ b/src/Renci.SshNet.Tests/Classes/Common/PosixPathTest_GetFileName.cs @@ -14,7 +14,7 @@ public void Path_Null() try { - PosixPath.GetFileName(path); + _ = PosixPath.GetFileName(path); Assert.Fail(); } catch (ArgumentNullException ex) diff --git a/src/Renci.SshNet.Tests/Classes/Common/SemaphoreLightTest.cs b/src/Renci.SshNet.Tests/Classes/Common/SemaphoreLightTest.cs index 93322c780..17d5e72f2 100644 --- a/src/Renci.SshNet.Tests/Classes/Common/SemaphoreLightTest.cs +++ b/src/Renci.SshNet.Tests/Classes/Common/SemaphoreLightTest.cs @@ -67,12 +67,11 @@ public void WaitTest() Assert.IsTrue(watch.ElapsedMilliseconds < 50); - var releaseThread = new Thread( - () => - { - Thread.Sleep(sleepTime); - target.Release(); - }); + var releaseThread = new Thread(() => + { + Thread.Sleep(sleepTime); + _ = target.Release(); + }); releaseThread.Start(); target.Wait(); diff --git a/src/Renci.SshNet.Tests/Classes/Common/SshConnectionExceptionTest.cs b/src/Renci.SshNet.Tests/Classes/Common/SshConnectionExceptionTest.cs index b960e4f41..2a305fcb9 100644 --- a/src/Renci.SshNet.Tests/Classes/Common/SshConnectionExceptionTest.cs +++ b/src/Renci.SshNet.Tests/Classes/Common/SshConnectionExceptionTest.cs @@ -1,6 +1,8 @@ using System; using System.Runtime.Serialization; + using Microsoft.VisualStudio.TestTools.UnitTesting; + using Renci.SshNet.Common; using Renci.SshNet.Messages.Transport; using Renci.SshNet.Tests.Common; @@ -20,7 +22,7 @@ public class SshConnectionExceptionTest : TestBase [TestMethod] public void SshConnectionExceptionConstructorTest() { - SshConnectionException target = new SshConnectionException(); + var target = new SshConnectionException(); Assert.Inconclusive("TODO: Implement code to verify target"); } @@ -30,8 +32,8 @@ public void SshConnectionExceptionConstructorTest() [TestMethod] public void SshConnectionExceptionConstructorTest1() { - string message = string.Empty; // TODO: Initialize to an appropriate value - SshConnectionException target = new SshConnectionException(message); + var message = string.Empty; // TODO: Initialize to an appropriate value + var target = new SshConnectionException(message); Assert.Inconclusive("TODO: Implement code to verify target"); } @@ -41,9 +43,9 @@ public void SshConnectionExceptionConstructorTest1() [TestMethod] public void SshConnectionExceptionConstructorTest2() { - string message = string.Empty; // TODO: Initialize to an appropriate value - DisconnectReason disconnectReasonCode = new DisconnectReason(); // TODO: Initialize to an appropriate value - SshConnectionException target = new SshConnectionException(message, disconnectReasonCode); + var message = string.Empty; // TODO: Initialize to an appropriate value + var disconnectReasonCode = new DisconnectReason(); // TODO: Initialize to an appropriate value + var target = new SshConnectionException(message, disconnectReasonCode); Assert.Inconclusive("TODO: Implement code to verify target"); } @@ -53,10 +55,10 @@ public void SshConnectionExceptionConstructorTest2() [TestMethod] public void SshConnectionExceptionConstructorTest3() { - string message = string.Empty; // TODO: Initialize to an appropriate value - DisconnectReason disconnectReasonCode = new DisconnectReason(); // TODO: Initialize to an appropriate value + var message = string.Empty; // TODO: Initialize to an appropriate value + var disconnectReasonCode = new DisconnectReason(); // TODO: Initialize to an appropriate value Exception inner = null; // TODO: Initialize to an appropriate value - SshConnectionException target = new SshConnectionException(message, disconnectReasonCode, inner); + var target = new SshConnectionException(message, disconnectReasonCode, inner); Assert.Inconclusive("TODO: Implement code to verify target"); } @@ -67,9 +69,9 @@ public void SshConnectionExceptionConstructorTest3() [Ignore] // placeholder for actual test public void GetObjectDataTest() { - SshConnectionException target = new SshConnectionException(); // TODO: Initialize to an appropriate value + var target = new SshConnectionException(); // TODO: Initialize to an appropriate value SerializationInfo info = null; // TODO: Initialize to an appropriate value - StreamingContext context = new StreamingContext(); // TODO: Initialize to an appropriate value + var context = new StreamingContext(); // TODO: Initialize to an appropriate value target.GetObjectData(info, context); Assert.Inconclusive("A method that does not return a value cannot be verified."); } diff --git a/src/Renci.SshNet.Tests/Classes/Compression/ZlibOpenSshTest.cs b/src/Renci.SshNet.Tests/Classes/Compression/ZlibOpenSshTest.cs index c11e13dcb..b3e166501 100644 --- a/src/Renci.SshNet.Tests/Classes/Compression/ZlibOpenSshTest.cs +++ b/src/Renci.SshNet.Tests/Classes/Compression/ZlibOpenSshTest.cs @@ -1,7 +1,6 @@ -using Renci.SshNet.Compression; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using System; -using Renci.SshNet; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +using Renci.SshNet.Compression; using Renci.SshNet.Tests.Common; namespace Renci.SshNet.Tests.Classes.Compression @@ -20,7 +19,7 @@ public class ZlibOpenSshTest : TestBase [TestMethod()] public void ZlibOpenSshConstructorTest() { - ZlibOpenSsh target = new ZlibOpenSsh(); + var target = new ZlibOpenSsh(); Assert.Inconclusive("TODO: Implement code to verify target"); } @@ -30,7 +29,7 @@ public void ZlibOpenSshConstructorTest() [TestMethod()] public void InitTest() { - ZlibOpenSsh target = new ZlibOpenSsh(); // TODO: Initialize to an appropriate value + var target = new ZlibOpenSsh(); // TODO: Initialize to an appropriate value Session session = null; // TODO: Initialize to an appropriate value target.Init(session); Assert.Inconclusive("A method that does not return a value cannot be verified."); @@ -42,9 +41,8 @@ public void InitTest() [TestMethod()] public void NameTest() { - ZlibOpenSsh target = new ZlibOpenSsh(); // TODO: Initialize to an appropriate value - string actual; - actual = target.Name; + var target = new ZlibOpenSsh(); // TODO: Initialize to an appropriate value + var actual = target.Name; Assert.Inconclusive("Verify the correctness of this test method."); } } diff --git a/src/Renci.SshNet.Tests/Classes/Compression/ZlibStreamTest.cs b/src/Renci.SshNet.Tests/Classes/Compression/ZlibStreamTest.cs index dd1c93bf2..6ee6236c2 100644 --- a/src/Renci.SshNet.Tests/Classes/Compression/ZlibStreamTest.cs +++ b/src/Renci.SshNet.Tests/Classes/Compression/ZlibStreamTest.cs @@ -1,11 +1,12 @@ -using Renci.SshNet.Compression; +using System.IO; + using Microsoft.VisualStudio.TestTools.UnitTesting; -using System; -using System.IO; + +using Renci.SshNet.Compression; using Renci.SshNet.Tests.Common; namespace Renci.SshNet.Tests.Classes.Compression -{ +{ /// ///This is a test class for ZlibStreamTest and is intended ///to contain all ZlibStreamTest Unit Tests @@ -21,8 +22,8 @@ public class ZlibStreamTest : TestBase public void ZlibStreamConstructorTest() { Stream stream = null; // TODO: Initialize to an appropriate value - CompressionMode mode = new CompressionMode(); // TODO: Initialize to an appropriate value - ZlibStream target = new ZlibStream(stream, mode); + var mode = new CompressionMode(); // TODO: Initialize to an appropriate value + var target = new ZlibStream(stream, mode); Assert.Inconclusive("TODO: Implement code to verify target"); } @@ -34,11 +35,11 @@ public void ZlibStreamConstructorTest() public void WriteTest() { Stream stream = null; // TODO: Initialize to an appropriate value - CompressionMode mode = new CompressionMode(); // TODO: Initialize to an appropriate value - ZlibStream target = new ZlibStream(stream, mode); // TODO: Initialize to an appropriate value + var mode = new CompressionMode(); // TODO: Initialize to an appropriate value + var target = new ZlibStream(stream, mode); // TODO: Initialize to an appropriate value byte[] buffer = null; // TODO: Initialize to an appropriate value - int offset = 0; // TODO: Initialize to an appropriate value - int count = 0; // TODO: Initialize to an appropriate value + var offset = 0; // TODO: Initialize to an appropriate value + var count = 0; // TODO: Initialize to an appropriate value target.Write(buffer, offset, count); Assert.Inconclusive("A method that does not return a value cannot be verified."); } diff --git a/src/Renci.SshNet.Tests/Classes/Connection/DirectConnectorTestBase.cs b/src/Renci.SshNet.Tests/Classes/Connection/DirectConnectorTestBase.cs index edb146808..d1989c3de 100644 --- a/src/Renci.SshNet.Tests/Classes/Connection/DirectConnectorTestBase.cs +++ b/src/Renci.SshNet.Tests/Classes/Connection/DirectConnectorTestBase.cs @@ -1,7 +1,7 @@ using Moq; + using Renci.SshNet.Connection; using Renci.SshNet.Tests.Common; -using System.Net; namespace Renci.SshNet.Tests.Classes.Connection { diff --git a/src/Renci.SshNet.Tests/Classes/Connection/DirectConnectorTest_Connect_ConnectionRefusedByServer.cs b/src/Renci.SshNet.Tests/Classes/Connection/DirectConnectorTest_Connect_ConnectionRefusedByServer.cs index 0583729a5..2a0976197 100644 --- a/src/Renci.SshNet.Tests/Classes/Connection/DirectConnectorTest_Connect_ConnectionRefusedByServer.cs +++ b/src/Renci.SshNet.Tests/Classes/Connection/DirectConnectorTest_Connect_ConnectionRefusedByServer.cs @@ -1,11 +1,12 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; -using Renci.SshNet.Common; -using System; +using System; using System.Diagnostics; using System.Net; using System.Net.Sockets; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +using Moq; + namespace Renci.SshNet.Tests.Classes.Connection { [TestClass] @@ -30,18 +31,15 @@ protected override void SetupData() protected override void SetupMocks() { - SocketFactoryMock.Setup(p => p.Create(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) - .Returns(_clientSocket); + _ = SocketFactoryMock.Setup(p => p.Create(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) + .Returns(_clientSocket); } protected override void TearDown() { base.TearDown(); - if (_clientSocket != null) - { - _clientSocket.Dispose(); - } + _clientSocket?.Dispose(); } protected override void Act() @@ -50,7 +48,7 @@ protected override void Act() try { - Connector.Connect(_connectionInfo); + _ = Connector.Connect(_connectionInfo); Assert.Fail(); } catch (SocketException ex) @@ -86,7 +84,7 @@ public void ClientSocketShouldHaveBeenDisposed() { try { - _clientSocket.Receive(new byte[0]); + _ = _clientSocket.Receive(new byte[0]); Assert.Fail(); } catch (ObjectDisposedException) diff --git a/src/Renci.SshNet.Tests/Classes/Connection/DirectConnectorTest_Connect_ConnectionSucceeded.cs b/src/Renci.SshNet.Tests/Classes/Connection/DirectConnectorTest_Connect_ConnectionSucceeded.cs index d2abc7749..433adff45 100644 --- a/src/Renci.SshNet.Tests/Classes/Connection/DirectConnectorTest_Connect_ConnectionSucceeded.cs +++ b/src/Renci.SshNet.Tests/Classes/Connection/DirectConnectorTest_Connect_ConnectionSucceeded.cs @@ -1,12 +1,13 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; -using Renci.SshNet.Common; -using Renci.SshNet.Tests.Common; -using System; +using System; using System.Diagnostics; using System.Net; using System.Net.Sockets; -using System.Threading; + +using Microsoft.VisualStudio.TestTools.UnitTesting; + +using Moq; + +using Renci.SshNet.Tests.Common; namespace Renci.SshNet.Tests.Classes.Connection { @@ -41,23 +42,16 @@ protected override void SetupData() protected override void SetupMocks() { - SocketFactoryMock.Setup(p => p.Create(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) - .Returns(_clientSocket); + _ = SocketFactoryMock.Setup(p => p.Create(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) + .Returns(_clientSocket); } protected override void TearDown() { base.TearDown(); - if (_server != null) - { - _server.Dispose(); - } - - if (_clientSocket != null) - { - _clientSocket.Dispose(); - } + _server?.Dispose(); + _clientSocket?.Dispose(); } protected override void Act() diff --git a/src/Renci.SshNet.Tests/Classes/Connection/DirectConnectorTest_Connect_HostNameInvalid.cs b/src/Renci.SshNet.Tests/Classes/Connection/DirectConnectorTest_Connect_HostNameInvalid.cs index 05a69e94b..068169248 100644 --- a/src/Renci.SshNet.Tests/Classes/Connection/DirectConnectorTest_Connect_HostNameInvalid.cs +++ b/src/Renci.SshNet.Tests/Classes/Connection/DirectConnectorTest_Connect_HostNameInvalid.cs @@ -1,6 +1,6 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; -using System.Net.Sockets; +using System.Net.Sockets; + +using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Renci.SshNet.Tests.Classes.Connection { @@ -22,7 +22,7 @@ protected override void Act() { try { - Connector.Connect(_connectionInfo); + _ = Connector.Connect(_connectionInfo); Assert.Fail(); } catch (SocketException ex) diff --git a/src/Renci.SshNet.Tests/Classes/Connection/DirectConnectorTest_Connect_TimeoutConnectingToServer.cs b/src/Renci.SshNet.Tests/Classes/Connection/DirectConnectorTest_Connect_TimeoutConnectingToServer.cs index 44cfe62c6..661b286ae 100644 --- a/src/Renci.SshNet.Tests/Classes/Connection/DirectConnectorTest_Connect_TimeoutConnectingToServer.cs +++ b/src/Renci.SshNet.Tests/Classes/Connection/DirectConnectorTest_Connect_TimeoutConnectingToServer.cs @@ -1,13 +1,15 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; -using Renci.SshNet.Common; -using Renci.SshNet.Tests.Common; -using System; +using System; using System.Diagnostics; using System.Globalization; using System.Net; using System.Net.Sockets; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +using Moq; + +using Renci.SshNet.Common; + namespace Renci.SshNet.Tests.Classes.Connection { [TestClass] @@ -34,18 +36,15 @@ protected override void SetupData() protected override void SetupMocks() { - SocketFactoryMock.Setup(p => p.Create(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) - .Returns(_clientSocket); + _ = SocketFactoryMock.Setup(p => p.Create(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) + .Returns(_clientSocket); } protected override void TearDown() { base.TearDown(); - if (_clientSocket != null) - { - _clientSocket.Dispose(); - } + _clientSocket?.Dispose(); } protected override void Act() @@ -54,7 +53,7 @@ protected override void Act() try { - Connector.Connect(_connectionInfo); + _ = Connector.Connect(_connectionInfo); Assert.Fail(); } catch (SshOperationTimeoutException ex) @@ -91,7 +90,7 @@ public void ClientSocketShouldHaveBeenDisposed() { try { - _clientSocket.Receive(new byte[0]); + _ = _clientSocket.Receive(new byte[0]); Assert.Fail(); } catch (ObjectDisposedException) diff --git a/src/Renci.SshNet.Tests/Classes/Connection/HttpConnectorTest_Connect_ConnectionToProxyRefused.cs b/src/Renci.SshNet.Tests/Classes/Connection/HttpConnectorTest_Connect_ConnectionToProxyRefused.cs index e507b92b7..518303329 100644 --- a/src/Renci.SshNet.Tests/Classes/Connection/HttpConnectorTest_Connect_ConnectionToProxyRefused.cs +++ b/src/Renci.SshNet.Tests/Classes/Connection/HttpConnectorTest_Connect_ConnectionToProxyRefused.cs @@ -1,6 +1,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; + using Moq; -using Renci.SshNet.Common; + using System; using System.Diagnostics; using System.Net; @@ -28,8 +29,10 @@ protected override void SetupData() 8122, "proxyUser", "proxyPwd", - new KeyboardInteractiveAuthenticationMethod("user")); - _connectionInfo.Timeout = TimeSpan.FromMilliseconds(5000); + new KeyboardInteractiveAuthenticationMethod("user")) + { + Timeout = TimeSpan.FromMilliseconds(5000) + }; _stopWatch = new Stopwatch(); _actualException = null; @@ -38,18 +41,15 @@ protected override void SetupData() protected override void SetupMocks() { - SocketFactoryMock.Setup(p => p.Create(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) - .Returns(_clientSocket); + _ = SocketFactoryMock.Setup(p => p.Create(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) + .Returns(_clientSocket); } protected override void TearDown() { base.TearDown(); - if (_clientSocket != null) - { - _clientSocket.Dispose(); - } + _clientSocket?.Dispose(); } protected override void Act() @@ -58,7 +58,7 @@ protected override void Act() try { - Connector.Connect(_connectionInfo); + _ = Connector.Connect(_connectionInfo); Assert.Fail(); } catch (SocketException ex) @@ -94,7 +94,7 @@ public void ClientSocketShouldHaveBeenDisposed() { try { - _clientSocket.Receive(new byte[0]); + _ = _clientSocket.Receive(new byte[0]); Assert.Fail(); } catch (ObjectDisposedException) diff --git a/src/Renci.SshNet.Tests/Classes/Connection/HttpConnectorTest_Connect_ProxyClosesConnectionBeforeStatusLineIsSent.cs b/src/Renci.SshNet.Tests/Classes/Connection/HttpConnectorTest_Connect_ProxyClosesConnectionBeforeStatusLineIsSent.cs index cd577ec9c..ece0aa9e1 100644 --- a/src/Renci.SshNet.Tests/Classes/Connection/HttpConnectorTest_Connect_ProxyClosesConnectionBeforeStatusLineIsSent.cs +++ b/src/Renci.SshNet.Tests/Classes/Connection/HttpConnectorTest_Connect_ProxyClosesConnectionBeforeStatusLineIsSent.cs @@ -30,8 +30,10 @@ protected override void SetupData() 8122, "proxyUser", "proxyPwd", - new KeyboardInteractiveAuthenticationMethod("user")); - _connectionInfo.Timeout = TimeSpan.FromMilliseconds(100); + new KeyboardInteractiveAuthenticationMethod("user")) + { + Timeout = TimeSpan.FromMilliseconds(100) + }; _actualException = null; _clientSocket = SocketFactory.Create(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); @@ -47,30 +49,23 @@ protected override void SetupData() protected override void SetupMocks() { - SocketFactoryMock.Setup(p => p.Create(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) - .Returns(_clientSocket); + _ = SocketFactoryMock.Setup(p => p.Create(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) + .Returns(_clientSocket); } protected override void TearDown() { base.TearDown(); - if (_proxyServer != null) - { - _proxyServer.Dispose(); - } - - if (_clientSocket != null) - { - _clientSocket.Dispose(); - } + _proxyServer?.Dispose(); + _clientSocket?.Dispose(); } protected override void Act() { try { - Connector.Connect(_connectionInfo); + _ = Connector.Connect(_connectionInfo); Assert.Fail(); } catch (ProxyException ex) @@ -101,7 +96,7 @@ public void ClientSocketShouldHaveBeenDisposed() { try { - _clientSocket.Receive(new byte[0]); + _ = _clientSocket.Receive(new byte[0]); Assert.Fail(); } catch (ObjectDisposedException) diff --git a/src/Renci.SshNet.Tests/Classes/Connection/HttpConnectorTest_Connect_ProxyHostInvalid.cs b/src/Renci.SshNet.Tests/Classes/Connection/HttpConnectorTest_Connect_ProxyHostInvalid.cs index 5843947dc..59524ffd7 100644 --- a/src/Renci.SshNet.Tests/Classes/Connection/HttpConnectorTest_Connect_ProxyHostInvalid.cs +++ b/src/Renci.SshNet.Tests/Classes/Connection/HttpConnectorTest_Connect_ProxyHostInvalid.cs @@ -29,7 +29,7 @@ protected override void Act() { try { - Connector.Connect(_connectionInfo); + _ = Connector.Connect(_connectionInfo); Assert.Fail(); } catch (SocketException ex) diff --git a/src/Renci.SshNet.Tests/Classes/Connection/HttpConnectorTest_Connect_ProxyPasswordIsEmpty.cs b/src/Renci.SshNet.Tests/Classes/Connection/HttpConnectorTest_Connect_ProxyPasswordIsEmpty.cs index 59fb77aaa..9a7e876a5 100644 --- a/src/Renci.SshNet.Tests/Classes/Connection/HttpConnectorTest_Connect_ProxyPasswordIsEmpty.cs +++ b/src/Renci.SshNet.Tests/Classes/Connection/HttpConnectorTest_Connect_ProxyPasswordIsEmpty.cs @@ -1,7 +1,4 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; -using Renci.SshNet.Tests.Common; -using System; +using System; using System.Collections.Generic; using System.Globalization; using System.Net; @@ -9,6 +6,12 @@ using System.Text; using System.Threading; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +using Moq; + +using Renci.SshNet.Tests.Common; + namespace Renci.SshNet.Tests.Classes.Connection { [TestClass] @@ -34,8 +37,10 @@ protected override void SetupData() 8122, "proxyUser", string.Empty, - new KeyboardInteractiveAuthenticationMethod("user")); - _connectionInfo.Timeout = TimeSpan.FromMilliseconds(20); + new KeyboardInteractiveAuthenticationMethod("user")) + { + Timeout = TimeSpan.FromMilliseconds(20) + }; _expectedHttpRequest = string.Format("CONNECT {0}:{1} HTTP/1.0{2}" + "Proxy-Authorization: Basic cHJveHlVc2VyOg=={2}{2}", _connectionInfo.Host, @@ -49,13 +54,14 @@ protected override void SetupData() _proxyServer.Disconnected += (socket) => _disconnected = true; _proxyServer.Connected += socket => { - socket.Send(Encoding.ASCII.GetBytes("\r\n")); - socket.Send(Encoding.ASCII.GetBytes("SSH.NET\r\n")); - socket.Send(Encoding.ASCII.GetBytes("HTTP/1.0 200 OK\r\n")); - socket.Send(Encoding.ASCII.GetBytes("Content-Type: application/octet-stream\r\n")); - socket.Send(Encoding.ASCII.GetBytes("\r\n")); - socket.Send(Encoding.ASCII.GetBytes("SSH4EVER")); - socket.Shutdown(SocketShutdown.Send); + _ = socket.Send(Encoding.ASCII.GetBytes("\r\n")); + _ = socket.Send(Encoding.ASCII.GetBytes("SSH.NET\r\n")); + _ = socket.Send(Encoding.ASCII.GetBytes("HTTP/1.0 200 OK\r\n")); + _ = socket.Send(Encoding.ASCII.GetBytes("Content-Type: application/octet-stream\r\n")); + _ = socket.Send(Encoding.ASCII.GetBytes("\r\n")); + _ = socket.Send(Encoding.ASCII.GetBytes("SSH4EVER")); + + socket.Shutdown(SocketShutdown.Send); }; _proxyServer.BytesReceived += (bytesReceived, socket) => { @@ -66,18 +72,15 @@ protected override void SetupData() protected override void SetupMocks() { - SocketFactoryMock.Setup(p => p.Create(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) - .Returns(_clientSocket); + _ = SocketFactoryMock.Setup(p => p.Create(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) + .Returns(_clientSocket); } protected override void TearDown() { base.TearDown(); - if (_proxyServer != null) - { - _proxyServer.Dispose(); - } + _proxyServer?.Dispose(); if (_clientSocket != null) { diff --git a/src/Renci.SshNet.Tests/Classes/Connection/HttpConnectorTest_Connect_ProxyPasswordIsNull.cs b/src/Renci.SshNet.Tests/Classes/Connection/HttpConnectorTest_Connect_ProxyPasswordIsNull.cs index dd267ef5d..ccbf2b751 100644 --- a/src/Renci.SshNet.Tests/Classes/Connection/HttpConnectorTest_Connect_ProxyPasswordIsNull.cs +++ b/src/Renci.SshNet.Tests/Classes/Connection/HttpConnectorTest_Connect_ProxyPasswordIsNull.cs @@ -34,8 +34,10 @@ protected override void SetupData() 8122, "proxyUser", null, - new KeyboardInteractiveAuthenticationMethod("user")); - _connectionInfo.Timeout = TimeSpan.FromMilliseconds(20); + new KeyboardInteractiveAuthenticationMethod("user")) + { + Timeout = TimeSpan.FromMilliseconds(20) + }; _expectedHttpRequest = string.Format("CONNECT {0}:{1} HTTP/1.0{2}" + "Proxy-Authorization: Basic cHJveHlVc2VyOg=={2}{2}", _connectionInfo.Host, @@ -49,12 +51,13 @@ protected override void SetupData() _proxyServer.Disconnected += (socket) => _disconnected = true; _proxyServer.Connected += socket => { - socket.Send(Encoding.ASCII.GetBytes("\r\n")); - socket.Send(Encoding.ASCII.GetBytes("SSH.NET\r\n")); - socket.Send(Encoding.ASCII.GetBytes("HTTP/1.0 200 OK\r\n")); - socket.Send(Encoding.ASCII.GetBytes("Content-Type: application/octet-stream\r\n")); - socket.Send(Encoding.ASCII.GetBytes("\r\n")); - socket.Send(Encoding.ASCII.GetBytes("SSH4EVER")); + _ = socket.Send(Encoding.ASCII.GetBytes("\r\n")); + _ = socket.Send(Encoding.ASCII.GetBytes("SSH.NET\r\n")); + _ = socket.Send(Encoding.ASCII.GetBytes("HTTP/1.0 200 OK\r\n")); + _ = socket.Send(Encoding.ASCII.GetBytes("Content-Type: application/octet-stream\r\n")); + _ = socket.Send(Encoding.ASCII.GetBytes("\r\n")); + _ = socket.Send(Encoding.ASCII.GetBytes("SSH4EVER")); + socket.Shutdown(SocketShutdown.Send); }; _proxyServer.BytesReceived += (bytesReceived, socket) => @@ -66,18 +69,15 @@ protected override void SetupData() protected override void SetupMocks() { - SocketFactoryMock.Setup(p => p.Create(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) - .Returns(_clientSocket); + _ = SocketFactoryMock.Setup(p => p.Create(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) + .Returns(_clientSocket); } protected override void TearDown() { base.TearDown(); - if (_proxyServer != null) - { - _proxyServer.Dispose(); - } + _proxyServer?.Dispose(); if (_clientSocket != null) { diff --git a/src/Renci.SshNet.Tests/Classes/Connection/HttpConnectorTest_Connect_ProxyResponseDoesNotContainHttpStatusLine.cs b/src/Renci.SshNet.Tests/Classes/Connection/HttpConnectorTest_Connect_ProxyResponseDoesNotContainHttpStatusLine.cs index 77f9091ad..eebb70faf 100644 --- a/src/Renci.SshNet.Tests/Classes/Connection/HttpConnectorTest_Connect_ProxyResponseDoesNotContainHttpStatusLine.cs +++ b/src/Renci.SshNet.Tests/Classes/Connection/HttpConnectorTest_Connect_ProxyResponseDoesNotContainHttpStatusLine.cs @@ -1,14 +1,17 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; -using Renci.SshNet.Common; -using Renci.SshNet.Tests.Common; -using System; +using System; using System.Collections.Generic; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +using Moq; + +using Renci.SshNet.Common; +using Renci.SshNet.Tests.Common; + namespace Renci.SshNet.Tests.Classes.Connection { [TestClass] @@ -33,8 +36,10 @@ protected override void SetupData() 8122, "proxyUser", "proxyPwd", - new KeyboardInteractiveAuthenticationMethod("user")); - _connectionInfo.Timeout = TimeSpan.FromMilliseconds(100); + new KeyboardInteractiveAuthenticationMethod("user")) + { + Timeout = TimeSpan.FromMilliseconds(100) + }; _bytesReceivedByProxy = new List(); _actualException = null; @@ -46,7 +51,8 @@ protected override void SetupData() { if (_bytesReceivedByProxy.Count == 0) { - socket.Send(Encoding.ASCII.GetBytes("Whatever\r\n")); + _ = socket.Send(Encoding.ASCII.GetBytes("Whatever\r\n")); + socket.Shutdown(SocketShutdown.Send); } @@ -57,25 +63,22 @@ protected override void SetupData() protected override void SetupMocks() { - SocketFactoryMock.Setup(p => p.Create(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) - .Returns(_clientSocket); + _ = SocketFactoryMock.Setup(p => p.Create(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) + .Returns(_clientSocket); } protected override void TearDown() { base.TearDown(); - if (_proxyServer != null) - { - _proxyServer.Dispose(); - } + _proxyServer?.Dispose(); } protected override void Act() { try { - Connector.Connect(_connectionInfo); + _ = Connector.Connect(_connectionInfo); Assert.Fail(); } catch (ProxyException ex) @@ -106,7 +109,7 @@ public void ClientSocketShouldHaveBeenDisposed() { try { - _clientSocket.Receive(new byte[0]); + _ = _clientSocket.Receive(new byte[0]); Assert.Fail(); } catch (ObjectDisposedException) diff --git a/src/Renci.SshNet.Tests/Classes/Connection/HttpConnectorTest_Connect_ProxyResponseStatusIs200_ExtraTextBeforeStatusLine.cs b/src/Renci.SshNet.Tests/Classes/Connection/HttpConnectorTest_Connect_ProxyResponseStatusIs200_ExtraTextBeforeStatusLine.cs index da56fa458..f2287807a 100644 --- a/src/Renci.SshNet.Tests/Classes/Connection/HttpConnectorTest_Connect_ProxyResponseStatusIs200_ExtraTextBeforeStatusLine.cs +++ b/src/Renci.SshNet.Tests/Classes/Connection/HttpConnectorTest_Connect_ProxyResponseStatusIs200_ExtraTextBeforeStatusLine.cs @@ -1,7 +1,4 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; -using Renci.SshNet.Tests.Common; -using System; +using System; using System.Collections.Generic; using System.Globalization; using System.Net; @@ -9,6 +6,12 @@ using System.Text; using System.Threading; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +using Moq; + +using Renci.SshNet.Tests.Common; + namespace Renci.SshNet.Tests.Classes.Connection { [TestClass] @@ -34,8 +37,10 @@ protected override void SetupData() 8122, "proxyUser", "proxyPwd", - new KeyboardInteractiveAuthenticationMethod("user")); - _connectionInfo.Timeout = TimeSpan.FromMilliseconds(20); + new KeyboardInteractiveAuthenticationMethod("user")) + { + Timeout = TimeSpan.FromMilliseconds(20) + }; _expectedHttpRequest = string.Format("CONNECT {0}:{1} HTTP/1.0{2}" + "Proxy-Authorization: Basic cHJveHlVc2VyOnByb3h5UHdk{2}{2}", _connectionInfo.Host, @@ -56,12 +61,13 @@ protected override void SetupData() // it sends the CONNECT request if (_bytesReceivedByProxy.Count == _expectedHttpRequest.Length) { - socket.Send(Encoding.ASCII.GetBytes("\r\n")); - socket.Send(Encoding.ASCII.GetBytes("SSH.NET\r\n")); - socket.Send(Encoding.ASCII.GetBytes("HTTP/1.0 200 OK\r\n")); - socket.Send(Encoding.ASCII.GetBytes("Content-Type: application/octet-stream\r\n")); - socket.Send(Encoding.ASCII.GetBytes("\r\n")); - socket.Send(Encoding.ASCII.GetBytes("SSH4EVER")); + _ = socket.Send(Encoding.ASCII.GetBytes("\r\n")); + _ = socket.Send(Encoding.ASCII.GetBytes("SSH.NET\r\n")); + _ = socket.Send(Encoding.ASCII.GetBytes("HTTP/1.0 200 OK\r\n")); + _ = socket.Send(Encoding.ASCII.GetBytes("Content-Type: application/octet-stream\r\n")); + _ = socket.Send(Encoding.ASCII.GetBytes("\r\n")); + _ = socket.Send(Encoding.ASCII.GetBytes("SSH4EVER")); + socket.Shutdown(SocketShutdown.Send); } }; @@ -70,18 +76,15 @@ protected override void SetupData() protected override void SetupMocks() { - SocketFactoryMock.Setup(p => p.Create(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) - .Returns(_clientSocket); + _ = SocketFactoryMock.Setup(p => p.Create(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) + .Returns(_clientSocket); } protected override void TearDown() { base.TearDown(); - if (_proxyServer != null) - { - _proxyServer.Dispose(); - } + _proxyServer?.Dispose(); if (_clientSocket != null) { diff --git a/src/Renci.SshNet.Tests/Classes/Connection/HttpConnectorTest_Connect_ProxyResponseStatusIs200_HeadersAndContent.cs b/src/Renci.SshNet.Tests/Classes/Connection/HttpConnectorTest_Connect_ProxyResponseStatusIs200_HeadersAndContent.cs index e89547b66..765e7f81a 100644 --- a/src/Renci.SshNet.Tests/Classes/Connection/HttpConnectorTest_Connect_ProxyResponseStatusIs200_HeadersAndContent.cs +++ b/src/Renci.SshNet.Tests/Classes/Connection/HttpConnectorTest_Connect_ProxyResponseStatusIs200_HeadersAndContent.cs @@ -1,7 +1,4 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; -using Renci.SshNet.Tests.Common; -using System; +using System; using System.Collections.Generic; using System.Globalization; using System.Net; @@ -9,6 +6,12 @@ using System.Text; using System.Threading; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +using Moq; + +using Renci.SshNet.Tests.Common; + namespace Renci.SshNet.Tests.Classes.Connection { [TestClass] @@ -34,8 +37,10 @@ protected override void SetupData() 8122, "proxyUser", "proxyPwd", - new KeyboardInteractiveAuthenticationMethod("user")); - _connectionInfo.Timeout = TimeSpan.FromMilliseconds(20); + new KeyboardInteractiveAuthenticationMethod("user")) + { + Timeout = TimeSpan.FromMilliseconds(20) + }; _expectedHttpRequest = string.Format("CONNECT {0}:{1} HTTP/1.0{2}" + "Proxy-Authorization: Basic cHJveHlVc2VyOnByb3h5UHdk{2}{2}", _connectionInfo.Host, @@ -56,12 +61,13 @@ protected override void SetupData() // it sends the CONNECT request if (_bytesReceivedByProxy.Count == _expectedHttpRequest.Length) { - socket.Send(Encoding.ASCII.GetBytes("HTTP/1.0 200 OK\r\n")); - socket.Send(Encoding.ASCII.GetBytes("Content-Length: 10\r\n")); - socket.Send(Encoding.ASCII.GetBytes("Content-Type: application/octet-stream\r\n")); - socket.Send(Encoding.ASCII.GetBytes("\r\n")); - socket.Send(Encoding.ASCII.GetBytes("TEEN_BYTES")); - socket.Send(Encoding.ASCII.GetBytes("!666!")); + _ = socket.Send(Encoding.ASCII.GetBytes("HTTP/1.0 200 OK\r\n")); + _ = socket.Send(Encoding.ASCII.GetBytes("Content-Length: 10\r\n")); + _ = socket.Send(Encoding.ASCII.GetBytes("Content-Type: application/octet-stream\r\n")); + _ = socket.Send(Encoding.ASCII.GetBytes("\r\n")); + _ = socket.Send(Encoding.ASCII.GetBytes("TEEN_BYTES")); + _ = socket.Send(Encoding.ASCII.GetBytes("!666!")); + socket.Shutdown(SocketShutdown.Send); } }; @@ -70,18 +76,15 @@ protected override void SetupData() protected override void SetupMocks() { - SocketFactoryMock.Setup(p => p.Create(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) - .Returns(_clientSocket); + _ = SocketFactoryMock.Setup(p => p.Create(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) + .Returns(_clientSocket); } protected override void TearDown() { base.TearDown(); - if (_proxyServer != null) - { - _proxyServer.Dispose(); - } + _proxyServer?.Dispose(); if (_clientSocket != null) { diff --git a/src/Renci.SshNet.Tests/Classes/Connection/HttpConnectorTest_Connect_ProxyResponseStatusIs200_OnlyHeaders.cs b/src/Renci.SshNet.Tests/Classes/Connection/HttpConnectorTest_Connect_ProxyResponseStatusIs200_OnlyHeaders.cs index 30cca421e..17da268c6 100644 --- a/src/Renci.SshNet.Tests/Classes/Connection/HttpConnectorTest_Connect_ProxyResponseStatusIs200_OnlyHeaders.cs +++ b/src/Renci.SshNet.Tests/Classes/Connection/HttpConnectorTest_Connect_ProxyResponseStatusIs200_OnlyHeaders.cs @@ -34,8 +34,10 @@ protected override void SetupData() 8122, "proxyUser", "proxyPwd", - new KeyboardInteractiveAuthenticationMethod("user")); - _connectionInfo.Timeout = TimeSpan.FromMilliseconds(20); + new KeyboardInteractiveAuthenticationMethod("user")) + { + Timeout = TimeSpan.FromMilliseconds(20) + }; _expectedHttpRequest = string.Format("CONNECT {0}:{1} HTTP/1.0{2}" + "Proxy-Authorization: Basic cHJveHlVc2VyOnByb3h5UHdk{2}{2}", _connectionInfo.Host, @@ -56,10 +58,11 @@ protected override void SetupData() // it sends the CONNECT request if (_bytesReceivedByProxy.Count == _expectedHttpRequest.Length) { - socket.Send(Encoding.ASCII.GetBytes("HTTP/1.0 200 OK\r\n")); - socket.Send(Encoding.ASCII.GetBytes("Content-Type: application/octet-stream\r\n")); - socket.Send(Encoding.ASCII.GetBytes("\r\n")); - socket.Send(Encoding.ASCII.GetBytes("SSH4EVER")); + _ = socket.Send(Encoding.ASCII.GetBytes("HTTP/1.0 200 OK\r\n")); + _ = socket.Send(Encoding.ASCII.GetBytes("Content-Type: application/octet-stream\r\n")); + _ = socket.Send(Encoding.ASCII.GetBytes("\r\n")); + _ = socket.Send(Encoding.ASCII.GetBytes("SSH4EVER")); + socket.Shutdown(SocketShutdown.Send); } }; @@ -68,18 +71,15 @@ protected override void SetupData() protected override void SetupMocks() { - SocketFactoryMock.Setup(p => p.Create(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) - .Returns(_clientSocket); + _ = SocketFactoryMock.Setup(p => p.Create(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) + .Returns(_clientSocket); } protected override void TearDown() { base.TearDown(); - if (_proxyServer != null) - { - _proxyServer.Dispose(); - } + _proxyServer?.Dispose(); if (_clientSocket != null) { diff --git a/src/Renci.SshNet.Tests/Classes/Connection/HttpConnectorTest_Connect_ProxyResponseStatusIsNot200.cs b/src/Renci.SshNet.Tests/Classes/Connection/HttpConnectorTest_Connect_ProxyResponseStatusIsNot200.cs index 8edca1811..b2cdc5fd3 100644 --- a/src/Renci.SshNet.Tests/Classes/Connection/HttpConnectorTest_Connect_ProxyResponseStatusIsNot200.cs +++ b/src/Renci.SshNet.Tests/Classes/Connection/HttpConnectorTest_Connect_ProxyResponseStatusIsNot200.cs @@ -1,14 +1,17 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; -using Renci.SshNet.Common; -using Renci.SshNet.Tests.Common; -using System; +using System; using System.Collections.Generic; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +using Moq; + +using Renci.SshNet.Common; +using Renci.SshNet.Tests.Common; + namespace Renci.SshNet.Tests.Classes.Connection { [TestClass] @@ -33,8 +36,10 @@ protected override void SetupData() 8122, "proxyUser", "proxyPwd", - new KeyboardInteractiveAuthenticationMethod("user")); - _connectionInfo.Timeout = TimeSpan.FromMilliseconds(100); + new KeyboardInteractiveAuthenticationMethod("user")) + { + Timeout = TimeSpan.FromMilliseconds(100) + }; _bytesReceivedByProxy = new List(); _actualException = null; @@ -46,7 +51,8 @@ protected override void SetupData() { if (_bytesReceivedByProxy.Count == 0) { - socket.Send(Encoding.ASCII.GetBytes("HTTP/1.0 404 I searched everywhere, really...\r\n")); + _ = socket.Send(Encoding.ASCII.GetBytes("HTTP/1.0 404 I searched everywhere, really...\r\n")); + socket.Shutdown(SocketShutdown.Send); } @@ -57,25 +63,22 @@ protected override void SetupData() protected override void SetupMocks() { - SocketFactoryMock.Setup(p => p.Create(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) - .Returns(_clientSocket); + _ = SocketFactoryMock.Setup(p => p.Create(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) + .Returns(_clientSocket); } protected override void TearDown() { base.TearDown(); - if (_proxyServer != null) - { - _proxyServer.Dispose(); - } + _proxyServer?.Dispose(); } protected override void Act() { try { - Connector.Connect(_connectionInfo); + _ = Connector.Connect(_connectionInfo); Assert.Fail(); } catch (ProxyException ex) @@ -106,7 +109,7 @@ public void ClientSocketShouldHaveBeenDisposed() { try { - _clientSocket.Receive(new byte[0]); + _ = _clientSocket.Receive(new byte[0]); Assert.Fail(); } catch (ObjectDisposedException) diff --git a/src/Renci.SshNet.Tests/Classes/Connection/HttpConnectorTest_Connect_ProxyUserNameIsEmpty.cs b/src/Renci.SshNet.Tests/Classes/Connection/HttpConnectorTest_Connect_ProxyUserNameIsEmpty.cs index d6b71bd04..455a41a9f 100644 --- a/src/Renci.SshNet.Tests/Classes/Connection/HttpConnectorTest_Connect_ProxyUserNameIsEmpty.cs +++ b/src/Renci.SshNet.Tests/Classes/Connection/HttpConnectorTest_Connect_ProxyUserNameIsEmpty.cs @@ -1,7 +1,4 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; -using Renci.SshNet.Tests.Common; -using System; +using System; using System.Collections.Generic; using System.Globalization; using System.Net; @@ -9,6 +6,12 @@ using System.Text; using System.Threading; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +using Moq; + +using Renci.SshNet.Tests.Common; + namespace Renci.SshNet.Tests.Classes.Connection { [TestClass] @@ -34,8 +37,10 @@ protected override void SetupData() 8122, string.Empty, "proxyPwd", - new KeyboardInteractiveAuthenticationMethod("user")); - _connectionInfo.Timeout = TimeSpan.FromMilliseconds(20); + new KeyboardInteractiveAuthenticationMethod("user")) + { + Timeout = TimeSpan.FromMilliseconds(20) + }; _expectedHttpRequest = string.Format("CONNECT {0}:{1} HTTP/1.0{2}{2}", _connectionInfo.Host, _connectionInfo.Port.ToString(CultureInfo.InvariantCulture), @@ -55,12 +60,12 @@ protected override void SetupData() // it sends the CONNECT request if (_bytesReceivedByProxy.Count == _expectedHttpRequest.Length) { - socket.Send(Encoding.ASCII.GetBytes("\r\n")); - socket.Send(Encoding.ASCII.GetBytes("SSH.NET\r\n")); - socket.Send(Encoding.ASCII.GetBytes("HTTP/1.0 200 OK\r\n")); - socket.Send(Encoding.ASCII.GetBytes("Content-Type: application/octet-stream\r\n")); - socket.Send(Encoding.ASCII.GetBytes("\r\n")); - socket.Send(Encoding.ASCII.GetBytes("SSH4EVER")); + _ = socket.Send(Encoding.ASCII.GetBytes("\r\n")); + _ = socket.Send(Encoding.ASCII.GetBytes("SSH.NET\r\n")); + _ = socket.Send(Encoding.ASCII.GetBytes("HTTP/1.0 200 OK\r\n")); + _ = socket.Send(Encoding.ASCII.GetBytes("Content-Type: application/octet-stream\r\n")); + _ = socket.Send(Encoding.ASCII.GetBytes("\r\n")); + _ = socket.Send(Encoding.ASCII.GetBytes("SSH4EVER")); } }; _proxyServer.Start(); @@ -68,23 +73,16 @@ protected override void SetupData() protected override void SetupMocks() { - SocketFactoryMock.Setup(p => p.Create(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) - .Returns(_clientSocket); + _ = SocketFactoryMock.Setup(p => p.Create(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) + .Returns(_clientSocket); } protected override void TearDown() { base.TearDown(); - if (_proxyServer != null) - { - _proxyServer.Dispose(); - } - - if (_clientSocket != null) - { - _clientSocket.Close(); - } + _proxyServer?.Dispose(); + _clientSocket?.Close(); } protected override void Act() diff --git a/src/Renci.SshNet.Tests/Classes/Connection/HttpConnectorTest_Connect_ProxyUserNameIsNotNullAndNotEmpty.cs b/src/Renci.SshNet.Tests/Classes/Connection/HttpConnectorTest_Connect_ProxyUserNameIsNotNullAndNotEmpty.cs index a12558714..b49d1b12a 100644 --- a/src/Renci.SshNet.Tests/Classes/Connection/HttpConnectorTest_Connect_ProxyUserNameIsNotNullAndNotEmpty.cs +++ b/src/Renci.SshNet.Tests/Classes/Connection/HttpConnectorTest_Connect_ProxyUserNameIsNotNullAndNotEmpty.cs @@ -1,7 +1,4 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; -using Renci.SshNet.Tests.Common; -using System; +using System; using System.Collections.Generic; using System.Globalization; using System.Net; @@ -9,6 +6,12 @@ using System.Text; using System.Threading; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +using Moq; + +using Renci.SshNet.Tests.Common; + namespace Renci.SshNet.Tests.Classes.Connection { [TestClass] @@ -34,8 +37,10 @@ protected override void SetupData() 8122, "user", "pwd", - new KeyboardInteractiveAuthenticationMethod("user")); - _connectionInfo.Timeout = TimeSpan.FromMilliseconds(20); + new KeyboardInteractiveAuthenticationMethod("user")) + { + Timeout = TimeSpan.FromMilliseconds(20) + }; _expectedHttpRequest = string.Format("CONNECT {0}:{1} HTTP/1.0{2}" + "Proxy-Authorization: Basic dXNlcjpwd2Q={2}{2}", _connectionInfo.Host, @@ -48,10 +53,10 @@ protected override void SetupData() _proxyServer = new AsyncSocketListener(new IPEndPoint(IPAddress.Loopback, _connectionInfo.ProxyPort)); _proxyServer.Connected += (socket) => { - socket.Send(Encoding.ASCII.GetBytes("HTTP/1.0 200 OK\r\n")); - socket.Send(Encoding.ASCII.GetBytes("Content-Type: application/octet-stream\r\n")); - socket.Send(Encoding.ASCII.GetBytes("\r\n")); - socket.Send(Encoding.ASCII.GetBytes("SSH4EVER")); + _ = socket.Send(Encoding.ASCII.GetBytes("HTTP/1.0 200 OK\r\n")); + _ = socket.Send(Encoding.ASCII.GetBytes("Content-Type: application/octet-stream\r\n")); + _ = socket.Send(Encoding.ASCII.GetBytes("\r\n")); + _ = socket.Send(Encoding.ASCII.GetBytes("SSH4EVER")); }; _proxyServer.Disconnected += (socket) => _disconnected = true; _proxyServer.BytesReceived += (bytesReceived, socket) => @@ -63,18 +68,15 @@ protected override void SetupData() protected override void SetupMocks() { - SocketFactoryMock.Setup(p => p.Create(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) - .Returns(_clientSocket); + _ = SocketFactoryMock.Setup(p => p.Create(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) + .Returns(_clientSocket); } protected override void TearDown() { base.TearDown(); - if (_proxyServer != null) - { - _proxyServer.Dispose(); - } + _proxyServer?.Dispose(); if (_clientSocket != null) { diff --git a/src/Renci.SshNet.Tests/Classes/Connection/HttpConnectorTest_Connect_ProxyUserNameIsNull.cs b/src/Renci.SshNet.Tests/Classes/Connection/HttpConnectorTest_Connect_ProxyUserNameIsNull.cs index 0e11e189b..59a022bc8 100644 --- a/src/Renci.SshNet.Tests/Classes/Connection/HttpConnectorTest_Connect_ProxyUserNameIsNull.cs +++ b/src/Renci.SshNet.Tests/Classes/Connection/HttpConnectorTest_Connect_ProxyUserNameIsNull.cs @@ -1,7 +1,4 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; -using Renci.SshNet.Tests.Common; -using System; +using System; using System.Collections.Generic; using System.Globalization; using System.Net; @@ -9,6 +6,12 @@ using System.Text; using System.Threading; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +using Moq; + +using Renci.SshNet.Tests.Common; + namespace Renci.SshNet.Tests.Classes.Connection { [TestClass] @@ -34,8 +37,10 @@ protected override void SetupData() 8122, null, "proxyPwd", - new KeyboardInteractiveAuthenticationMethod("user")); - _connectionInfo.Timeout = TimeSpan.FromMilliseconds(20); + new KeyboardInteractiveAuthenticationMethod("user")) + { + Timeout = TimeSpan.FromMilliseconds(20) + }; _expectedHttpRequest = string.Format("CONNECT {0}:{1} HTTP/1.0{2}{2}", _connectionInfo.Host, _connectionInfo.Port.ToString(CultureInfo.InvariantCulture), @@ -55,12 +60,12 @@ protected override void SetupData() // it sends the CONNECT request if (_bytesReceivedByProxy.Count == _expectedHttpRequest.Length) { - socket.Send(Encoding.ASCII.GetBytes("\r\n")); - socket.Send(Encoding.ASCII.GetBytes("SSH.NET\r\n")); - socket.Send(Encoding.ASCII.GetBytes("HTTP/1.0 200 OK\r\n")); - socket.Send(Encoding.ASCII.GetBytes("Content-Type: application/octet-stream\r\n")); - socket.Send(Encoding.ASCII.GetBytes("\r\n")); - socket.Send(Encoding.ASCII.GetBytes("SSH4EVER")); + _ = socket.Send(Encoding.ASCII.GetBytes("\r\n")); + _ = socket.Send(Encoding.ASCII.GetBytes("SSH.NET\r\n")); + _ = socket.Send(Encoding.ASCII.GetBytes("HTTP/1.0 200 OK\r\n")); + _ = socket.Send(Encoding.ASCII.GetBytes("Content-Type: application/octet-stream\r\n")); + _ = socket.Send(Encoding.ASCII.GetBytes("\r\n")); + _ = socket.Send(Encoding.ASCII.GetBytes("SSH4EVER")); } }; _proxyServer.Start(); @@ -68,8 +73,8 @@ protected override void SetupData() protected override void SetupMocks() { - SocketFactoryMock.Setup(p => p.Create(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) - .Returns(_clientSocket); + _ = SocketFactoryMock.Setup(p => p.Create(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) + .Returns(_clientSocket); } protected override void TearDown() @@ -82,10 +87,7 @@ protected override void TearDown() _clientSocket.Close(); } - if (_proxyServer != null) - { - _proxyServer.Dispose(); - } + _proxyServer?.Dispose(); } protected override void Act() diff --git a/src/Renci.SshNet.Tests/Classes/Connection/HttpConnectorTest_Connect_TimeoutConnectingToProxy.cs b/src/Renci.SshNet.Tests/Classes/Connection/HttpConnectorTest_Connect_TimeoutConnectingToProxy.cs index 61e35cf36..bb8041c89 100644 --- a/src/Renci.SshNet.Tests/Classes/Connection/HttpConnectorTest_Connect_TimeoutConnectingToProxy.cs +++ b/src/Renci.SshNet.Tests/Classes/Connection/HttpConnectorTest_Connect_TimeoutConnectingToProxy.cs @@ -1,12 +1,15 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; -using Renci.SshNet.Common; -using System; +using System; using System.Diagnostics; using System.Globalization; using System.Net; using System.Net.Sockets; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +using Moq; + +using Renci.SshNet.Common; + namespace Renci.SshNet.Tests.Classes.Connection { [TestClass] @@ -31,8 +34,10 @@ protected override void SetupData() 8122, "proxyUser", "proxyPwd", - new KeyboardInteractiveAuthenticationMethod("user")); - _connectionInfo.Timeout = TimeSpan.FromMilliseconds(random.Next(50, 200)); + new KeyboardInteractiveAuthenticationMethod("user")) + { + Timeout = TimeSpan.FromMilliseconds(random.Next(50, 200)) + }; _stopWatch = new Stopwatch(); _actualException = null; @@ -41,18 +46,15 @@ protected override void SetupData() protected override void SetupMocks() { - SocketFactoryMock.Setup(p => p.Create(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) - .Returns(_clientSocket); + _ = SocketFactoryMock.Setup(p => p.Create(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) + .Returns(_clientSocket); } protected override void TearDown() { base.TearDown(); - if (_clientSocket != null) - { - _clientSocket.Dispose(); - } + _clientSocket?.Dispose(); } protected override void Act() @@ -61,7 +63,7 @@ protected override void Act() try { - Connector.Connect(_connectionInfo); + _ = Connector.Connect(_connectionInfo); Assert.Fail(); } catch (SshOperationTimeoutException ex) @@ -98,7 +100,7 @@ public void ClientSocketShouldHaveBeenDisposed() { try { - _clientSocket.Receive(new byte[0]); + _ = _clientSocket.Receive(new byte[0]); Assert.Fail(); } catch (ObjectDisposedException) diff --git a/src/Renci.SshNet.Tests/Classes/Connection/HttpConnectorTest_Connect_TimeoutReadingHttpContent.cs b/src/Renci.SshNet.Tests/Classes/Connection/HttpConnectorTest_Connect_TimeoutReadingHttpContent.cs index 9c219c016..5db6b2353 100644 --- a/src/Renci.SshNet.Tests/Classes/Connection/HttpConnectorTest_Connect_TimeoutReadingHttpContent.cs +++ b/src/Renci.SshNet.Tests/Classes/Connection/HttpConnectorTest_Connect_TimeoutReadingHttpContent.cs @@ -1,9 +1,4 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; -using Renci.SshNet.Common; -using Renci.SshNet.Connection; -using Renci.SshNet.Tests.Common; -using System; +using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; @@ -12,6 +7,14 @@ using System.Text; using System.Threading; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +using Moq; + +using Renci.SshNet.Common; +using Renci.SshNet.Connection; +using Renci.SshNet.Tests.Common; + namespace Renci.SshNet.Tests.Classes.Connection { [TestClass] @@ -41,8 +44,10 @@ protected override void SetupData() 8122, "proxyUser", "proxyPwd", - new KeyboardInteractiveAuthenticationMethod("user")); - _connectionInfo.Timeout = TimeSpan.FromMilliseconds(random.Next(50, 200)); + new KeyboardInteractiveAuthenticationMethod("user")) + { + Timeout = TimeSpan.FromMilliseconds(random.Next(50, 200)) + }; _expectedHttpRequest = string.Format("CONNECT {0}:{1} HTTP/1.0{2}" + "Proxy-Authorization: Basic cHJveHlVc2VyOnByb3h5UHdk{2}{2}", _connectionInfo.Host, @@ -63,11 +68,11 @@ protected override void SetupData() // Force a timeout by sending less content than indicated by Content-Length header if (_bytesReceivedByProxy.Count == _expectedHttpRequest.Length) { - socket.Send(Encoding.ASCII.GetBytes("HTTP/1.0 200 OK\r\n")); - socket.Send(Encoding.ASCII.GetBytes("Content-Length: 10\r\n")); - socket.Send(Encoding.ASCII.GetBytes("Content-Type: application/octet-stream\r\n")); - socket.Send(Encoding.ASCII.GetBytes("\r\n")); - socket.Send(Encoding.ASCII.GetBytes("TOO_FEW")); + _ = socket.Send(Encoding.ASCII.GetBytes("HTTP/1.0 200 OK\r\n")); + _ = socket.Send(Encoding.ASCII.GetBytes("Content-Length: 10\r\n")); + _ = socket.Send(Encoding.ASCII.GetBytes("Content-Type: application/octet-stream\r\n")); + _ = socket.Send(Encoding.ASCII.GetBytes("\r\n")); + _ = socket.Send(Encoding.ASCII.GetBytes("TOO_FEW")); } }; _proxyServer.Start(); @@ -78,23 +83,16 @@ protected override void SetupData() protected override void SetupMocks() { - SocketFactoryMock.Setup(p => p.Create(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) - .Returns(_clientSocket); + _ = SocketFactoryMock.Setup(p => p.Create(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) + .Returns(_clientSocket); } protected override void TearDown() { base.TearDown(); - if (_server != null) - { - _server.Dispose(); - } - - if (_proxyServer != null) - { - _proxyServer.Dispose(); - } + _server?.Dispose(); + _proxyServer?.Dispose(); } protected override void Act() @@ -103,7 +101,7 @@ protected override void Act() try { - Connector.Connect(_connectionInfo); + _ = Connector.Connect(_connectionInfo); Assert.Fail(); } catch (SshOperationTimeoutException ex) @@ -156,7 +154,7 @@ public void ClientSocketShouldHaveBeenDisposed() { try { - _clientSocket.Receive(new byte[0]); + _ = _clientSocket.Receive(new byte[0]); Assert.Fail(); } catch (ObjectDisposedException) diff --git a/src/Renci.SshNet.Tests/Classes/Connection/HttpConnectorTest_Connect_TimeoutReadingStatusLine.cs b/src/Renci.SshNet.Tests/Classes/Connection/HttpConnectorTest_Connect_TimeoutReadingStatusLine.cs index a05212312..10aa8bd91 100644 --- a/src/Renci.SshNet.Tests/Classes/Connection/HttpConnectorTest_Connect_TimeoutReadingStatusLine.cs +++ b/src/Renci.SshNet.Tests/Classes/Connection/HttpConnectorTest_Connect_TimeoutReadingStatusLine.cs @@ -1,15 +1,18 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; -using Renci.SshNet.Common; -using Renci.SshNet.Connection; -using Renci.SshNet.Tests.Common; -using System; +using System; using System.Diagnostics; using System.Globalization; using System.Net; using System.Net.Sockets; using System.Threading; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +using Moq; + +using Renci.SshNet.Common; +using Renci.SshNet.Connection; +using Renci.SshNet.Tests.Common; + namespace Renci.SshNet.Tests.Classes.Connection { [TestClass] @@ -37,8 +40,10 @@ protected override void SetupData() 8122, "proxyUser", "proxyPwd", - new KeyboardInteractiveAuthenticationMethod("user")); - _connectionInfo.Timeout = TimeSpan.FromMilliseconds(random.Next(50, 200)); + new KeyboardInteractiveAuthenticationMethod("user")) + { + Timeout = TimeSpan.FromMilliseconds(random.Next(50, 200)) + }; _stopWatch = new Stopwatch(); _actualException = null; @@ -54,23 +59,16 @@ protected override void SetupData() protected override void SetupMocks() { - SocketFactoryMock.Setup(p => p.Create(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) - .Returns(_clientSocket); + _ = SocketFactoryMock.Setup(p => p.Create(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) + .Returns(_clientSocket); } protected override void TearDown() { base.TearDown(); - if (_server != null) - { - _server.Dispose(); - } - - if (_proxyServer != null) - { - _proxyServer.Dispose(); - } + _server?.Dispose(); + _proxyServer?.Dispose(); } protected override void Act() @@ -79,7 +77,7 @@ protected override void Act() try { - Connector.Connect(_connectionInfo); + _ = Connector.Connect(_connectionInfo); Assert.Fail(); } catch (SshOperationTimeoutException ex) @@ -126,7 +124,7 @@ public void ClientSocketShouldHaveBeenDisposed() { try { - _clientSocket.Receive(new byte[0]); + _ = _clientSocket.Receive(new byte[0]); Assert.Fail(); } catch (ObjectDisposedException) diff --git a/src/Renci.SshNet.Tests/Classes/Connection/ProtocolVersionExchangeTest_ServerResponseInvalid_SshIdentificationOnlyContainsProtocolVersion.cs b/src/Renci.SshNet.Tests/Classes/Connection/ProtocolVersionExchangeTest_ServerResponseInvalid_SshIdentificationOnlyContainsProtocolVersion.cs index b97ba5f8f..3b0649517 100644 --- a/src/Renci.SshNet.Tests/Classes/Connection/ProtocolVersionExchangeTest_ServerResponseInvalid_SshIdentificationOnlyContainsProtocolVersion.cs +++ b/src/Renci.SshNet.Tests/Classes/Connection/ProtocolVersionExchangeTest_ServerResponseInvalid_SshIdentificationOnlyContainsProtocolVersion.cs @@ -1,8 +1,4 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Renci.SshNet.Common; -using Renci.SshNet.Connection; -using Renci.SshNet.Tests.Common; -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Net; @@ -10,6 +6,12 @@ using System.Text; using System.Threading; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +using Renci.SshNet.Common; +using Renci.SshNet.Connection; +using Renci.SshNet.Tests.Common; + namespace Renci.SshNet.Tests.Classes.Connection { [TestClass] @@ -63,7 +65,9 @@ protected void Arrange() _server.BytesReceived += (bytes, socket) => { _dataReceivedByServer.AddRange(bytes); - socket.Send(_serverIdentification); + + _ = socket.Send(_serverIdentification); + socket.Shutdown(SocketShutdown.Send); }; _server.Disconnected += (socket) => _clientDisconnected = true; @@ -78,7 +82,7 @@ protected void Act() { try { - _protocolVersionExchange.Start(_clientVersion, _client, _timeout); + _ = _protocolVersionExchange.Start(_clientVersion, _client, _timeout); Assert.Fail(); } catch (SshConnectionException ex) diff --git a/src/Renci.SshNet.Tests/Classes/Connection/ProtocolVersionExchangeTest_ServerResponseValid_TerminatedByLineFeedWithoutCarriageReturn.cs b/src/Renci.SshNet.Tests/Classes/Connection/ProtocolVersionExchangeTest_ServerResponseValid_TerminatedByLineFeedWithoutCarriageReturn.cs index f66afe057..7aa26b309 100644 --- a/src/Renci.SshNet.Tests/Classes/Connection/ProtocolVersionExchangeTest_ServerResponseValid_TerminatedByLineFeedWithoutCarriageReturn.cs +++ b/src/Renci.SshNet.Tests/Classes/Connection/ProtocolVersionExchangeTest_ServerResponseValid_TerminatedByLineFeedWithoutCarriageReturn.cs @@ -1,8 +1,4 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Renci.SshNet.Common; -using Renci.SshNet.Connection; -using Renci.SshNet.Tests.Common; -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Net; @@ -10,6 +6,12 @@ using System.Text; using System.Threading; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +using Renci.SshNet.Common; +using Renci.SshNet.Connection; +using Renci.SshNet.Tests.Common; + namespace Renci.SshNet.Tests.Classes.Connection { [TestClass] @@ -61,11 +63,13 @@ protected void Arrange() _server = new AsyncSocketListener(_serverEndPoint); _server.Start(); _server.BytesReceived += (bytes, socket) => - { - _dataReceivedByServer.AddRange(bytes); - socket.Send(_serverIdentification); - socket.Shutdown(SocketShutdown.Send); - }; + { + _dataReceivedByServer.AddRange(bytes); + + _ = socket.Send(_serverIdentification); + + socket.Shutdown(SocketShutdown.Send); + }; _server.Disconnected += (socket) => _clientDisconnected = true; _client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); diff --git a/src/Renci.SshNet.Tests/Classes/Connection/ProtocolVersionExchangeTest_TimeoutReadingIdentificationString.cs b/src/Renci.SshNet.Tests/Classes/Connection/ProtocolVersionExchangeTest_TimeoutReadingIdentificationString.cs index 238d7e337..3710e2064 100644 --- a/src/Renci.SshNet.Tests/Classes/Connection/ProtocolVersionExchangeTest_TimeoutReadingIdentificationString.cs +++ b/src/Renci.SshNet.Tests/Classes/Connection/ProtocolVersionExchangeTest_TimeoutReadingIdentificationString.cs @@ -1,8 +1,4 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Renci.SshNet.Common; -using Renci.SshNet.Connection; -using Renci.SshNet.Tests.Common; -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Net; @@ -10,6 +6,12 @@ using System.Text; using System.Threading; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +using Renci.SshNet.Common; +using Renci.SshNet.Connection; +using Renci.SshNet.Tests.Common; + namespace Renci.SshNet.Tests.Classes.Connection { [TestClass] @@ -61,7 +63,8 @@ protected void Arrange() _server.BytesReceived += (bytes, socket) => { _dataReceivedByServer.AddRange(bytes); - socket.Send(Encoding.UTF8.GetBytes("Welcome!\r\n")); + + _ = socket.Send(Encoding.UTF8.GetBytes("Welcome!\r\n")); }; _server.Disconnected += (socket) => _clientDisconnected = true; @@ -75,7 +78,7 @@ protected void Act() { try { - _protocolVersionExchange.Start(_clientVersion, _client, _timeout); + _ = _protocolVersionExchange.Start(_clientVersion, _client, _timeout); Assert.Fail(); } catch (SshOperationTimeoutException ex) diff --git a/src/Renci.SshNet.Tests/Classes/Connection/Socks4ConnectorTestBase.cs b/src/Renci.SshNet.Tests/Classes/Connection/Socks4ConnectorTestBase.cs index 16dc70006..0c3497f12 100644 --- a/src/Renci.SshNet.Tests/Classes/Connection/Socks4ConnectorTestBase.cs +++ b/src/Renci.SshNet.Tests/Classes/Connection/Socks4ConnectorTestBase.cs @@ -1,8 +1,9 @@ -using Moq; +using System.Net; + +using Moq; + using Renci.SshNet.Connection; using Renci.SshNet.Tests.Common; -using System.Net; -using System.Threading; namespace Renci.SshNet.Tests.Classes.Connection { diff --git a/src/Renci.SshNet.Tests/Classes/Connection/Socks4ConnectorTest_Connect_ConnectionRejectedByProxy.cs b/src/Renci.SshNet.Tests/Classes/Connection/Socks4ConnectorTest_Connect_ConnectionRejectedByProxy.cs index e993fa573..a220b9423 100644 --- a/src/Renci.SshNet.Tests/Classes/Connection/Socks4ConnectorTest_Connect_ConnectionRejectedByProxy.cs +++ b/src/Renci.SshNet.Tests/Classes/Connection/Socks4ConnectorTest_Connect_ConnectionRejectedByProxy.cs @@ -1,13 +1,16 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; -using Renci.SshNet.Common; -using Renci.SshNet.Tests.Common; -using System; +using System; using System.Collections.Generic; using System.Net; using System.Net.Sockets; using System.Threading; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +using Moq; + +using Renci.SshNet.Common; +using Renci.SshNet.Tests.Common; + namespace Renci.SshNet.Tests.Classes.Connection { [TestClass] @@ -36,7 +39,7 @@ protected override void SetupData() { if (_bytesReceivedByProxy.Count == 0) { - socket.Send(new byte[] + _ = socket.Send(new byte[] { // Reply version (null byte) 0x00, @@ -52,30 +55,23 @@ protected override void SetupData() protected override void SetupMocks() { - SocketFactoryMock.Setup(p => p.Create(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) - .Returns(_clientSocket); + _ = SocketFactoryMock.Setup(p => p.Create(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) + .Returns(_clientSocket); } protected override void TearDown() { base.TearDown(); - if (_proxyServer != null) - { - _proxyServer.Dispose(); - } - - if (_clientSocket != null) - { - _clientSocket.Dispose(); - } + _proxyServer?.Dispose(); + _clientSocket?.Dispose(); } protected override void Act() { try { - Connector.Connect(_connectionInfo); + _ = Connector.Connect(_connectionInfo); Assert.Fail(); } catch (ProxyException ex) @@ -106,7 +102,7 @@ public void ClientSocketShouldHaveBeenDisposed() { try { - _clientSocket.Receive(new byte[0]); + _ = _clientSocket.Receive(new byte[0]); Assert.Fail(); } catch (ObjectDisposedException) @@ -120,19 +116,5 @@ public void CreateOnSocketFactoryShouldHaveBeenInvokedOnce() SocketFactoryMock.Verify(p => p.Create(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp), Times.Once()); } - - private static byte GetNotSupportedSocksVersion() - { - var random = new Random(); - - while (true) - { - var socksVersion = random.Next(1, 255); - if (socksVersion != 4) - { - return (byte) socksVersion; - } - } - } } } diff --git a/src/Renci.SshNet.Tests/Classes/Connection/Socks4ConnectorTest_Connect_ConnectionSucceeded.cs b/src/Renci.SshNet.Tests/Classes/Connection/Socks4ConnectorTest_Connect_ConnectionSucceeded.cs index f4c97c639..b482b753c 100644 --- a/src/Renci.SshNet.Tests/Classes/Connection/Socks4ConnectorTest_Connect_ConnectionSucceeded.cs +++ b/src/Renci.SshNet.Tests/Classes/Connection/Socks4ConnectorTest_Connect_ConnectionSucceeded.cs @@ -1,15 +1,18 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; -using Renci.SshNet.Common; -using Renci.SshNet.Connection; -using Renci.SshNet.Tests.Common; -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Sockets; using System.Threading; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +using Moq; + +using Renci.SshNet.Common; +using Renci.SshNet.Connection; +using Renci.SshNet.Tests.Common; + namespace Renci.SshNet.Tests.Classes.Connection { [TestClass] @@ -43,7 +46,7 @@ protected override void SetupData() if (_bytesReceivedByProxy.Count == bytesReceived.Length) { // Send SOCKS response - socket.Send(new byte[] + _ = socket.Send(new byte[] { // Reply version (null byte) 0x00, @@ -60,7 +63,7 @@ protected override void SetupData() }); // Send extra byte to allow us to verify that connector did not consume too much - socket.Send(new byte[] + _ = socket.Send(new byte[] { 0xfe }); @@ -71,23 +74,16 @@ protected override void SetupData() protected override void SetupMocks() { - SocketFactoryMock.Setup(p => p.Create(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) - .Returns(_clientSocket); + _ = SocketFactoryMock.Setup(p => p.Create(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) + .Returns(_clientSocket); } protected override void TearDown() { base.TearDown(); - if (_proxyServer != null) - { - _proxyServer.Dispose(); - } - - if (_clientSocket != null) - { - _clientSocket.Dispose(); - } + _proxyServer?.Dispose(); + _clientSocket?.Dispose(); } protected override void Act() diff --git a/src/Renci.SshNet.Tests/Classes/Connection/Socks4ConnectorTest_Connect_ConnectionToProxyRefused.cs b/src/Renci.SshNet.Tests/Classes/Connection/Socks4ConnectorTest_Connect_ConnectionToProxyRefused.cs index 176a5a57b..7c41d93d0 100644 --- a/src/Renci.SshNet.Tests/Classes/Connection/Socks4ConnectorTest_Connect_ConnectionToProxyRefused.cs +++ b/src/Renci.SshNet.Tests/Classes/Connection/Socks4ConnectorTest_Connect_ConnectionToProxyRefused.cs @@ -1,10 +1,11 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; -using Renci.SshNet.Common; -using System; +using System; using System.Diagnostics; using System.Net.Sockets; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +using Moq; + namespace Renci.SshNet.Tests.Classes.Connection { [TestClass] @@ -29,18 +30,15 @@ protected override void SetupData() protected override void SetupMocks() { - SocketFactoryMock.Setup(p => p.Create(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) - .Returns(_clientSocket); + _ = SocketFactoryMock.Setup(p => p.Create(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) + .Returns(_clientSocket); } protected override void TearDown() { base.TearDown(); - if (_clientSocket != null) - { - _clientSocket.Dispose(); - } + _clientSocket?.Dispose(); } protected override void Act() @@ -49,7 +47,7 @@ protected override void Act() try { - Connector.Connect(_connectionInfo); + _ = Connector.Connect(_connectionInfo); Assert.Fail(); } catch (SocketException ex) @@ -85,7 +83,7 @@ public void ClientSocketShouldHaveBeenDisposed() { try { - _clientSocket.Receive(new byte[0]); + _ = _clientSocket.Receive(new byte[0]); Assert.Fail(); } catch (ObjectDisposedException) diff --git a/src/Renci.SshNet.Tests/Classes/Connection/Socks4ConnectorTest_Connect_TimeoutConnectingToProxy.cs b/src/Renci.SshNet.Tests/Classes/Connection/Socks4ConnectorTest_Connect_TimeoutConnectingToProxy.cs index 7c7ad08f4..d7ad42157 100644 --- a/src/Renci.SshNet.Tests/Classes/Connection/Socks4ConnectorTest_Connect_TimeoutConnectingToProxy.cs +++ b/src/Renci.SshNet.Tests/Classes/Connection/Socks4ConnectorTest_Connect_TimeoutConnectingToProxy.cs @@ -31,18 +31,15 @@ protected override void SetupData() protected override void SetupMocks() { - SocketFactoryMock.Setup(p => p.Create(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) - .Returns(_clientSocket); + _ = SocketFactoryMock.Setup(p => p.Create(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) + .Returns(_clientSocket); } protected override void TearDown() { base.TearDown(); - if (_clientSocket != null) - { - _clientSocket.Dispose(); - } + _clientSocket?.Dispose(); } protected override void Act() @@ -51,7 +48,7 @@ protected override void Act() try { - Connector.Connect(_connectionInfo); + _ = Connector.Connect(_connectionInfo); Assert.Fail(); } catch (SshOperationTimeoutException ex) @@ -88,7 +85,7 @@ public void ClientSocketShouldHaveBeenDisposed() { try { - _clientSocket.Receive(new byte[0]); + _ = _clientSocket.Receive(new byte[0]); Assert.Fail(); } catch (ObjectDisposedException) diff --git a/src/Renci.SshNet.Tests/Classes/Connection/Socks4ConnectorTest_Connect_TimeoutReadingDestinationAddress.cs b/src/Renci.SshNet.Tests/Classes/Connection/Socks4ConnectorTest_Connect_TimeoutReadingDestinationAddress.cs index 0981e13a9..d8121e894 100644 --- a/src/Renci.SshNet.Tests/Classes/Connection/Socks4ConnectorTest_Connect_TimeoutReadingDestinationAddress.cs +++ b/src/Renci.SshNet.Tests/Classes/Connection/Socks4ConnectorTest_Connect_TimeoutReadingDestinationAddress.cs @@ -1,15 +1,18 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; -using Renci.SshNet.Common; -using Renci.SshNet.Connection; -using Renci.SshNet.Tests.Common; -using System; +using System; using System.Diagnostics; using System.Globalization; using System.Net; using System.Net.Sockets; using System.Threading; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +using Moq; + +using Renci.SshNet.Common; +using Renci.SshNet.Connection; +using Renci.SshNet.Tests.Common; + namespace Renci.SshNet.Tests.Classes.Connection { [TestClass] @@ -40,7 +43,7 @@ protected override void SetupData() _proxyServer.Disconnected += socket => _disconnected = true; _proxyServer.Connected += socket => { - socket.Send(new byte[] + _ = socket.Send(new byte[] { // Reply version (null byte) 0x00, @@ -58,23 +61,16 @@ protected override void SetupData() protected override void SetupMocks() { - SocketFactoryMock.Setup(p => p.Create(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) - .Returns(_clientSocket); + _ = SocketFactoryMock.Setup(p => p.Create(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) + .Returns(_clientSocket); } protected override void TearDown() { base.TearDown(); - if (_server != null) - { - _server.Dispose(); - } - - if (_proxyServer != null) - { - _proxyServer.Dispose(); - } + _server?.Dispose(); + _proxyServer?.Dispose(); } protected override void Act() @@ -83,7 +79,7 @@ protected override void Act() try { - Connector.Connect(_connectionInfo); + _ = Connector.Connect(_connectionInfo); Assert.Fail(); } catch (SshOperationTimeoutException ex) @@ -130,7 +126,7 @@ public void ClientSocketShouldHaveBeenDisposed() { try { - _clientSocket.Receive(new byte[0]); + _ = _clientSocket.Receive(new byte[0]); Assert.Fail(); } catch (ObjectDisposedException) diff --git a/src/Renci.SshNet.Tests/Classes/Connection/Socks4ConnectorTest_Connect_TimeoutReadingReplyCode.cs b/src/Renci.SshNet.Tests/Classes/Connection/Socks4ConnectorTest_Connect_TimeoutReadingReplyCode.cs index cdcc667ec..1aaa36e4a 100644 --- a/src/Renci.SshNet.Tests/Classes/Connection/Socks4ConnectorTest_Connect_TimeoutReadingReplyCode.cs +++ b/src/Renci.SshNet.Tests/Classes/Connection/Socks4ConnectorTest_Connect_TimeoutReadingReplyCode.cs @@ -1,15 +1,18 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; -using Renci.SshNet.Common; -using Renci.SshNet.Connection; -using Renci.SshNet.Tests.Common; -using System; +using System; using System.Diagnostics; using System.Globalization; using System.Net; using System.Net.Sockets; using System.Threading; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +using Moq; + +using Renci.SshNet.Common; +using Renci.SshNet.Connection; +using Renci.SshNet.Tests.Common; + namespace Renci.SshNet.Tests.Classes.Connection { [TestClass] @@ -40,7 +43,7 @@ protected override void SetupData() _proxyServer.Disconnected += socket => _disconnected = true; _proxyServer.Connected += socket => { - socket.Send(new byte[] + _ = socket.Send(new byte[] { // Reply version (null byte) 0x00 @@ -54,23 +57,16 @@ protected override void SetupData() protected override void SetupMocks() { - SocketFactoryMock.Setup(p => p.Create(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) - .Returns(_clientSocket); + _ = SocketFactoryMock.Setup(p => p.Create(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) + .Returns(_clientSocket); } protected override void TearDown() { base.TearDown(); - if (_server != null) - { - _server.Dispose(); - } - - if (_proxyServer != null) - { - _proxyServer.Dispose(); - } + _server?.Dispose(); + _proxyServer?.Dispose(); } protected override void Act() @@ -79,7 +75,7 @@ protected override void Act() try { - Connector.Connect(_connectionInfo); + _ = Connector.Connect(_connectionInfo); Assert.Fail(); } catch (SshOperationTimeoutException ex) diff --git a/src/Renci.SshNet.Tests/Classes/Connection/Socks4ConnectorTest_Connect_TimeoutReadingReplyVersion.cs b/src/Renci.SshNet.Tests/Classes/Connection/Socks4ConnectorTest_Connect_TimeoutReadingReplyVersion.cs index 15751c79a..37b7f8389 100644 --- a/src/Renci.SshNet.Tests/Classes/Connection/Socks4ConnectorTest_Connect_TimeoutReadingReplyVersion.cs +++ b/src/Renci.SshNet.Tests/Classes/Connection/Socks4ConnectorTest_Connect_TimeoutReadingReplyVersion.cs @@ -46,23 +46,16 @@ protected override void SetupData() protected override void SetupMocks() { - SocketFactoryMock.Setup(p => p.Create(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) - .Returns(_clientSocket); + _ = SocketFactoryMock.Setup(p => p.Create(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) + .Returns(_clientSocket); } protected override void TearDown() { base.TearDown(); - if (_server != null) - { - _server.Dispose(); - } - - if (_proxyServer != null) - { - _proxyServer.Dispose(); - } + _server?.Dispose(); + _proxyServer?.Dispose(); } protected override void Act() @@ -71,7 +64,7 @@ protected override void Act() try { - Connector.Connect(_connectionInfo); + _ = Connector.Connect(_connectionInfo); Assert.Fail(); } catch (SshOperationTimeoutException ex) @@ -118,7 +111,7 @@ public void ClientSocketShouldHaveBeenDisposed() { try { - _clientSocket.Receive(new byte[0]); + _ = _clientSocket.Receive(new byte[0]); Assert.Fail(); } catch (ObjectDisposedException) diff --git a/src/Renci.SshNet.Tests/Classes/Connection/Socks5ConnectorTestBase.cs b/src/Renci.SshNet.Tests/Classes/Connection/Socks5ConnectorTestBase.cs index 9125fb34e..fefe5728e 100644 --- a/src/Renci.SshNet.Tests/Classes/Connection/Socks5ConnectorTestBase.cs +++ b/src/Renci.SshNet.Tests/Classes/Connection/Socks5ConnectorTestBase.cs @@ -1,10 +1,11 @@ using Moq; + using Renci.SshNet.Connection; using Renci.SshNet.Tests.Common; + using System; using System.Net; using System.Text; -using System.Threading; namespace Renci.SshNet.Tests.Classes.Connection { @@ -59,8 +60,8 @@ protected static string GenerateRandomString(int minLength, int maxLength) for (var i = 0; i < length; i++) { - var @char = (char) random.Next(offset, offset + 26); - sb.Append(@char); + var c = (char) random.Next(offset, offset + 26); + _ = sb.Append(c); } return sb.ToString(); diff --git a/src/Renci.SshNet.Tests/Classes/Connection/Socks5ConnectorTest_Connect_ConnectionToProxyRefused.cs b/src/Renci.SshNet.Tests/Classes/Connection/Socks5ConnectorTest_Connect_ConnectionToProxyRefused.cs index 82e195fb4..05bd850dc 100644 --- a/src/Renci.SshNet.Tests/Classes/Connection/Socks5ConnectorTest_Connect_ConnectionToProxyRefused.cs +++ b/src/Renci.SshNet.Tests/Classes/Connection/Socks5ConnectorTest_Connect_ConnectionToProxyRefused.cs @@ -1,11 +1,11 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; -using Renci.SshNet.Common; -using System; +using System; using System.Diagnostics; -using System.Net; using System.Net.Sockets; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +using Moq; + namespace Renci.SshNet.Tests.Classes.Connection { [TestClass] @@ -30,18 +30,15 @@ protected override void SetupData() protected override void SetupMocks() { - SocketFactoryMock.Setup(p => p.Create(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) - .Returns(_clientSocket); + _ = SocketFactoryMock.Setup(p => p.Create(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) + .Returns(_clientSocket); } protected override void TearDown() { base.TearDown(); - if (_clientSocket != null) - { - _clientSocket.Dispose(); - } + _clientSocket?.Dispose(); } protected override void Act() @@ -50,7 +47,7 @@ protected override void Act() try { - Connector.Connect(_connectionInfo); + _ = Connector.Connect(_connectionInfo); Assert.Fail(); } catch (SocketException ex) @@ -86,7 +83,7 @@ public void ClientSocketShouldHaveBeenDisposed() { try { - _clientSocket.Receive(new byte[0]); + _ = _clientSocket.Receive(new byte[0]); Assert.Fail(); } catch (ObjectDisposedException) diff --git a/src/Renci.SshNet.Tests/Classes/Connection/Socks5ConnectorTest_Connect_NoAuthentication_ConnectionSucceeded.cs b/src/Renci.SshNet.Tests/Classes/Connection/Socks5ConnectorTest_Connect_NoAuthentication_ConnectionSucceeded.cs index 61afbf71c..e51548840 100644 --- a/src/Renci.SshNet.Tests/Classes/Connection/Socks5ConnectorTest_Connect_NoAuthentication_ConnectionSucceeded.cs +++ b/src/Renci.SshNet.Tests/Classes/Connection/Socks5ConnectorTest_Connect_NoAuthentication_ConnectionSucceeded.cs @@ -39,7 +39,7 @@ protected override void SetupData() { // We received the greeting - socket.Send(new byte[] + _ = socket.Send(new byte[] { // SOCKS version 0x05, @@ -51,7 +51,7 @@ protected override void SetupData() { // We received the connection request - socket.Send(new byte[] + _ = socket.Send(new byte[] { // SOCKS version 0x05, @@ -62,7 +62,7 @@ protected override void SetupData() }); // Send server bound address - socket.Send(new byte[] + _ = socket.Send(new byte[] { // IPv6 0x04, @@ -89,7 +89,7 @@ protected override void SetupData() }); // Send extra byte to allow us to verify that connector did not consume too much - socket.Send(new byte[] + _ = socket.Send(new byte[] { 0xff }); @@ -100,18 +100,15 @@ protected override void SetupData() protected override void SetupMocks() { - SocketFactoryMock.Setup(p => p.Create(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) - .Returns(_clientSocket); + _ = SocketFactoryMock.Setup(p => p.Create(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) + .Returns(_clientSocket); } protected override void TearDown() { base.TearDown(); - if (_proxyServer != null) - { - _proxyServer.Dispose(); - } + _proxyServer?.Dispose(); if (_clientSocket != null) { diff --git a/src/Renci.SshNet.Tests/Classes/Connection/Socks5ConnectorTest_Connect_ProxySocksVersionIsNotSupported.cs b/src/Renci.SshNet.Tests/Classes/Connection/Socks5ConnectorTest_Connect_ProxySocksVersionIsNotSupported.cs index e90bd32c1..76cd2568f 100644 --- a/src/Renci.SshNet.Tests/Classes/Connection/Socks5ConnectorTest_Connect_ProxySocksVersionIsNotSupported.cs +++ b/src/Renci.SshNet.Tests/Classes/Connection/Socks5ConnectorTest_Connect_ProxySocksVersionIsNotSupported.cs @@ -1,12 +1,15 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; -using Renci.SshNet.Common; -using Renci.SshNet.Tests.Common; -using System; +using System; using System.Net; using System.Net.Sockets; using System.Threading; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +using Moq; + +using Renci.SshNet.Common; +using Renci.SshNet.Tests.Common; + namespace Renci.SshNet.Tests.Classes.Connection { [TestClass] @@ -34,37 +37,30 @@ protected override void SetupData() _proxyServer.Disconnected += socket => _disconnected = true; _proxyServer.BytesReceived += (bytesReceived, socket) => { - socket.Send(new byte[] { _proxySocksVersion }); + _ = socket.Send(new byte[] { _proxySocksVersion }); }; _proxyServer.Start(); } protected override void SetupMocks() { - SocketFactoryMock.Setup(p => p.Create(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) - .Returns(_clientSocket); + _ = SocketFactoryMock.Setup(p => p.Create(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) + .Returns(_clientSocket); } protected override void TearDown() { base.TearDown(); - if (_proxyServer != null) - { - _proxyServer.Dispose(); - } - - if (_clientSocket != null) - { - _clientSocket.Dispose(); - } + _proxyServer?.Dispose(); + _clientSocket?.Dispose(); } protected override void Act() { try { - Connector.Connect(_connectionInfo); + _ = Connector.Connect(_connectionInfo); Assert.Fail(); } catch (ProxyException ex) @@ -95,7 +91,7 @@ public void ClientSocketShouldHaveBeenDisposed() { try { - _clientSocket.Receive(new byte[0]); + _ = _clientSocket.Receive(new byte[0]); Assert.Fail(); } catch (ObjectDisposedException) diff --git a/src/Renci.SshNet.Tests/Classes/Connection/Socks5ConnectorTest_Connect_TimeoutConnectingToProxy.cs b/src/Renci.SshNet.Tests/Classes/Connection/Socks5ConnectorTest_Connect_TimeoutConnectingToProxy.cs index e93d8dc55..720c24ff9 100644 --- a/src/Renci.SshNet.Tests/Classes/Connection/Socks5ConnectorTest_Connect_TimeoutConnectingToProxy.cs +++ b/src/Renci.SshNet.Tests/Classes/Connection/Socks5ConnectorTest_Connect_TimeoutConnectingToProxy.cs @@ -1,12 +1,14 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; -using Renci.SshNet.Common; -using System; +using System; using System.Diagnostics; using System.Globalization; -using System.Net; using System.Net.Sockets; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +using Moq; + +using Renci.SshNet.Common; + namespace Renci.SshNet.Tests.Classes.Connection { [TestClass] @@ -33,18 +35,15 @@ protected override void SetupData() protected override void SetupMocks() { - SocketFactoryMock.Setup(p => p.Create(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) - .Returns(_clientSocket); + _ = SocketFactoryMock.Setup(p => p.Create(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) + .Returns(_clientSocket); } protected override void TearDown() { base.TearDown(); - if (_clientSocket != null) - { - _clientSocket.Dispose(); - } + _clientSocket?.Dispose(); } protected override void Act() @@ -53,7 +52,7 @@ protected override void Act() try { - Connector.Connect(_connectionInfo); + _ = Connector.Connect(_connectionInfo); Assert.Fail(); } catch (SshOperationTimeoutException ex) @@ -90,7 +89,7 @@ public void ClientSocketShouldHaveBeenDisposed() { try { - _clientSocket.Receive(new byte[0]); + _ = _clientSocket.Receive(new byte[0]); Assert.Fail(); } catch (ObjectDisposedException) diff --git a/src/Renci.SshNet.Tests/Classes/Connection/Socks5ConnectorTest_Connect_UserNamePasswordAuthentication_AuthenticationFailed.cs b/src/Renci.SshNet.Tests/Classes/Connection/Socks5ConnectorTest_Connect_UserNamePasswordAuthentication_AuthenticationFailed.cs index a76a100e2..e6bcf5abe 100644 --- a/src/Renci.SshNet.Tests/Classes/Connection/Socks5ConnectorTest_Connect_UserNamePasswordAuthentication_AuthenticationFailed.cs +++ b/src/Renci.SshNet.Tests/Classes/Connection/Socks5ConnectorTest_Connect_UserNamePasswordAuthentication_AuthenticationFailed.cs @@ -42,7 +42,7 @@ protected override void SetupData() { // We received the greeting - socket.Send(new byte[] + _ = socket.Send(new byte[] { // SOCKS version 0x05, @@ -54,7 +54,7 @@ protected override void SetupData() { // We received the username/password authentication request - socket.Send(new byte[] + _ = socket.Send(new byte[] { // Authentication version 0x01, @@ -68,30 +68,23 @@ protected override void SetupData() protected override void SetupMocks() { - SocketFactoryMock.Setup(p => p.Create(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) - .Returns(_clientSocket); + _ = SocketFactoryMock.Setup(p => p.Create(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) + .Returns(_clientSocket); } protected override void TearDown() { base.TearDown(); - if (_proxyServer != null) - { - _proxyServer.Dispose(); - } - - if (_clientSocket != null) - { - _clientSocket.Dispose(); - } + _proxyServer?.Dispose(); + _clientSocket?.Dispose(); } protected override void Act() { try { - Connector.Connect(_connectionInfo); + _ = Connector.Connect(_connectionInfo); Assert.Fail(); } catch (ProxyException ex) @@ -163,7 +156,7 @@ public void ClientSocketShouldHaveBeenDisposed() { try { - _clientSocket.Receive(new byte[0]); + _ = _clientSocket.Receive(new byte[0]); Assert.Fail(); } catch (ObjectDisposedException) diff --git a/src/Renci.SshNet.Tests/Classes/Connection/Socks5ConnectorTest_Connect_UserNamePasswordAuthentication_ConnectionSucceeded.cs b/src/Renci.SshNet.Tests/Classes/Connection/Socks5ConnectorTest_Connect_UserNamePasswordAuthentication_ConnectionSucceeded.cs index a9f7e4ef1..0c13af50d 100644 --- a/src/Renci.SshNet.Tests/Classes/Connection/Socks5ConnectorTest_Connect_UserNamePasswordAuthentication_ConnectionSucceeded.cs +++ b/src/Renci.SshNet.Tests/Classes/Connection/Socks5ConnectorTest_Connect_UserNamePasswordAuthentication_ConnectionSucceeded.cs @@ -1,8 +1,4 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; -using Renci.SshNet.Common; -using Renci.SshNet.Tests.Common; -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Net; @@ -10,6 +6,13 @@ using System.Text; using System.Threading; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +using Moq; + +using Renci.SshNet.Common; +using Renci.SshNet.Tests.Common; + namespace Renci.SshNet.Tests.Classes.Connection { [TestClass] @@ -40,7 +43,7 @@ protected override void SetupData() { // We received the greeting - socket.Send(new byte[] + _ = socket.Send(new byte[] { // SOCKS version 0x05, @@ -52,7 +55,7 @@ protected override void SetupData() { // We received the username/password authentication request - socket.Send(new byte[] + _ = socket.Send(new byte[] { // Authentication version 0x01, @@ -64,7 +67,7 @@ protected override void SetupData() { // We received the connection request - socket.Send(new byte[] + _ = socket.Send(new byte[] { // SOCKS version 0x05, @@ -75,7 +78,7 @@ protected override void SetupData() }); // Send server bound address - socket.Send(new byte[] + _ = socket.Send(new byte[] { // IPv4 0x01, @@ -90,7 +93,7 @@ protected override void SetupData() }); // Send extra byte to allow us to verify that connector did not consume too much - socket.Send(new byte[] + _ = socket.Send(new byte[] { 0xfe }); @@ -101,18 +104,15 @@ protected override void SetupData() protected override void SetupMocks() { - SocketFactoryMock.Setup(p => p.Create(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) - .Returns(_clientSocket); + _ = SocketFactoryMock.Setup(p => p.Create(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) + .Returns(_clientSocket); } protected override void TearDown() { base.TearDown(); - if (_proxyServer != null) - { - _proxyServer.Dispose(); - } + _proxyServer?.Dispose(); if (_clientSocket != null) { diff --git a/src/Renci.SshNet.Tests/Classes/Connection/Socks5ConnectorTest_Connect_UserNamePasswordAuthentication_PasswordExceedsMaximumLength.cs b/src/Renci.SshNet.Tests/Classes/Connection/Socks5ConnectorTest_Connect_UserNamePasswordAuthentication_PasswordExceedsMaximumLength.cs index 5e1d5389b..b36a7eff9 100644 --- a/src/Renci.SshNet.Tests/Classes/Connection/Socks5ConnectorTest_Connect_UserNamePasswordAuthentication_PasswordExceedsMaximumLength.cs +++ b/src/Renci.SshNet.Tests/Classes/Connection/Socks5ConnectorTest_Connect_UserNamePasswordAuthentication_PasswordExceedsMaximumLength.cs @@ -41,7 +41,7 @@ protected override void SetupData() // Wait until we received the greeting if (_bytesReceivedByProxy.Count == 4) { - socket.Send(new byte[] + _ = socket.Send(new byte[] { // SOCKS version 0x05, @@ -55,30 +55,23 @@ protected override void SetupData() protected override void SetupMocks() { - SocketFactoryMock.Setup(p => p.Create(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) - .Returns(_clientSocket); + _ = SocketFactoryMock.Setup(p => p.Create(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) + .Returns(_clientSocket); } protected override void TearDown() { base.TearDown(); - if (_proxyServer != null) - { - _proxyServer.Dispose(); - } - - if (_clientSocket != null) - { - _clientSocket.Dispose(); - } + _proxyServer?.Dispose(); + _clientSocket?.Dispose(); } protected override void Act() { try { - Connector.Connect(_connectionInfo); + _ = Connector.Connect(_connectionInfo); Assert.Fail(); } catch (ProxyException ex) @@ -135,7 +128,7 @@ public void ClientSocketShouldHaveBeenDisposed() { try { - _clientSocket.Receive(new byte[0]); + _ = _clientSocket.Receive(new byte[0]); Assert.Fail(); } catch (ObjectDisposedException) diff --git a/src/Renci.SshNet.Tests/Classes/Connection/Socks5ConnectorTest_Connect_UserNamePasswordAuthentication_UserNameExceedsMaximumLength.cs b/src/Renci.SshNet.Tests/Classes/Connection/Socks5ConnectorTest_Connect_UserNamePasswordAuthentication_UserNameExceedsMaximumLength.cs index 653b41181..83a58f89e 100644 --- a/src/Renci.SshNet.Tests/Classes/Connection/Socks5ConnectorTest_Connect_UserNamePasswordAuthentication_UserNameExceedsMaximumLength.cs +++ b/src/Renci.SshNet.Tests/Classes/Connection/Socks5ConnectorTest_Connect_UserNamePasswordAuthentication_UserNameExceedsMaximumLength.cs @@ -1,14 +1,17 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; -using Renci.SshNet.Common; -using Renci.SshNet.Tests.Common; -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Sockets; using System.Threading; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +using Moq; + +using Renci.SshNet.Common; +using Renci.SshNet.Tests.Common; + namespace Renci.SshNet.Tests.Classes.Connection { [TestClass] @@ -41,7 +44,7 @@ protected override void SetupData() // Wait until we received the greeting if (_bytesReceivedByProxy.Count == 4) { - socket.Send(new byte[] + _ = socket.Send(new byte[] { // SOCKS version 0x05, @@ -55,30 +58,23 @@ protected override void SetupData() protected override void SetupMocks() { - SocketFactoryMock.Setup(p => p.Create(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) - .Returns(_clientSocket); + _ = SocketFactoryMock.Setup(p => p.Create(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) + .Returns(_clientSocket); } protected override void TearDown() { base.TearDown(); - if (_proxyServer != null) - { - _proxyServer.Dispose(); - } - - if (_clientSocket != null) - { - _clientSocket.Dispose(); - } + _proxyServer?.Dispose(); + _clientSocket?.Dispose(); } protected override void Act() { try { - Connector.Connect(_connectionInfo); + _ = Connector.Connect(_connectionInfo); Assert.Fail(); } catch (ProxyException ex) @@ -101,20 +97,18 @@ public void ConnectShouldHaveThrownProxyException() [TestMethod] public void ProxyShouldHaveReceivedExpectedSocksRequest() { - var expectedSocksRequest = new List(); - - // // Client greeting - // - - // SOCKS version - expectedSocksRequest.Add(0x05); - // Number of authentication methods supported - expectedSocksRequest.Add(0x02); - // No authentication - expectedSocksRequest.Add(0x00); - // Username/password - expectedSocksRequest.Add(0x02); + var expectedSocksRequest = new List + { + // SOCKS version + 0x05, + // Number of authentication methods supported + 0x02, + // No authentication + 0x00, + // Username/password + 0x02 + }; var errorText = string.Format("Expected:{0}{1}{0}but was:{0}{2}", Environment.NewLine, @@ -135,7 +129,7 @@ public void ClientSocketShouldHaveBeenDisposed() { try { - _clientSocket.Receive(new byte[0]); + _ = _clientSocket.Receive(new byte[0]); Assert.Fail(); } catch (ObjectDisposedException) diff --git a/src/Renci.SshNet.Tests/Classes/Connection/SshIdentificationTest.cs b/src/Renci.SshNet.Tests/Classes/Connection/SshIdentificationTest.cs index 2a7137aed..3d18cfa53 100644 --- a/src/Renci.SshNet.Tests/Classes/Connection/SshIdentificationTest.cs +++ b/src/Renci.SshNet.Tests/Classes/Connection/SshIdentificationTest.cs @@ -27,7 +27,7 @@ public void Ctor_ProtocolVersionAndSoftwareVersion_ProtocolVersionIsNull() try { - new SshIdentification(protocolVersion, softwareVersion); + _ = new SshIdentification(protocolVersion, softwareVersion); Assert.Fail(); } catch (ArgumentNullException ex) @@ -45,7 +45,7 @@ public void Ctor_ProtocolVersionAndSoftwareVersion_SoftwareVersionIsNull() try { - new SshIdentification(protocolVersion, softwareVersion); + _ = new SshIdentification(protocolVersion, softwareVersion); Assert.Fail(); } catch (ArgumentNullException ex) @@ -90,7 +90,7 @@ public void Ctor_ProtocolVersionAndSoftwareVersionAndComments_ProtocolVersionIsN try { - new SshIdentification(protocolVersion, softwareVersion, comments); + _ = new SshIdentification(protocolVersion, softwareVersion, comments); Assert.Fail(); } catch (ArgumentNullException ex) @@ -109,7 +109,7 @@ public void Ctor_ProtocolVersionAndSoftwareVersionAndComments_SoftwareVersionIsN try { - new SshIdentification(protocolVersion, softwareVersion, comments); + _ = new SshIdentification(protocolVersion, softwareVersion, comments); Assert.Fail(); } catch (ArgumentNullException ex) diff --git a/src/Renci.SshNet.Tests/Classes/ConnectionInfoTest.cs b/src/Renci.SshNet.Tests/Classes/ConnectionInfoTest.cs index 5fc1cd832..c6b19ca49 100644 --- a/src/Renci.SshNet.Tests/Classes/ConnectionInfoTest.cs +++ b/src/Renci.SshNet.Tests/Classes/ConnectionInfoTest.cs @@ -33,9 +33,15 @@ public void ConstructorShouldThrowArgumentNullExceptionhenProxyTypesIsNotNoneAnd { try { - new ConnectionInfo(Resources.HOST, int.Parse(Resources.PORT), Resources.USERNAME, ProxyTypes.Http, null, - int.Parse(Resources.PORT), Resources.USERNAME, Resources.PASSWORD, - new KeyboardInteractiveAuthenticationMethod(Resources.USERNAME)); + _ = new ConnectionInfo(Resources.HOST, + int.Parse(Resources.PORT), + Resources.USERNAME, + ProxyTypes.Http, + null, + int.Parse(Resources.PORT), + Resources.USERNAME, + Resources.PASSWORD, + new KeyboardInteractiveAuthenticationMethod(Resources.USERNAME)); Assert.Fail(); } catch (ArgumentNullException ex) @@ -51,8 +57,14 @@ public void ConstructorShouldNotThrowExceptionWhenProxyTypesIsNotNoneAndProxyHos { var proxyHost = string.Empty; - var connectionInfo = new ConnectionInfo(Resources.HOST, int.Parse(Resources.PORT), Resources.USERNAME, - ProxyTypes.Http, string.Empty, int.Parse(Resources.PORT), Resources.USERNAME, Resources.PASSWORD, + var connectionInfo = new ConnectionInfo(Resources.HOST, + int.Parse(Resources.PORT), + Resources.USERNAME, + ProxyTypes.Http, + string.Empty, + int.Parse(Resources.PORT), + Resources.USERNAME, + Resources.PASSWORD, new KeyboardInteractiveAuthenticationMethod(Resources.USERNAME)); Assert.AreSame(proxyHost, connectionInfo.ProxyHost); @@ -66,7 +78,15 @@ public void ConstructorShouldThrowArgumentOutOfRangeExceptionWhenProxyTypesIsNot try { - new ConnectionInfo(Resources.HOST, int.Parse(Resources.PORT), Resources.USERNAME, ProxyTypes.Http, Resources.HOST, ++maxPort, Resources.USERNAME, Resources.PASSWORD, null); + _ = new ConnectionInfo(Resources.HOST, + int.Parse(Resources.PORT), + Resources.USERNAME, + ProxyTypes.Http, + Resources.HOST, + ++maxPort, + Resources.USERNAME, + Resources.PASSWORD, + null); Assert.Fail(); } catch (ArgumentOutOfRangeException ex) @@ -84,7 +104,15 @@ public void ConstructorShouldThrowArgumentOutOfRangeExceptionWhenProxyTypesIsNot try { - new ConnectionInfo(Resources.HOST, int.Parse(Resources.PORT), Resources.USERNAME, ProxyTypes.Http, Resources.HOST, --minPort, Resources.USERNAME, Resources.PASSWORD, null); + _ = new ConnectionInfo(Resources.HOST, + int.Parse(Resources.PORT), + Resources.USERNAME, + ProxyTypes.Http, + Resources.HOST, + --minPort, + Resources.USERNAME, + Resources.PASSWORD, + null); Assert.Fail(); } catch (ArgumentOutOfRangeException ex) @@ -126,8 +154,15 @@ public void ConstructorShouldThrowArgumentNullExceptionhenHostIsNull() { try { - new ConnectionInfo(null, int.Parse(Resources.PORT), Resources.USERNAME, ProxyTypes.None, Resources.HOST, - int.Parse(Resources.PORT), Resources.USERNAME, Resources.PASSWORD, null); + _ = new ConnectionInfo(null, + int.Parse(Resources.PORT), + Resources.USERNAME, + ProxyTypes.None, + Resources.HOST, + int.Parse(Resources.PORT), + Resources.USERNAME, + Resources.PASSWORD, + null); } catch (ArgumentNullException ex) { @@ -183,8 +218,15 @@ public void ConstructorShouldThrowArgumentOutOfRangeExceptionWhenPortIsGreaterTh try { - new ConnectionInfo(Resources.HOST, port, Resources.USERNAME, ProxyTypes.None, Resources.HOST, - int.Parse(Resources.PORT), Resources.USERNAME, Resources.PASSWORD, null); + _ = new ConnectionInfo(Resources.HOST, + port, + Resources.USERNAME, + ProxyTypes.None, + Resources.HOST, + int.Parse(Resources.PORT), + Resources.USERNAME, + Resources.PASSWORD, + null); Assert.Fail(); } catch (ArgumentOutOfRangeException ex) @@ -202,8 +244,15 @@ public void ConstructorShouldThrowArgumentOutOfRangeExceptionWhenPortIsLessThanM try { - new ConnectionInfo(Resources.HOST, port, Resources.USERNAME, ProxyTypes.None, Resources.HOST, - int.Parse(Resources.PORT), Resources.USERNAME, Resources.PASSWORD, null); + _ = new ConnectionInfo(Resources.HOST, + port, + Resources.USERNAME, + ProxyTypes.None, + Resources.HOST, + int.Parse(Resources.PORT), + Resources.USERNAME, + Resources.PASSWORD, + null); Assert.Fail(); } catch (ArgumentOutOfRangeException ex) @@ -234,9 +283,15 @@ public void ConstructorShouldThrowArgumentExceptionhenUsernameIsNull() try { - new ConnectionInfo(Resources.HOST, int.Parse(Resources.PORT), username, ProxyTypes.Http, Resources.USERNAME, - int.Parse(Resources.PORT), Resources.USERNAME, Resources.PASSWORD, - new KeyboardInteractiveAuthenticationMethod(Resources.USERNAME)); + _ = new ConnectionInfo(Resources.HOST, + int.Parse(Resources.PORT), + username, + ProxyTypes.Http, + Resources.USERNAME, + int.Parse(Resources.PORT), + Resources.USERNAME, + Resources.PASSWORD, + new KeyboardInteractiveAuthenticationMethod(Resources.USERNAME)); Assert.Fail(); } catch (ArgumentNullException ex) @@ -254,9 +309,15 @@ public void ConstructorShouldThrowArgumentExceptionhenUsernameIsEmpty() try { - new ConnectionInfo(Resources.HOST, int.Parse(Resources.PORT), username, ProxyTypes.Http, Resources.USERNAME, - int.Parse(Resources.PORT), Resources.USERNAME, Resources.PASSWORD, - new KeyboardInteractiveAuthenticationMethod(Resources.USERNAME)); + _ = new ConnectionInfo(Resources.HOST, + int.Parse(Resources.PORT), + username, + ProxyTypes.Http, + Resources.USERNAME, + int.Parse(Resources.PORT), + Resources.USERNAME, + Resources.PASSWORD, + new KeyboardInteractiveAuthenticationMethod(Resources.USERNAME)); Assert.Fail(); } catch (ArgumentException ex) @@ -275,9 +336,15 @@ public void ConstructorShouldThrowArgumentExceptionhenUsernameContainsOnlyWhites try { - new ConnectionInfo(Resources.HOST, int.Parse(Resources.PORT), username, ProxyTypes.Http, Resources.USERNAME, - int.Parse(Resources.PORT), Resources.USERNAME, Resources.PASSWORD, - new KeyboardInteractiveAuthenticationMethod(Resources.USERNAME)); + _ = new ConnectionInfo(Resources.HOST, + int.Parse(Resources.PORT), + username, + ProxyTypes.Http, + Resources.USERNAME, + int.Parse(Resources.PORT), + Resources.USERNAME, + Resources.PASSWORD, + new KeyboardInteractiveAuthenticationMethod(Resources.USERNAME)); Assert.Fail(); } catch (ArgumentException ex) @@ -294,8 +361,15 @@ public void ConstructorShouldThrowArgumentNullExceptionWhenAuthenticationMethods { try { - new ConnectionInfo(Resources.HOST, int.Parse(Resources.PORT), Resources.USERNAME, ProxyTypes.None, Resources.HOST, - int.Parse(Resources.PORT), Resources.USERNAME, Resources.PASSWORD, null); + _ = new ConnectionInfo(Resources.HOST, + int.Parse(Resources.PORT), + Resources.USERNAME, + ProxyTypes.None, + Resources.HOST, + int.Parse(Resources.PORT), + Resources.USERNAME, + Resources.PASSWORD, + null); Assert.Fail(); } catch (ArgumentNullException ex) @@ -311,8 +385,15 @@ public void ConstructorShouldThrowArgumentNullExceptionWhenAuthenticationMethods { try { - new ConnectionInfo(Resources.HOST, int.Parse(Resources.PORT), Resources.USERNAME, ProxyTypes.None, Resources.HOST, - int.Parse(Resources.PORT), Resources.USERNAME, Resources.PASSWORD, new AuthenticationMethod[0]); + _ = new ConnectionInfo(Resources.HOST, + int.Parse(Resources.PORT), + Resources.USERNAME, + ProxyTypes.None, + Resources.HOST, + int.Parse(Resources.PORT), + Resources.USERNAME, + Resources.PASSWORD, + new AuthenticationMethod[0]); Assert.Fail(); } catch (ArgumentException ex) @@ -326,11 +407,18 @@ public void ConstructorShouldThrowArgumentNullExceptionWhenAuthenticationMethods [TestCategory("ConnectionInfo")] public void AuthenticateShouldThrowArgumentNullExceptionWhenServiceFactoryIsNull() { - var connectionInfo = new ConnectionInfo(Resources.HOST, int.Parse(Resources.PORT), Resources.USERNAME, ProxyTypes.None, - Resources.HOST, int.Parse(Resources.PORT), Resources.USERNAME, Resources.PASSWORD, - new KeyboardInteractiveAuthenticationMethod(Resources.USERNAME)); + var connectionInfo = new ConnectionInfo(Resources.HOST, + int.Parse(Resources.PORT), + Resources.USERNAME, + ProxyTypes.None, + Resources.HOST, + int.Parse(Resources.PORT), + Resources.USERNAME, + Resources.PASSWORD, + new KeyboardInteractiveAuthenticationMethod(Resources.USERNAME)); + var session = new Mock(MockBehavior.Strict).Object; - IServiceFactory serviceFactory = null; + const IServiceFactory serviceFactory = null; try { @@ -344,4 +432,4 @@ public void AuthenticateShouldThrowArgumentNullExceptionWhenServiceFactoryIsNull } } } -} \ No newline at end of file +} diff --git a/src/Renci.SshNet.Tests/Classes/ForwardedPortDynamicTest_Dispose_PortNeverStarted.cs b/src/Renci.SshNet.Tests/Classes/ForwardedPortDynamicTest_Dispose_PortNeverStarted.cs index afa281d89..dfd07a273 100644 --- a/src/Renci.SshNet.Tests/Classes/ForwardedPortDynamicTest_Dispose_PortNeverStarted.cs +++ b/src/Renci.SshNet.Tests/Classes/ForwardedPortDynamicTest_Dispose_PortNeverStarted.cs @@ -2,9 +2,11 @@ using System.Collections.Generic; using System.Net; using System.Net.Sockets; + using Microsoft.VisualStudio.TestTools.UnitTesting; + using Moq; -using Renci.SshNet.Channels; + using Renci.SshNet.Common; namespace Renci.SshNet.Tests.Classes diff --git a/src/Renci.SshNet.Tests/Classes/ForwardedPortDynamicTest_Dispose_PortStarted_ChannelNotBound.cs b/src/Renci.SshNet.Tests/Classes/ForwardedPortDynamicTest_Dispose_PortStarted_ChannelNotBound.cs index 6c4439440..aa9957389 100644 --- a/src/Renci.SshNet.Tests/Classes/ForwardedPortDynamicTest_Dispose_PortStarted_ChannelNotBound.cs +++ b/src/Renci.SshNet.Tests/Classes/ForwardedPortDynamicTest_Dispose_PortStarted_ChannelNotBound.cs @@ -2,10 +2,12 @@ using System.Collections.Generic; using System.Net; using System.Net.Sockets; -using System.Runtime.InteropServices; using System.Threading; + using Microsoft.VisualStudio.TestTools.UnitTesting; + using Moq; + using Renci.SshNet.Channels; using Renci.SshNet.Common; diff --git a/src/Renci.SshNet.Tests/Classes/ForwardedPortDynamicTest_Started_SocketSendShutdownImmediately.cs b/src/Renci.SshNet.Tests/Classes/ForwardedPortDynamicTest_Started_SocketSendShutdownImmediately.cs index ffc104f17..9859be49f 100644 --- a/src/Renci.SshNet.Tests/Classes/ForwardedPortDynamicTest_Started_SocketSendShutdownImmediately.cs +++ b/src/Renci.SshNet.Tests/Classes/ForwardedPortDynamicTest_Started_SocketSendShutdownImmediately.cs @@ -2,10 +2,12 @@ using System.Collections.Generic; using System.Net; using System.Net.Sockets; -using System.Text; using System.Threading; + using Microsoft.VisualStudio.TestTools.UnitTesting; + using Moq; + using Renci.SshNet.Channels; using Renci.SshNet.Common; using Renci.SshNet.Tests.Common; @@ -38,8 +40,11 @@ public void Cleanup() { if (_forwardedPort != null && _forwardedPort.IsStarted) { - _sessionMock.Setup(p => p.ConnectionInfo).Returns(_connectionInfoMock.Object); - _connectionInfoMock.Setup(p => p.Timeout).Returns(TimeSpan.FromSeconds(5)); + _ = _sessionMock.Setup(p => p.ConnectionInfo) + .Returns(_connectionInfoMock.Object); + _ = _connectionInfoMock.Setup(p => p.Timeout) + .Returns(TimeSpan.FromSeconds(5)); + _forwardedPort.Stop(); } @@ -87,11 +92,21 @@ private void SetupMocks() { var seq = new MockSequence(); - _sessionMock.InSequence(seq).Setup(p => p.IsConnected).Returns(true); - _sessionMock.InSequence(seq).Setup(p => p.CreateChannelDirectTcpip()).Returns(_channelMock.Object); - _sessionMock.InSequence(seq).Setup(p => p.ConnectionInfo).Returns(_connectionInfoMock.Object); - _connectionInfoMock.InSequence(seq).Setup(p => p.Timeout).Returns(_connectionTimeout); - _channelMock.InSequence(seq).Setup(p => p.Dispose()).Callback(() => _channelDisposed.Set()); + _ = _sessionMock.InSequence(seq) + .Setup(p => p.IsConnected) + .Returns(true); + _ = _sessionMock.InSequence(seq) + .Setup(p => p.CreateChannelDirectTcpip()) + .Returns(_channelMock.Object); + _ = _sessionMock.InSequence(seq) + .Setup(p => p.ConnectionInfo) + .Returns(_connectionInfoMock.Object); + _ = _connectionInfoMock.InSequence(seq) + .Setup(p => p.Timeout) + .Returns(_connectionTimeout); + _ = _channelMock.InSequence(seq) + .Setup(p => p.Dispose()) + .Callback(() => _channelDisposed.Set()); } private void Arrange() @@ -110,7 +125,7 @@ private void Act() _client.Shutdown(SocketShutdown.Send); // wait for channel to be disposed - _channelDisposed.WaitOne(TimeSpan.FromMilliseconds(200)); + _ = _channelDisposed.WaitOne(TimeSpan.FromMilliseconds(200)); } [TestMethod] diff --git a/src/Renci.SshNet.Tests/Classes/ForwardedPortDynamicTest_Started_SocketVersionNotSupported.cs b/src/Renci.SshNet.Tests/Classes/ForwardedPortDynamicTest_Started_SocketVersionNotSupported.cs index 8eef3061f..e3dc264b5 100644 --- a/src/Renci.SshNet.Tests/Classes/ForwardedPortDynamicTest_Started_SocketVersionNotSupported.cs +++ b/src/Renci.SshNet.Tests/Classes/ForwardedPortDynamicTest_Started_SocketVersionNotSupported.cs @@ -2,10 +2,12 @@ using System.Collections.Generic; using System.Net; using System.Net.Sockets; -using System.Text; using System.Threading; + using Microsoft.VisualStudio.TestTools.UnitTesting; + using Moq; + using Renci.SshNet.Channels; using Renci.SshNet.Common; using Renci.SshNet.Tests.Common; diff --git a/src/Renci.SshNet.Tests/Classes/ForwardedPortDynamicTest_Stop_PortStarted_ChannelNotBound.cs b/src/Renci.SshNet.Tests/Classes/ForwardedPortDynamicTest_Stop_PortStarted_ChannelNotBound.cs index b84d947d5..34db4f9dd 100644 --- a/src/Renci.SshNet.Tests/Classes/ForwardedPortDynamicTest_Stop_PortStarted_ChannelNotBound.cs +++ b/src/Renci.SshNet.Tests/Classes/ForwardedPortDynamicTest_Stop_PortStarted_ChannelNotBound.cs @@ -2,10 +2,12 @@ using System.Collections.Generic; using System.Net; using System.Net.Sockets; -using System.Runtime.InteropServices; using System.Threading; + using Microsoft.VisualStudio.TestTools.UnitTesting; + using Moq; + using Renci.SshNet.Channels; using Renci.SshNet.Common; @@ -55,11 +57,15 @@ protected void Arrange() _sessionMock = new Mock(MockBehavior.Strict); _channelMock = new Mock(MockBehavior.Strict); - _connectionInfoMock.Setup(p => p.Timeout).Returns(TimeSpan.FromSeconds(15)); - _sessionMock.Setup(p => p.IsConnected).Returns(true); - _sessionMock.Setup(p => p.ConnectionInfo).Returns(_connectionInfoMock.Object); - _sessionMock.Setup(p => p.CreateChannelDirectTcpip()).Returns(_channelMock.Object); - _channelMock.Setup(p => p.Dispose()); + _ = _connectionInfoMock.Setup(p => p.Timeout) + .Returns(TimeSpan.FromSeconds(15)); + _ = _sessionMock.Setup(p => p.IsConnected) + .Returns(true); + _ = _sessionMock.Setup(p => p.ConnectionInfo) + .Returns(_connectionInfoMock.Object); + _ = _sessionMock.Setup(p => p.CreateChannelDirectTcpip()) + .Returns(_channelMock.Object); + _ = _channelMock.Setup(p => p.Dispose()); _forwardedPort = new ForwardedPortDynamic(_endpoint.Address.ToString(), (uint) _endpoint.Port); _forwardedPort.Closing += (sender, args) => _closingRegister.Add(args); @@ -112,7 +118,7 @@ public void ExistingConnectionShouldBeClosed() { try { - _client.Send(new byte[] { 0x0a }, 0, 1, SocketFlags.None); + _ = _client.Send(new byte[] { 0x0a }, 0, 1, SocketFlags.None); Assert.Fail(); } catch (SocketException ex) diff --git a/src/Renci.SshNet.Tests/Classes/ForwardedPortLocalTest.cs b/src/Renci.SshNet.Tests/Classes/ForwardedPortLocalTest.cs index 13b2c81b9..82459d00a 100644 --- a/src/Renci.SshNet.Tests/Classes/ForwardedPortLocalTest.cs +++ b/src/Renci.SshNet.Tests/Classes/ForwardedPortLocalTest.cs @@ -1,11 +1,18 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Renci.SshNet.Common; -using Renci.SshNet.Tests.Common; -using Renci.SshNet.Tests.Properties; -using System; +using System; using System.Diagnostics; +#if NET6_0_OR_GREATER +using System.Net.Http; +#else using System.Net; +#endif // NET6_0_OR_GREATER using System.Threading; +using System.Threading.Tasks; + +using Microsoft.VisualStudio.TestTools.UnitTesting; + +using Renci.SshNet.Common; +using Renci.SshNet.Tests.Common; +using Renci.SshNet.Tests.Properties; namespace Renci.SshNet.Tests.Classes { @@ -23,7 +30,7 @@ public partial class ForwardedPortLocalTest : TestBase [Description("Test if calling Stop on ForwardedPortLocal instance causes wait.")] public void Test_PortForwarding_Local_Stop_Hangs_On_Wait() { - using (var client = new SshClient(Resources.HOST, Int32.Parse(Resources.PORT), Resources.USERNAME, Resources.PASSWORD)) + using (var client = new SshClient(Resources.HOST, int.Parse(Resources.PORT), Resources.USERNAME, Resources.PASSWORD)) { client.Connect(); @@ -36,47 +43,57 @@ public void Test_PortForwarding_Local_Stop_Hangs_On_Wait() port1.Start(); - bool hasTestedTunnel = false; - System.Threading.ThreadPool.QueueUserWorkItem(delegate(object state) - { - try + var hasTestedTunnel = false; + + _ = ThreadPool.QueueUserWorkItem(delegate(object state) { - var url = "http://www.google.com/"; - Debug.WriteLine("Starting web request to \"" + url + "\""); - HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url); - HttpWebResponse response = (HttpWebResponse)request.GetResponse(); + try + { + var url = "http://www.google.com/"; + Debug.WriteLine("Starting web request to \"" + url + "\""); - Assert.IsNotNull(response); +#if NET6_0_OR_GREATER + var httpClient = new HttpClient(); + var response = httpClient.GetAsync(url) + .ConfigureAwait(false) + .GetAwaiter() + .GetResult(); +#else + var request = (HttpWebRequest) WebRequest.Create(url); + var response = (HttpWebResponse) request.GetResponse(); +#endif // NET6_0_OR_GREATER - Debug.WriteLine("Http Response status code: " + response.StatusCode.ToString()); + Assert.IsNotNull(response); - response.Close(); + Debug.WriteLine("Http Response status code: " + response.StatusCode.ToString()); - hasTestedTunnel = true; - } - catch (Exception ex) - { - Assert.Fail(ex.ToString()); - } - }); + response.Dispose(); + + hasTestedTunnel = true; + } + catch (Exception ex) + { + Assert.Fail(ex.ToString()); + } + }); // Wait for the web request to complete. while (!hasTestedTunnel) { - System.Threading.Thread.Sleep(1000); + Thread.Sleep(1000); } try { // Try stop the port forwarding, wait 3 seconds and fail if it is still started. - System.Threading.ThreadPool.QueueUserWorkItem(delegate(object state) - { - Debug.WriteLine("Trying to stop port forward."); - port1.Stop(); - Debug.WriteLine("Port forwarding stopped."); - }); + _ = ThreadPool.QueueUserWorkItem(delegate(object state) + { + Debug.WriteLine("Trying to stop port forward."); + port1.Stop(); + Debug.WriteLine("Port forwarding stopped."); + }); - System.Threading.Thread.Sleep(3000); + Thread.Sleep(3000); if (port1.IsStarted) { Assert.Fail("Port forwarding not stopped."); @@ -96,7 +113,7 @@ public void ConstructorShouldThrowArgumentNullExceptionWhenBoundHostIsNull() { try { - new ForwardedPortLocal(null, 8080, Resources.HOST, 80); + _ = new ForwardedPortLocal(null, 8080, Resources.HOST, 80); Assert.Fail(); } catch (ArgumentNullException ex) @@ -131,7 +148,7 @@ public void ConstructorShouldThrowArgumentNullExceptionWhenHostIsNull() { try { - new ForwardedPortLocal(Resources.HOST, 8080, null, 80); + _ = new ForwardedPortLocal(Resources.HOST, 8080, null, 80); Assert.Fail(); } catch (ArgumentNullException ex) @@ -188,7 +205,6 @@ public void Test_ForwardedPortRemote() Assert.Inconclusive("TODO: Implement code to verify target"); } -#if FEATURE_TPL [TestMethod] [TestCategory("integration")] [ExpectedException(typeof(SshConnectionException))] @@ -199,30 +215,33 @@ public void Test_PortForwarding_Local_Without_Connecting() var port1 = new ForwardedPortLocal("localhost", 8084, "www.renci.org", 80); client.AddForwardedPort(port1); port1.Exception += delegate (object sender, ExceptionEventArgs e) - { - Assert.Fail(e.Exception.ToString()); - }; - port1.Start(); - - System.Threading.Tasks.Parallel.For(0, 100, - - //new ParallelOptions - //{ - // MaxDegreeOfParallelism = 20, - //}, - (counter) => { - var start = DateTime.Now; - var req = HttpWebRequest.Create("http://localhost:8084"); - using (var response = req.GetResponse()) - { - var data = ReadStream(response.GetResponseStream()); - var end = DateTime.Now; + Assert.Fail(e.Exception.ToString()); + }; + port1.Start(); - Debug.WriteLine(string.Format("Request# {2}: Lenght: {0} Time: {1}", data.Length, (end - start), counter)); - } - } - ); + _ = Parallel.For(0, + 100, + counter => + { + var start = DateTime.Now; + +#if NET6_0_OR_GREATER + var httpClient = new HttpClient(); + using (var response = httpClient.GetAsync("http://localhost:8084").GetAwaiter().GetResult()) + { + var data = ReadStream(response.Content.ReadAsStream()); +#else + var request = (HttpWebRequest) WebRequest.Create("http://localhost:8084"); + using (var response = (HttpWebResponse) request.GetResponse()) + { + var data = ReadStream(response.GetResponseStream()); +#endif // NET6_0_OR_GREATER + var end = DateTime.Now; + + Debug.WriteLine(string.Format("Request# {2}: Lenght: {0} Time: {1}", data.Length, end - start, counter)); + } + }); } } @@ -236,48 +255,54 @@ public void Test_PortForwarding_Local() var port1 = new ForwardedPortLocal("localhost", 8084, "www.renci.org", 80); client.AddForwardedPort(port1); port1.Exception += delegate (object sender, ExceptionEventArgs e) - { - Assert.Fail(e.Exception.ToString()); - }; - port1.Start(); - - System.Threading.Tasks.Parallel.For(0, 100, - - //new ParallelOptions - //{ - // MaxDegreeOfParallelism = 20, - //}, - (counter) => { - var start = DateTime.Now; - var req = HttpWebRequest.Create("http://localhost:8084"); - using (var response = req.GetResponse()) - { - var data = ReadStream(response.GetResponseStream()); - var end = DateTime.Now; + Assert.Fail(e.Exception.ToString()); + }; + port1.Start(); - Debug.WriteLine(string.Format("Request# {2}: Length: {0} Time: {1}", data.Length, (end - start), counter)); - } - } - ); + _ = Parallel.For(0, + 100, + counter => + { + var start = DateTime.Now; + +#if NET6_0_OR_GREATER + var httpClient = new HttpClient(); + using (var response = httpClient.GetAsync("http://localhost:8084").GetAwaiter().GetResult()) + { + var data = ReadStream(response.Content.ReadAsStream()); +#else + var request = (HttpWebRequest) WebRequest.Create("http://localhost:8084"); + using (var response = (HttpWebResponse) request.GetResponse()) + { + var data = ReadStream(response.GetResponseStream()); +#endif // NET6_0_OR_GREATER + var end = DateTime.Now; + + Debug.WriteLine(string.Format("Request# {2}: Length: {0} Time: {1}", data.Length, end - start, counter)); + } + }); } } private static byte[] ReadStream(System.IO.Stream stream) { - byte[] buffer = new byte[1024]; + var buffer = new byte[1024]; using (var ms = new System.IO.MemoryStream()) { while (true) { - int read = stream.Read(buffer, 0, buffer.Length); + var read = stream.Read(buffer, 0, buffer.Length); if (read > 0) + { ms.Write(buffer, 0, read); + } else + { return ms.ToArray(); + } } } } -#endif // FEATURE_TPL } -} \ No newline at end of file +} diff --git a/src/Renci.SshNet.Tests/Classes/ForwardedPortLocalTest_Start_PortNeverStarted.cs b/src/Renci.SshNet.Tests/Classes/ForwardedPortLocalTest_Start_PortNeverStarted.cs index 6bb32b280..c286bd88f 100644 --- a/src/Renci.SshNet.Tests/Classes/ForwardedPortLocalTest_Start_PortNeverStarted.cs +++ b/src/Renci.SshNet.Tests/Classes/ForwardedPortLocalTest_Start_PortNeverStarted.cs @@ -51,9 +51,12 @@ protected void Arrange() _sessionMock = new Mock(MockBehavior.Strict); _channelMock = new Mock(MockBehavior.Strict); - _connectionInfoMock.Setup(p => p.Timeout).Returns(TimeSpan.FromSeconds(15)); - _sessionMock.Setup(p => p.IsConnected).Returns(true); - _sessionMock.Setup(p => p.ConnectionInfo).Returns(_connectionInfoMock.Object); + _ = _connectionInfoMock.Setup(p => p.Timeout) + .Returns(TimeSpan.FromSeconds(15)); + _ = _sessionMock.Setup(p => p.IsConnected) + .Returns(true); + _ = _sessionMock.Setup(p => p.ConnectionInfo) + .Returns(_connectionInfoMock.Object); _forwardedPort = new ForwardedPortLocal(_localEndpoint.Address.ToString(), (uint) _localEndpoint.Port, _remoteEndpoint.Address.ToString(), (uint) _remoteEndpoint.Port); @@ -78,14 +81,19 @@ public void ForwardedPortShouldAcceptNewConnections() { Socket handlerSocket = null; - _sessionMock.Setup(p => p.CreateChannelDirectTcpip()).Returns(_channelMock.Object); - _channelMock.Setup(p => p.Open(_forwardedPort.Host, _forwardedPort.Port, _forwardedPort, It.IsAny())).Callback((address, port, forwardedPort, socket) => handlerSocket = socket); - _channelMock.Setup(p => p.Bind()).Callback(() => - { - if (handlerSocket != null && handlerSocket.Connected) - handlerSocket.Shutdown(SocketShutdown.Both); - }); - _channelMock.Setup(p => p.Dispose()); + _ = _sessionMock.Setup(p => p.CreateChannelDirectTcpip()) + .Returns(_channelMock.Object); + _ = _channelMock.Setup(p => p.Open(_forwardedPort.Host, _forwardedPort.Port, _forwardedPort, It.IsAny())) + .Callback((address, port, forwardedPort, socket) => handlerSocket = socket); + _ = _channelMock.Setup(p => p.Bind()) + .Callback(() => + { + if (handlerSocket != null && handlerSocket.Connected) + { + handlerSocket.Shutdown(SocketShutdown.Both); + } + }); + _ = _channelMock.Setup(p => p.Dispose()); using (var client = new Socket(_localEndpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp)) { diff --git a/src/Renci.SshNet.Tests/Classes/ForwardedPortLocalTest_Start_PortStarted.cs b/src/Renci.SshNet.Tests/Classes/ForwardedPortLocalTest_Start_PortStarted.cs index 5980aad96..e9e07e393 100644 --- a/src/Renci.SshNet.Tests/Classes/ForwardedPortLocalTest_Start_PortStarted.cs +++ b/src/Renci.SshNet.Tests/Classes/ForwardedPortLocalTest_Start_PortStarted.cs @@ -2,8 +2,11 @@ using System.Collections.Generic; using System.Net; using System.Net.Sockets; + using Microsoft.VisualStudio.TestTools.UnitTesting; + using Moq; + using Renci.SshNet.Channels; using Renci.SshNet.Common; @@ -45,16 +48,18 @@ protected void Arrange() _closingRegister = new List(); _exceptionRegister = new List(); _localEndpoint = new IPEndPoint(IPAddress.Loopback, 8122); - _remoteEndpoint = new IPEndPoint(IPAddress.Parse("193.168.1.5"), - random.Next(IPEndPoint.MinPort, IPEndPoint.MaxPort)); + _remoteEndpoint = new IPEndPoint(IPAddress.Parse("193.168.1.5"), random.Next(IPEndPoint.MinPort, IPEndPoint.MaxPort)); _connectionInfoMock = new Mock(MockBehavior.Strict); _sessionMock = new Mock(MockBehavior.Strict); _channelMock = new Mock(MockBehavior.Strict); - _connectionInfoMock.Setup(p => p.Timeout).Returns(TimeSpan.FromSeconds(15)); - _sessionMock.Setup(p => p.IsConnected).Returns(true); - _sessionMock.Setup(p => p.ConnectionInfo).Returns(_connectionInfoMock.Object); + _ = _connectionInfoMock.Setup(p => p.Timeout) + .Returns(TimeSpan.FromSeconds(15)); + _ = _sessionMock.Setup(p => p.IsConnected) + .Returns(true); + _ = _sessionMock.Setup(p => p.ConnectionInfo) + .Returns(_connectionInfoMock.Object); _forwardedPort = new ForwardedPortLocal(_localEndpoint.Address.ToString(), (uint)_localEndpoint.Port, _remoteEndpoint.Address.ToString(), (uint)_remoteEndpoint.Port); @@ -95,14 +100,19 @@ public void ForwardedPortShouldAcceptNewConnections() { Socket handlerSocket = null; - _sessionMock.Setup(p => p.CreateChannelDirectTcpip()).Returns(_channelMock.Object); - _channelMock.Setup(p => p.Open(_forwardedPort.Host, _forwardedPort.Port, _forwardedPort, It.IsAny())).Callback((address, port, forwardedPort, socket) => handlerSocket = socket); - _channelMock.Setup(p => p.Bind()).Callback(() => - { - if (handlerSocket != null && handlerSocket.Connected) - handlerSocket.Shutdown(SocketShutdown.Both); - }); - _channelMock.Setup(p => p.Dispose()); + _ = _sessionMock.Setup(p => p.CreateChannelDirectTcpip()) + .Returns(_channelMock.Object); + _ = _channelMock.Setup(p => p.Open(_forwardedPort.Host, _forwardedPort.Port, _forwardedPort, It.IsAny())) + .Callback((address, port, forwardedPort, socket) => handlerSocket = socket); + _ = _channelMock.Setup(p => p.Bind()) + .Callback(() => + { + if (handlerSocket != null && handlerSocket.Connected) + { + handlerSocket.Shutdown(SocketShutdown.Both); + } + }); + _ = _channelMock.Setup(p => p.Dispose()); using (var client = new Socket(_localEndpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp)) { diff --git a/src/Renci.SshNet.Tests/Classes/ForwardedPortLocalTest_Start_PortStopped.cs b/src/Renci.SshNet.Tests/Classes/ForwardedPortLocalTest_Start_PortStopped.cs index 9889af6aa..7998ea99f 100644 --- a/src/Renci.SshNet.Tests/Classes/ForwardedPortLocalTest_Start_PortStopped.cs +++ b/src/Renci.SshNet.Tests/Classes/ForwardedPortLocalTest_Start_PortStopped.cs @@ -2,8 +2,11 @@ using System.Collections.Generic; using System.Net; using System.Net.Sockets; + using Microsoft.VisualStudio.TestTools.UnitTesting; + using Moq; + using Renci.SshNet.Channels; using Renci.SshNet.Common; @@ -45,18 +48,22 @@ protected void Arrange() _exceptionRegister = new List(); _localEndpoint = new IPEndPoint(IPAddress.Loopback, 8122); _remoteEndpoint = new IPEndPoint(IPAddress.Parse("193.168.1.5"), - random.Next(IPEndPoint.MinPort, IPEndPoint.MaxPort)); + random.Next(IPEndPoint.MinPort, IPEndPoint.MaxPort)); _connectionInfoMock = new Mock(MockBehavior.Strict); _sessionMock = new Mock(MockBehavior.Strict); _channelMock = new Mock(MockBehavior.Strict); - _connectionInfoMock.Setup(p => p.Timeout).Returns(TimeSpan.FromSeconds(15)); - _sessionMock.Setup(p => p.IsConnected).Returns(true); - _sessionMock.Setup(p => p.ConnectionInfo).Returns(_connectionInfoMock.Object); + _ = _connectionInfoMock.Setup(p => p.Timeout) + .Returns(TimeSpan.FromSeconds(15)); + _ = _sessionMock.Setup(p => p.IsConnected) + .Returns(true); + _ = _sessionMock.Setup(p => p.ConnectionInfo) + .Returns(_connectionInfoMock.Object); - _forwardedPort = new ForwardedPortLocal(_localEndpoint.Address.ToString(), (uint)_localEndpoint.Port, - _remoteEndpoint.Address.ToString(), (uint)_remoteEndpoint.Port); + _forwardedPort = new ForwardedPortLocal(_localEndpoint.Address.ToString(), + (uint) _localEndpoint.Port, + _remoteEndpoint.Address.ToString(), (uint) _remoteEndpoint.Port); _forwardedPort.Closing += (sender, args) => _closingRegister.Add(args); _forwardedPort.Exception += (sender, args) => _exceptionRegister.Add(args); _forwardedPort.Session = _sessionMock.Object; @@ -82,14 +89,19 @@ public void ForwardedPortShouldAcceptNewConnections() { Socket handlerSocket = null; - _sessionMock.Setup(p => p.CreateChannelDirectTcpip()).Returns(_channelMock.Object); - _channelMock.Setup(p => p.Open(_forwardedPort.Host, _forwardedPort.Port, _forwardedPort, It.IsAny())).Callback((address, port, forwardedPort, socket) => handlerSocket = socket); - _channelMock.Setup(p => p.Bind()).Callback(() => - { - if (handlerSocket != null && handlerSocket.Connected) - handlerSocket.Shutdown(SocketShutdown.Both); - }); - _channelMock.Setup(p => p.Dispose()); + _ = _sessionMock.Setup(p => p.CreateChannelDirectTcpip()) + .Returns(_channelMock.Object); + _ = _channelMock.Setup(p => p.Open(_forwardedPort.Host, _forwardedPort.Port, _forwardedPort, It.IsAny())) + .Callback((address, port, forwardedPort, socket) => handlerSocket = socket); + _ = _channelMock.Setup(p => p.Bind()) + .Callback(() => + { + if (handlerSocket != null && handlerSocket.Connected) + { + handlerSocket.Shutdown(SocketShutdown.Both); + } + }); + _ = _channelMock.Setup(p => p.Dispose()); using (var client = new Socket(_localEndpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp)) { diff --git a/src/Renci.SshNet.Tests/Classes/ForwardedPortRemoteTest.cs b/src/Renci.SshNet.Tests/Classes/ForwardedPortRemoteTest.cs index 3a99441d1..5f0777190 100644 --- a/src/Renci.SshNet.Tests/Classes/ForwardedPortRemoteTest.cs +++ b/src/Renci.SshNet.Tests/Classes/ForwardedPortRemoteTest.cs @@ -1,10 +1,12 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using System; +using System.Net; +using System.Threading; + +using Microsoft.VisualStudio.TestTools.UnitTesting; + using Renci.SshNet.Common; using Renci.SshNet.Tests.Common; using Renci.SshNet.Tests.Properties; -using System; -using System.Net; -using System.Threading; namespace Renci.SshNet.Tests.Classes { @@ -23,7 +25,7 @@ public void Test_AddForwardedPort_Remote_Hosts_Are_Null() using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD)) { client.Connect(); - var port1 = new ForwardedPortRemote((string)null, 8080, (string)null, 80); + var port1 = new ForwardedPortRemote(boundHost: null, 8080, host: null, 80); client.AddForwardedPort(port1); client.Disconnect(); } @@ -80,9 +82,9 @@ public void Test_ForwardedPortRemote() public void StopTest() { uint boundPort = 0; // TODO: Initialize to an appropriate value - string host = string.Empty; // TODO: Initialize to an appropriate value + var host = string.Empty; // TODO: Initialize to an appropriate value uint port = 0; // TODO: Initialize to an appropriate value - ForwardedPortRemote target = new ForwardedPortRemote(boundPort, host, port); // TODO: Initialize to an appropriate value + var target = new ForwardedPortRemote(boundPort, host, port); // TODO: Initialize to an appropriate value target.Stop(); Assert.Inconclusive("A method that does not return a value cannot be verified."); } @@ -91,7 +93,7 @@ public void StopTest() public void Start_NotAddedToClient() { const int boundPort = 80; - string host = string.Empty; + var host = string.Empty; const uint port = 22; var target = new ForwardedPortRemote(boundPort, host, port); @@ -115,9 +117,9 @@ public void Start_NotAddedToClient() public void DisposeTest() { uint boundPort = 0; // TODO: Initialize to an appropriate value - string host = string.Empty; // TODO: Initialize to an appropriate value + var host = string.Empty; // TODO: Initialize to an appropriate value uint port = 0; // TODO: Initialize to an appropriate value - ForwardedPortRemote target = new ForwardedPortRemote(boundPort, host, port); // TODO: Initialize to an appropriate value + var target = new ForwardedPortRemote(boundPort, host, port); // TODO: Initialize to an appropriate value target.Dispose(); Assert.Inconclusive("A method that does not return a value cannot be verified."); } @@ -129,11 +131,11 @@ public void DisposeTest() [Ignore] // placeholder public void ForwardedPortRemoteConstructorTest() { - string boundHost = string.Empty; // TODO: Initialize to an appropriate value + var boundHost = string.Empty; // TODO: Initialize to an appropriate value uint boundPort = 0; // TODO: Initialize to an appropriate value - string host = string.Empty; // TODO: Initialize to an appropriate value + var host = string.Empty; // TODO: Initialize to an appropriate value uint port = 0; // TODO: Initialize to an appropriate value - ForwardedPortRemote target = new ForwardedPortRemote(boundHost, boundPort, host, port); + var target = new ForwardedPortRemote(boundHost, boundPort, host, port); Assert.Inconclusive("TODO: Implement code to verify target"); } @@ -145,9 +147,9 @@ public void ForwardedPortRemoteConstructorTest() public void ForwardedPortRemoteConstructorTest1() { uint boundPort = 0; // TODO: Initialize to an appropriate value - string host = string.Empty; // TODO: Initialize to an appropriate value + var host = string.Empty; // TODO: Initialize to an appropriate value uint port = 0; // TODO: Initialize to an appropriate value - ForwardedPortRemote target = new ForwardedPortRemote(boundPort, host, port); + var target = new ForwardedPortRemote(boundPort, host, port); Assert.Inconclusive("TODO: Implement code to verify target"); } @@ -192,4 +194,4 @@ public void Test_PortForwarding_Remote() } #endif // FEATURE_TPL } -} \ No newline at end of file +} diff --git a/src/Renci.SshNet.Tests/Classes/ForwardedPortRemoteTest_Start_SessionNotConnected.cs b/src/Renci.SshNet.Tests/Classes/ForwardedPortRemoteTest_Start_SessionNotConnected.cs index fc56157be..af38f057a 100644 --- a/src/Renci.SshNet.Tests/Classes/ForwardedPortRemoteTest_Start_SessionNotConnected.cs +++ b/src/Renci.SshNet.Tests/Classes/ForwardedPortRemoteTest_Start_SessionNotConnected.cs @@ -2,9 +2,11 @@ using System.Collections.Generic; using System.Globalization; using System.Net; -using System.Net.Sockets; + using Microsoft.VisualStudio.TestTools.UnitTesting; + using Moq; + using Renci.SshNet.Channels; using Renci.SshNet.Common; using Renci.SshNet.Messages.Connection; @@ -35,8 +37,11 @@ public void Cleanup() { if (_forwardedPort != null) { - _sessionMock.Setup(p => p.ConnectionInfo).Returns(_connectionInfoMock.Object); - _connectionInfoMock.Setup(p => p.Timeout).Returns(TimeSpan.FromSeconds(1)); + _ = _sessionMock.Setup(p => p.ConnectionInfo) + .Returns(_connectionInfoMock.Object); + _ = _connectionInfoMock.Setup(p => p.Timeout) + .Returns(TimeSpan.FromSeconds(1)); + _forwardedPort.Dispose(); _forwardedPort = null; } @@ -53,7 +58,8 @@ protected void Arrange() _sessionMock = new Mock(MockBehavior.Strict); _connectionInfoMock = new Mock(MockBehavior.Strict); - _sessionMock.Setup(p => p.IsConnected).Returns(false); + _ = _sessionMock.Setup(p => p.IsConnected) + .Returns(false); _forwardedPort = new ForwardedPortRemote(_bindEndpoint.Address, (uint)_bindEndpoint.Port, _remoteEndpoint.Address, (uint)_remoteEndpoint.Port); _forwardedPort.Closing += (sender, args) => _closingRegister.Add(args); @@ -90,19 +96,17 @@ public void IsStartedShouldReturnFalse() [TestMethod] public void ForwardedPortShouldIgnoreReceivedSignalForNewConnection() { - var channelNumber = (uint)new Random().Next(1001, int.MaxValue); - var initialWindowSize = (uint)new Random().Next(0, int.MaxValue); - var maximumPacketSize = (uint)new Random().Next(0, int.MaxValue); + var channelNumber = (uint) new Random().Next(1001, int.MaxValue); + var initialWindowSize = (uint) new Random().Next(0, int.MaxValue); + var maximumPacketSize = (uint) new Random().Next(0, int.MaxValue); var originatorAddress = new Random().Next().ToString(CultureInfo.InvariantCulture); - var originatorPort = (uint)new Random().Next(0, int.MaxValue); + var originatorPort = (uint) new Random().Next(0, int.MaxValue); var channelMock = new Mock(MockBehavior.Strict); - _sessionMock.Setup( - p => - p.CreateChannelForwardedTcpip(channelNumber, initialWindowSize, maximumPacketSize)).Returns(channelMock.Object); - + _ = _sessionMock.Setup(p => p.CreateChannelForwardedTcpip(channelNumber, initialWindowSize, maximumPacketSize)).Returns(channelMock.Object); + _sessionMock.Raise(p => p.ChannelOpenReceived += null, - new MessageEventArgs(new ChannelOpenMessage(channelNumber, initialWindowSize, + new MessageEventArgs(new ChannelOpenMessage(channelNumber, initialWindowSize, maximumPacketSize, new ForwardedTcpipChannelInfo(_forwardedPort.BoundHost, _forwardedPort.BoundPort, originatorAddress, originatorPort)))); diff --git a/src/Renci.SshNet.Tests/Classes/ForwardedPortRemoteTest_Start_SessionNull.cs b/src/Renci.SshNet.Tests/Classes/ForwardedPortRemoteTest_Start_SessionNull.cs index 68931a0a1..9cd3a3046 100644 --- a/src/Renci.SshNet.Tests/Classes/ForwardedPortRemoteTest_Start_SessionNull.cs +++ b/src/Renci.SshNet.Tests/Classes/ForwardedPortRemoteTest_Start_SessionNull.cs @@ -1,13 +1,10 @@ using System; using System.Collections.Generic; -using System.Globalization; using System.Net; -using System.Net.Sockets; + using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; -using Renci.SshNet.Channels; + using Renci.SshNet.Common; -using Renci.SshNet.Messages.Connection; namespace Renci.SshNet.Tests.Classes { diff --git a/src/Renci.SshNet.Tests/Classes/MessageEventArgsTest.cs b/src/Renci.SshNet.Tests/Classes/MessageEventArgsTest.cs index 051fd6c34..da6ab8517 100644 --- a/src/Renci.SshNet.Tests/Classes/MessageEventArgsTest.cs +++ b/src/Renci.SshNet.Tests/Classes/MessageEventArgsTest.cs @@ -14,8 +14,8 @@ public class MessageEventArgsTest : TestBase /// public void MessageEventArgsConstructorTestHelper() { - T message = default(T); // TODO: Initialize to an appropriate value - MessageEventArgs target = new MessageEventArgs(message); + T message = default; // TODO: Initialize to an appropriate value + var target = new MessageEventArgs(message); Assert.Inconclusive("TODO: Implement code to verify target"); } @@ -26,4 +26,4 @@ public void MessageEventArgsConstructorTest() MessageEventArgsConstructorTestHelper(); } } -} \ No newline at end of file +} diff --git a/src/Renci.SshNet.Tests/Classes/Messages/Authentication/FailureMessageTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/Authentication/FailureMessageTest.cs index 9f0169f02..979b1d750 100644 --- a/src/Renci.SshNet.Tests/Classes/Messages/Authentication/FailureMessageTest.cs +++ b/src/Renci.SshNet.Tests/Classes/Messages/Authentication/FailureMessageTest.cs @@ -1,6 +1,6 @@ -using Renci.SshNet.Messages.Authentication; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using System; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +using Renci.SshNet.Messages.Authentication; using Renci.SshNet.Tests.Common; namespace Renci.SshNet.Tests.Messages.Authentication @@ -19,7 +19,7 @@ public class FailureMessageTest : TestBase [Ignore] // placeholder public void FailureMessageConstructorTest() { - FailureMessage target = new FailureMessage(); + var target = new FailureMessage(); Assert.Inconclusive("TODO: Implement code to verify target"); } @@ -30,7 +30,7 @@ public void FailureMessageConstructorTest() [Ignore] // placeholder public void AllowedAuthenticationsTest() { - FailureMessage target = new FailureMessage(); // TODO: Initialize to an appropriate value + var target = new FailureMessage(); // TODO: Initialize to an appropriate value string[] expected = null; // TODO: Initialize to an appropriate value string[] actual; target.AllowedAuthentications = expected; diff --git a/src/Renci.SshNet.Tests/Classes/Messages/Authentication/RequestMessagePublicKeyTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/Authentication/RequestMessagePublicKeyTest.cs index f09aa4a4c..fb4e36af1 100644 --- a/src/Renci.SshNet.Tests/Classes/Messages/Authentication/RequestMessagePublicKeyTest.cs +++ b/src/Renci.SshNet.Tests/Classes/Messages/Authentication/RequestMessagePublicKeyTest.cs @@ -1,7 +1,7 @@ -using Renci.SshNet.Messages.Authentication; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using System; +using Microsoft.VisualStudio.TestTools.UnitTesting; + using Renci.SshNet.Messages; +using Renci.SshNet.Messages.Authentication; using Renci.SshNet.Tests.Common; namespace Renci.SshNet.Tests.Messages.Authentication @@ -20,11 +20,11 @@ public class RequestMessagePublicKeyTest : TestBase [Ignore] // placeholder public void RequestMessagePublicKeyConstructorTest() { - ServiceName serviceName = new ServiceName(); // TODO: Initialize to an appropriate value - string username = string.Empty; // TODO: Initialize to an appropriate value - string keyAlgorithmName = string.Empty; // TODO: Initialize to an appropriate value + var serviceName = new ServiceName(); // TODO: Initialize to an appropriate value + var username = string.Empty; // TODO: Initialize to an appropriate value + var keyAlgorithmName = string.Empty; // TODO: Initialize to an appropriate value byte[] keyData = null; // TODO: Initialize to an appropriate value - RequestMessagePublicKey target = new RequestMessagePublicKey(serviceName, username, keyAlgorithmName, keyData); + var target = new RequestMessagePublicKey(serviceName, username, keyAlgorithmName, keyData); Assert.Inconclusive("TODO: Implement code to verify target"); } @@ -35,12 +35,12 @@ public void RequestMessagePublicKeyConstructorTest() [Ignore] // placeholder public void RequestMessagePublicKeyConstructorTest1() { - ServiceName serviceName = new ServiceName(); // TODO: Initialize to an appropriate value - string username = string.Empty; // TODO: Initialize to an appropriate value - string keyAlgorithmName = string.Empty; // TODO: Initialize to an appropriate value + var serviceName = new ServiceName(); // TODO: Initialize to an appropriate value + var username = string.Empty; // TODO: Initialize to an appropriate value + var keyAlgorithmName = string.Empty; // TODO: Initialize to an appropriate value byte[] keyData = null; // TODO: Initialize to an appropriate value byte[] signature = null; // TODO: Initialize to an appropriate value - RequestMessagePublicKey target = new RequestMessagePublicKey(serviceName, username, keyAlgorithmName, keyData, signature); + var target = new RequestMessagePublicKey(serviceName, username, keyAlgorithmName, keyData, signature); Assert.Inconclusive("TODO: Implement code to verify target"); } @@ -51,13 +51,12 @@ public void RequestMessagePublicKeyConstructorTest1() [Ignore] // placeholder public void MethodNameTest() { - ServiceName serviceName = new ServiceName(); // TODO: Initialize to an appropriate value - string username = string.Empty; // TODO: Initialize to an appropriate value - string keyAlgorithmName = string.Empty; // TODO: Initialize to an appropriate value + var serviceName = new ServiceName(); // TODO: Initialize to an appropriate value + var username = string.Empty; // TODO: Initialize to an appropriate value + var keyAlgorithmName = string.Empty; // TODO: Initialize to an appropriate value byte[] keyData = null; // TODO: Initialize to an appropriate value - RequestMessagePublicKey target = new RequestMessagePublicKey(serviceName, username, keyAlgorithmName, keyData); // TODO: Initialize to an appropriate value - string actual; - actual = target.MethodName; + var target = new RequestMessagePublicKey(serviceName, username, keyAlgorithmName, keyData); // TODO: Initialize to an appropriate value + var actual = target.MethodName; Assert.Inconclusive("Verify the correctness of this test method."); } @@ -68,11 +67,11 @@ public void MethodNameTest() [Ignore] // placeholder public void SignatureTest() { - ServiceName serviceName = new ServiceName(); // TODO: Initialize to an appropriate value - string username = string.Empty; // TODO: Initialize to an appropriate value - string keyAlgorithmName = string.Empty; // TODO: Initialize to an appropriate value + var serviceName = new ServiceName(); // TODO: Initialize to an appropriate value + var username = string.Empty; // TODO: Initialize to an appropriate value + var keyAlgorithmName = string.Empty; // TODO: Initialize to an appropriate value byte[] keyData = null; // TODO: Initialize to an appropriate value - RequestMessagePublicKey target = new RequestMessagePublicKey(serviceName, username, keyAlgorithmName, keyData); // TODO: Initialize to an appropriate value + var target = new RequestMessagePublicKey(serviceName, username, keyAlgorithmName, keyData); // TODO: Initialize to an appropriate value byte[] expected = null; // TODO: Initialize to an appropriate value target.Signature = expected; var actual = target.Signature; diff --git a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelCloseMessageTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelCloseMessageTest.cs index 9d3ebc3c0..995981a60 100644 --- a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelCloseMessageTest.cs +++ b/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelCloseMessageTest.cs @@ -1,6 +1,5 @@ using Renci.SshNet.Messages.Connection; using Microsoft.VisualStudio.TestTools.UnitTesting; -using System; using Renci.SshNet.Tests.Common; namespace Renci.SshNet.Tests.Classes.Messages.Connection @@ -19,7 +18,7 @@ public class ChannelCloseMessageTest : TestBase [Ignore] // placeholder public void ChannelCloseMessageConstructorTest() { - ChannelCloseMessage target = new ChannelCloseMessage(); + var target = new ChannelCloseMessage(); Assert.Inconclusive("TODO: Implement code to verify target"); } @@ -31,7 +30,7 @@ public void ChannelCloseMessageConstructorTest() public void ChannelCloseMessageConstructorTest1() { uint localChannelNumber = 0; // TODO: Initialize to an appropriate value - ChannelCloseMessage target = new ChannelCloseMessage(localChannelNumber); + var target = new ChannelCloseMessage(localChannelNumber); Assert.Inconclusive("TODO: Implement code to verify target"); } } diff --git a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelEofMessageTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelEofMessageTest.cs index a302fb6e8..ad2becd89 100644 --- a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelEofMessageTest.cs +++ b/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelEofMessageTest.cs @@ -1,6 +1,5 @@ using Renci.SshNet.Messages.Connection; using Microsoft.VisualStudio.TestTools.UnitTesting; -using System; using Renci.SshNet.Tests.Common; namespace Renci.SshNet.Tests.Classes.Messages.Connection @@ -19,7 +18,7 @@ public class ChannelEofMessageTest : TestBase [Ignore] // placeholder public void ChannelEofMessageConstructorTest() { - ChannelEofMessage target = new ChannelEofMessage(); + var target = new ChannelEofMessage(); Assert.Inconclusive("TODO: Implement code to verify target"); } @@ -31,7 +30,7 @@ public void ChannelEofMessageConstructorTest() public void ChannelEofMessageConstructorTest1() { uint localChannelNumber = 0; // TODO: Initialize to an appropriate value - ChannelEofMessage target = new ChannelEofMessage(localChannelNumber); + var target = new ChannelEofMessage(localChannelNumber); Assert.Inconclusive("TODO: Implement code to verify target"); } } diff --git a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelExtendedDataMessageTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelExtendedDataMessageTest.cs index 469908ea3..65e3dbcc7 100644 --- a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelExtendedDataMessageTest.cs +++ b/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelExtendedDataMessageTest.cs @@ -1,6 +1,6 @@ -using Renci.SshNet.Messages.Connection; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using System; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +using Renci.SshNet.Messages.Connection; using Renci.SshNet.Tests.Common; namespace Renci.SshNet.Tests.Classes.Messages.Connection @@ -19,7 +19,7 @@ public class ChannelExtendedDataMessageTest : TestBase [Ignore] // placeholder public void ChannelExtendedDataMessageConstructorTest() { - ChannelExtendedDataMessage target = new ChannelExtendedDataMessage(); + var target = new ChannelExtendedDataMessage(); Assert.Inconclusive("TODO: Implement code to verify target"); } diff --git a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelFailureMessageTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelFailureMessageTest.cs index ef1fe76c4..070df2a68 100644 --- a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelFailureMessageTest.cs +++ b/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelFailureMessageTest.cs @@ -1,6 +1,6 @@ -using Renci.SshNet.Messages.Connection; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using System; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +using Renci.SshNet.Messages.Connection; using Renci.SshNet.Tests.Common; namespace Renci.SshNet.Tests.Classes.Messages.Connection @@ -19,7 +19,7 @@ public class ChannelFailureMessageTest : TestBase [Ignore] // placeholder public void ChannelFailureMessageConstructorTest() { - ChannelFailureMessage target = new ChannelFailureMessage(); + var target = new ChannelFailureMessage(); Assert.Inconclusive("TODO: Implement code to verify target"); } @@ -31,7 +31,7 @@ public void ChannelFailureMessageConstructorTest() public void ChannelFailureMessageConstructorTest1() { uint localChannelNumber = 0; // TODO: Initialize to an appropriate value - ChannelFailureMessage target = new ChannelFailureMessage(localChannelNumber); + var target = new ChannelFailureMessage(localChannelNumber); Assert.Inconclusive("TODO: Implement code to verify target"); } } diff --git a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelMessageTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelMessageTest.cs index baa4a7fca..53c56cf7f 100644 --- a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelMessageTest.cs +++ b/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelMessageTest.cs @@ -1,6 +1,6 @@ -using Renci.SshNet.Messages.Connection; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using System; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +using Renci.SshNet.Messages.Connection; using Renci.SshNet.Tests.Common; namespace Renci.SshNet.Tests.Classes.Messages.Connection @@ -26,10 +26,9 @@ internal virtual ChannelMessage CreateChannelMessage() [TestMethod()] public void ToStringTest() { - ChannelMessage target = CreateChannelMessage(); // TODO: Initialize to an appropriate value - string expected = string.Empty; // TODO: Initialize to an appropriate value - string actual; - actual = target.ToString(); + var target = CreateChannelMessage(); // TODO: Initialize to an appropriate value + var expected = string.Empty; // TODO: Initialize to an appropriate value + var actual = target.ToString(); Assert.AreEqual(expected, actual); Assert.Inconclusive("Verify the correctness of this test method."); } diff --git a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelOpen/ChannelOpenMessageTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelOpen/ChannelOpenMessageTest.cs index 368f55319..1a40d8609 100644 --- a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelOpen/ChannelOpenMessageTest.cs +++ b/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelOpen/ChannelOpenMessageTest.cs @@ -28,9 +28,9 @@ public void DefaultConstructor() Assert.IsNull(target.ChannelType); Assert.IsNull(target.Info); - Assert.AreEqual(default(uint), target.InitialWindowSize); - Assert.AreEqual(default(uint), target.LocalChannelNumber); - Assert.AreEqual(default(uint), target.MaximumPacketSize); + Assert.AreEqual(default, target.InitialWindowSize); + Assert.AreEqual(default, target.LocalChannelNumber); + Assert.AreEqual(default, target.MaximumPacketSize); } [TestMethod] diff --git a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelOpenConfirmationMessageTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelOpenConfirmationMessageTest.cs index ce5abb61a..3ad44b48f 100644 --- a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelOpenConfirmationMessageTest.cs +++ b/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelOpenConfirmationMessageTest.cs @@ -1,6 +1,6 @@ -using Renci.SshNet.Messages.Connection; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using System; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +using Renci.SshNet.Messages.Connection; using Renci.SshNet.Tests.Common; namespace Renci.SshNet.Tests.Classes.Messages.Connection @@ -19,7 +19,7 @@ public class ChannelOpenConfirmationMessageTest : TestBase [Ignore] // placeholder public void ChannelOpenConfirmationMessageConstructorTest() { - ChannelOpenConfirmationMessage target = new ChannelOpenConfirmationMessage(); + var target = new ChannelOpenConfirmationMessage(); Assert.Inconclusive("TODO: Implement code to verify target"); } @@ -34,7 +34,7 @@ public void ChannelOpenConfirmationMessageConstructorTest1() uint initialWindowSize = 0; // TODO: Initialize to an appropriate value uint maximumPacketSize = 0; // TODO: Initialize to an appropriate value uint remoteChannelNumber = 0; // TODO: Initialize to an appropriate value - ChannelOpenConfirmationMessage target = new ChannelOpenConfirmationMessage(localChannelNumber, initialWindowSize, maximumPacketSize, remoteChannelNumber); + var target = new ChannelOpenConfirmationMessage(localChannelNumber, initialWindowSize, maximumPacketSize, remoteChannelNumber); Assert.Inconclusive("TODO: Implement code to verify target"); } } diff --git a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelOpenFailureMessageTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelOpenFailureMessageTest.cs index 3992ca491..848f81eda 100644 --- a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelOpenFailureMessageTest.cs +++ b/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelOpenFailureMessageTest.cs @@ -1,6 +1,6 @@ -using Renci.SshNet.Messages.Connection; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using System; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +using Renci.SshNet.Messages.Connection; using Renci.SshNet.Tests.Common; namespace Renci.SshNet.Tests.Classes.Messages.Connection @@ -19,7 +19,7 @@ public class ChannelOpenFailureMessageTest : TestBase [Ignore] // placeholder public void ChannelOpenFailureMessageConstructorTest() { - ChannelOpenFailureMessage target = new ChannelOpenFailureMessage(); + var target = new ChannelOpenFailureMessage(); Assert.Inconclusive("TODO: Implement code to verify target"); } @@ -31,9 +31,9 @@ public void ChannelOpenFailureMessageConstructorTest() public void ChannelOpenFailureMessageConstructorTest1() { uint localChannelNumber = 0; // TODO: Initialize to an appropriate value - string description = string.Empty; // TODO: Initialize to an appropriate value + var description = string.Empty; // TODO: Initialize to an appropriate value uint reasonCode = 0; // TODO: Initialize to an appropriate value - ChannelOpenFailureMessage target = new ChannelOpenFailureMessage(localChannelNumber, description, reasonCode); + var target = new ChannelOpenFailureMessage(localChannelNumber, description, reasonCode); Assert.Inconclusive("TODO: Implement code to verify target"); } } diff --git a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelOpenInfoTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelOpenInfoTest.cs index 845cc8c07..a28e17ed8 100644 --- a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelOpenInfoTest.cs +++ b/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelOpenInfoTest.cs @@ -1,6 +1,6 @@ -using Renci.SshNet.Messages.Connection; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using System; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +using Renci.SshNet.Messages.Connection; using Renci.SshNet.Tests.Common; namespace Renci.SshNet.Tests.Classes.Messages.Connection @@ -26,9 +26,8 @@ internal virtual ChannelOpenInfo CreateChannelOpenInfo() [TestMethod()] public void ChannelTypeTest() { - ChannelOpenInfo target = CreateChannelOpenInfo(); // TODO: Initialize to an appropriate value - string actual; - actual = target.ChannelType; + var target = CreateChannelOpenInfo(); // TODO: Initialize to an appropriate value + var actual = target.ChannelType; Assert.Inconclusive("Verify the correctness of this test method."); } } diff --git a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelRequest/EndOfWriteRequestInfoTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelRequest/EndOfWriteRequestInfoTest.cs index 68ffa7af7..0573bade7 100644 --- a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelRequest/EndOfWriteRequestInfoTest.cs +++ b/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelRequest/EndOfWriteRequestInfoTest.cs @@ -1,6 +1,6 @@ -using Renci.SshNet.Messages.Connection; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using System; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +using Renci.SshNet.Messages.Connection; using Renci.SshNet.Tests.Common; namespace Renci.SshNet.Tests.Classes.Messages.Connection @@ -19,7 +19,7 @@ public class EndOfWriteRequestInfoTest : TestBase [Ignore] // placeholder public void EndOfWriteRequestInfoConstructorTest() { - EndOfWriteRequestInfo target = new EndOfWriteRequestInfo(); + var target = new EndOfWriteRequestInfo(); Assert.Inconclusive("TODO: Implement code to verify target"); } @@ -30,9 +30,9 @@ public void EndOfWriteRequestInfoConstructorTest() [Ignore] // placeholder public void RequestNameTest() { - EndOfWriteRequestInfo target = new EndOfWriteRequestInfo(); // TODO: Initialize to an appropriate value - string actual; - actual = target.RequestName; + var target = new EndOfWriteRequestInfo(); // TODO: Initialize to an appropriate value + + var actual = target.RequestName; Assert.Inconclusive("Verify the correctness of this test method."); } } diff --git a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelRequest/KeepAliveRequestInfoTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelRequest/KeepAliveRequestInfoTest.cs index 515a723a5..77b8cc927 100644 --- a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelRequest/KeepAliveRequestInfoTest.cs +++ b/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelRequest/KeepAliveRequestInfoTest.cs @@ -1,6 +1,6 @@ -using Renci.SshNet.Messages.Connection; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using System; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +using Renci.SshNet.Messages.Connection; using Renci.SshNet.Tests.Common; namespace Renci.SshNet.Tests.Classes.Messages.Connection @@ -19,7 +19,7 @@ public class KeepAliveRequestInfoTest : TestBase [Ignore] // placeholder public void KeepAliveRequestInfoConstructorTest() { - KeepAliveRequestInfo target = new KeepAliveRequestInfo(); + var target = new KeepAliveRequestInfo(); Assert.Inconclusive("TODO: Implement code to verify target"); } @@ -30,9 +30,8 @@ public void KeepAliveRequestInfoConstructorTest() [Ignore] // placeholder public void RequestNameTest() { - KeepAliveRequestInfo target = new KeepAliveRequestInfo(); // TODO: Initialize to an appropriate value - string actual; - actual = target.RequestName; + var target = new KeepAliveRequestInfo(); // TODO: Initialize to an appropriate value + var actual = target.RequestName; Assert.Inconclusive("Verify the correctness of this test method."); } } diff --git a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelRequest/PseudoTerminalInfoTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelRequest/PseudoTerminalInfoTest.cs index b7e3e3234..fedbdb7fc 100644 --- a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelRequest/PseudoTerminalInfoTest.cs +++ b/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelRequest/PseudoTerminalInfoTest.cs @@ -55,7 +55,7 @@ public void GetBytes() expectedBytesLength += 4; // PixelWidth expectedBytesLength += 4; // PixelHeight expectedBytesLength += 4; // Length of "encoded terminal modes" - expectedBytesLength += _terminalModeValues.Count*(1 + 4) + 1; // encoded terminal modes + expectedBytesLength += (_terminalModeValues.Count * (1 + 4)) + 1; // encoded terminal modes Assert.AreEqual(expectedBytesLength, bytes.Length); @@ -67,7 +67,7 @@ public void GetBytes() Assert.AreEqual(_rows, sshDataStream.ReadUInt32()); Assert.AreEqual(_width, sshDataStream.ReadUInt32()); Assert.AreEqual(_height, sshDataStream.ReadUInt32()); - Assert.AreEqual((uint) (_terminalModeValues.Count * (1 + 4) + 1), sshDataStream.ReadUInt32()); + Assert.AreEqual((uint) ((_terminalModeValues.Count * (1 + 4)) + 1), sshDataStream.ReadUInt32()); Assert.AreEqual((int) TerminalModes.CS8, sshDataStream.ReadByte()); Assert.AreEqual(_terminalModeValues[TerminalModes.CS8], sshDataStream.ReadUInt32()); Assert.AreEqual((int) TerminalModes.ECHO, sshDataStream.ReadByte()); @@ -180,4 +180,4 @@ public void NameShouldReturnPtyReq() Assert.AreEqual("pty-req", PseudoTerminalRequestInfo.Name); } } -} \ No newline at end of file +} diff --git a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelSuccessMessageTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelSuccessMessageTest.cs index 6bfb5b0c2..68efa44c4 100644 --- a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelSuccessMessageTest.cs +++ b/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelSuccessMessageTest.cs @@ -1,6 +1,6 @@ -using Renci.SshNet.Messages.Connection; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using System; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +using Renci.SshNet.Messages.Connection; using Renci.SshNet.Tests.Common; namespace Renci.SshNet.Tests.Classes.Messages.Connection @@ -19,7 +19,7 @@ public class ChannelSuccessMessageTest : TestBase [Ignore] // placeholder public void ChannelSuccessMessageConstructorTest() { - ChannelSuccessMessage target = new ChannelSuccessMessage(); + var target = new ChannelSuccessMessage(); Assert.Inconclusive("TODO: Implement code to verify target"); } @@ -31,7 +31,7 @@ public void ChannelSuccessMessageConstructorTest() public void ChannelSuccessMessageConstructorTest1() { uint localChannelNumber = 0; // TODO: Initialize to an appropriate value - ChannelSuccessMessage target = new ChannelSuccessMessage(localChannelNumber); + var target = new ChannelSuccessMessage(localChannelNumber); Assert.Inconclusive("TODO: Implement code to verify target"); } } diff --git a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelWindowAdjustMessageTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelWindowAdjustMessageTest.cs index 131cdfda6..12d19a61c 100644 --- a/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelWindowAdjustMessageTest.cs +++ b/src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelWindowAdjustMessageTest.cs @@ -1,6 +1,6 @@ -using Renci.SshNet.Messages.Connection; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using System; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +using Renci.SshNet.Messages.Connection; using Renci.SshNet.Tests.Common; namespace Renci.SshNet.Tests.Classes.Messages.Connection diff --git a/src/Renci.SshNet.Tests/Classes/Messages/Connection/RequestInfoTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/Connection/RequestInfoTest.cs index fdf6d5348..f37ecc183 100644 --- a/src/Renci.SshNet.Tests/Classes/Messages/Connection/RequestInfoTest.cs +++ b/src/Renci.SshNet.Tests/Classes/Messages/Connection/RequestInfoTest.cs @@ -1,6 +1,6 @@ -using Renci.SshNet.Messages.Connection; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using System; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +using Renci.SshNet.Messages.Connection; using Renci.SshNet.Tests.Common; namespace Renci.SshNet.Tests.Classes.Messages.Connection @@ -26,9 +26,8 @@ internal virtual RequestInfo CreateRequestInfo() [TestMethod()] public void RequestNameTest() { - RequestInfo target = CreateRequestInfo(); // TODO: Initialize to an appropriate value - string actual; - actual = target.RequestName; + var target = CreateRequestInfo(); // TODO: Initialize to an appropriate value + var actual = target.RequestName; Assert.Inconclusive("Verify the correctness of this test method."); } } diff --git a/src/Renci.SshNet.Tests/Classes/Messages/Connection/RequestSuccessMessageTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/Connection/RequestSuccessMessageTest.cs index 55d7ec6db..fba922456 100644 --- a/src/Renci.SshNet.Tests/Classes/Messages/Connection/RequestSuccessMessageTest.cs +++ b/src/Renci.SshNet.Tests/Classes/Messages/Connection/RequestSuccessMessageTest.cs @@ -1,6 +1,6 @@ -using Renci.SshNet.Messages.Connection; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using System; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +using Renci.SshNet.Messages.Connection; using Renci.SshNet.Tests.Common; namespace Renci.SshNet.Tests.Classes.Messages.Connection @@ -19,7 +19,7 @@ public class RequestSuccessMessageTest : TestBase [Ignore] // placeholder public void RequestSuccessMessageConstructorTest() { - RequestSuccessMessage target = new RequestSuccessMessage(); + var target = new RequestSuccessMessage(); Assert.Inconclusive("TODO: Implement code to verify target"); } @@ -31,7 +31,7 @@ public void RequestSuccessMessageConstructorTest() public void RequestSuccessMessageConstructorTest1() { uint boundPort = 0; // TODO: Initialize to an appropriate value - RequestSuccessMessage target = new RequestSuccessMessage(boundPort); + var target = new RequestSuccessMessage(boundPort); Assert.Inconclusive("TODO: Implement code to verify target"); } } diff --git a/src/Renci.SshNet.Tests/Classes/Messages/MessageAttributeTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/MessageAttributeTest.cs index 9c4f93cd0..eb6118d61 100644 --- a/src/Renci.SshNet.Tests/Classes/Messages/MessageAttributeTest.cs +++ b/src/Renci.SshNet.Tests/Classes/Messages/MessageAttributeTest.cs @@ -1,6 +1,6 @@ -using Renci.SshNet.Messages; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using System; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +using Renci.SshNet.Messages; using Renci.SshNet.Tests.Common; namespace Renci.SshNet.Tests.Classes.Messages @@ -19,9 +19,9 @@ public class MessageAttributeTest : TestBase [Ignore] // placeholder public void MessageAttributeConstructorTest() { - string name = string.Empty; // TODO: Initialize to an appropriate value + var name = string.Empty; // TODO: Initialize to an appropriate value byte number = 0; // TODO: Initialize to an appropriate value - MessageAttribute target = new MessageAttribute(name, number); + var target = new MessageAttribute(name, number); Assert.Inconclusive("TODO: Implement code to verify target"); } @@ -32,10 +32,10 @@ public void MessageAttributeConstructorTest() [Ignore] // placeholder public void NameTest() { - string name = string.Empty; // TODO: Initialize to an appropriate value + var name = string.Empty; // TODO: Initialize to an appropriate value byte number = 0; // TODO: Initialize to an appropriate value - MessageAttribute target = new MessageAttribute(name, number); // TODO: Initialize to an appropriate value - string expected = string.Empty; // TODO: Initialize to an appropriate value + var target = new MessageAttribute(name, number); // TODO: Initialize to an appropriate value + var expected = string.Empty; // TODO: Initialize to an appropriate value target.Name = expected; var actual = target.Name; Assert.AreEqual(expected, actual); @@ -49,9 +49,9 @@ public void NameTest() [Ignore] // placeholder public void NumberTest() { - string name = string.Empty; // TODO: Initialize to an appropriate value + var name = string.Empty; // TODO: Initialize to an appropriate value byte number = 0; // TODO: Initialize to an appropriate value - MessageAttribute target = new MessageAttribute(name, number); // TODO: Initialize to an appropriate value + var target = new MessageAttribute(name, number); // TODO: Initialize to an appropriate value byte expected = 0; // TODO: Initialize to an appropriate value target.Number = expected; var actual = target.Number; diff --git a/src/Renci.SshNet.Tests/Classes/Messages/MessageTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/MessageTest.cs index 5ad0d6bfe..d3290f1f9 100644 --- a/src/Renci.SshNet.Tests/Classes/Messages/MessageTest.cs +++ b/src/Renci.SshNet.Tests/Classes/Messages/MessageTest.cs @@ -1,6 +1,6 @@ -using Renci.SshNet.Messages; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using System; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +using Renci.SshNet.Messages; using Renci.SshNet.Tests.Common; namespace Renci.SshNet.Tests.Classes.Messages @@ -26,7 +26,7 @@ internal virtual Message CreateMessage() [TestMethod] public void GetBytesTest() { - Message target = CreateMessage(); // TODO: Initialize to an appropriate value + var target = CreateMessage(); // TODO: Initialize to an appropriate value byte[] expected = null; // TODO: Initialize to an appropriate value var actual = target.GetBytes(); Assert.AreEqual(expected, actual); @@ -39,8 +39,8 @@ public void GetBytesTest() [TestMethod] public void ToStringTest() { - Message target = CreateMessage(); // TODO: Initialize to an appropriate value - string expected = string.Empty; // TODO: Initialize to an appropriate value + var target = CreateMessage(); // TODO: Initialize to an appropriate value + var expected = string.Empty; // TODO: Initialize to an appropriate value var actual = target.ToString(); Assert.AreEqual(expected, actual); Assert.Inconclusive("Verify the correctness of this test method."); diff --git a/src/Renci.SshNet.Tests/Classes/Messages/Transport/DisconnectMessageTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/Transport/DisconnectMessageTest.cs index 280370364..853653826 100644 --- a/src/Renci.SshNet.Tests/Classes/Messages/Transport/DisconnectMessageTest.cs +++ b/src/Renci.SshNet.Tests/Classes/Messages/Transport/DisconnectMessageTest.cs @@ -1,6 +1,6 @@ -using Renci.SshNet.Messages.Transport; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using System; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +using Renci.SshNet.Messages.Transport; using Renci.SshNet.Tests.Common; namespace Renci.SshNet.Tests.Classes.Messages.Transport @@ -19,7 +19,7 @@ public class DisconnectMessageTest : TestBase [Ignore] // placeholder public void DisconnectMessageConstructorTest() { - DisconnectMessage target = new DisconnectMessage(); + var target = new DisconnectMessage(); Assert.Inconclusive("TODO: Implement code to verify target"); } @@ -30,9 +30,9 @@ public void DisconnectMessageConstructorTest() [Ignore] // placeholder public void DisconnectMessageConstructorTest1() { - DisconnectReason reasonCode = new DisconnectReason(); // TODO: Initialize to an appropriate value - string message = string.Empty; // TODO: Initialize to an appropriate value - DisconnectMessage target = new DisconnectMessage(reasonCode, message); + var reasonCode = new DisconnectReason(); // TODO: Initialize to an appropriate value + var message = string.Empty; // TODO: Initialize to an appropriate value + var target = new DisconnectMessage(reasonCode, message); Assert.Inconclusive("TODO: Implement code to verify target"); } } diff --git a/src/Renci.SshNet.Tests/Classes/Messages/Transport/KeyExchangeDhGroupExchangeGroupTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/Transport/KeyExchangeDhGroupExchangeGroupTest.cs index fc49a61d9..b5a56f48c 100644 --- a/src/Renci.SshNet.Tests/Classes/Messages/Transport/KeyExchangeDhGroupExchangeGroupTest.cs +++ b/src/Renci.SshNet.Tests/Classes/Messages/Transport/KeyExchangeDhGroupExchangeGroupTest.cs @@ -1,6 +1,6 @@ -using Renci.SshNet.Messages.Transport; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using System; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +using Renci.SshNet.Messages.Transport; using Renci.SshNet.Tests.Common; namespace Renci.SshNet.Tests.Classes.Messages.Transport @@ -19,7 +19,7 @@ public class KeyExchangeDhGroupExchangeGroupTest : TestBase [Ignore] // placeholder public void KeyExchangeDhGroupExchangeGroupConstructorTest() { - KeyExchangeDhGroupExchangeGroup target = new KeyExchangeDhGroupExchangeGroup(); + var target = new KeyExchangeDhGroupExchangeGroup(); Assert.Inconclusive("TODO: Implement code to verify target"); } } diff --git a/src/Renci.SshNet.Tests/Classes/Messages/Transport/KeyExchangeDhGroupExchangeReplyBuilder.cs b/src/Renci.SshNet.Tests/Classes/Messages/Transport/KeyExchangeDhGroupExchangeReplyBuilder.cs index dbb5d0ede..81714f368 100644 --- a/src/Renci.SshNet.Tests/Classes/Messages/Transport/KeyExchangeDhGroupExchangeReplyBuilder.cs +++ b/src/Renci.SshNet.Tests/Classes/Messages/Transport/KeyExchangeDhGroupExchangeReplyBuilder.cs @@ -17,7 +17,10 @@ public KeyExchangeDhGroupExchangeReplyBuilder WithHostKey(string hostKeyAlgorith var sshDataStream = new SshDataStream(0); foreach (var hostKey in hostKeys) + { sshDataStream.Write(hostKey); + } + _hostKeys = sshDataStream.ToArray(); return this; diff --git a/src/Renci.SshNet.Tests/Classes/Messages/Transport/KeyExchangeDhGroupExchangeRequestTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/Transport/KeyExchangeDhGroupExchangeRequestTest.cs index ea2b7159d..0120c5550 100644 --- a/src/Renci.SshNet.Tests/Classes/Messages/Transport/KeyExchangeDhGroupExchangeRequestTest.cs +++ b/src/Renci.SshNet.Tests/Classes/Messages/Transport/KeyExchangeDhGroupExchangeRequestTest.cs @@ -1,8 +1,9 @@ using System; + using Microsoft.VisualStudio.TestTools.UnitTesting; + using Renci.SshNet.Common; using Renci.SshNet.Messages.Transport; -using Renci.SshNet.Tests.Common; namespace Renci.SshNet.Tests.Classes.Messages.Transport { @@ -67,4 +68,4 @@ public void Load() Assert.AreEqual(_maximum, target.Maximum); } } -} \ No newline at end of file +} diff --git a/src/Renci.SshNet.Tests/Classes/Messages/Transport/KeyExchangeDhReplyMessageTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/Transport/KeyExchangeDhReplyMessageTest.cs index 961fe4370..a0d0d2f13 100644 --- a/src/Renci.SshNet.Tests/Classes/Messages/Transport/KeyExchangeDhReplyMessageTest.cs +++ b/src/Renci.SshNet.Tests/Classes/Messages/Transport/KeyExchangeDhReplyMessageTest.cs @@ -1,6 +1,6 @@ -using Renci.SshNet.Messages.Transport; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using System; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +using Renci.SshNet.Messages.Transport; using Renci.SshNet.Tests.Common; namespace Renci.SshNet.Tests.Classes.Messages.Transport @@ -19,7 +19,7 @@ public class KeyExchangeDhReplyMessageTest : TestBase [Ignore] // placeholder public void KeyExchangeDhReplyMessageConstructorTest() { - KeyExchangeDhReplyMessage target = new KeyExchangeDhReplyMessage(); + var target = new KeyExchangeDhReplyMessage(); Assert.Inconclusive("TODO: Implement code to verify target"); } } diff --git a/src/Renci.SshNet.Tests/Classes/Messages/Transport/NewKeysMessageTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/Transport/NewKeysMessageTest.cs index f1ea0398d..430c2151f 100644 --- a/src/Renci.SshNet.Tests/Classes/Messages/Transport/NewKeysMessageTest.cs +++ b/src/Renci.SshNet.Tests/Classes/Messages/Transport/NewKeysMessageTest.cs @@ -1,6 +1,6 @@ -using Renci.SshNet.Messages.Transport; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using System; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +using Renci.SshNet.Messages.Transport; using Renci.SshNet.Tests.Common; namespace Renci.SshNet.Tests.Classes.Messages.Transport @@ -19,7 +19,7 @@ public class NewKeysMessageTest : TestBase [Ignore] // placeholder public void NewKeysMessageConstructorTest() { - NewKeysMessage target = new NewKeysMessage(); + var target = new NewKeysMessage(); Assert.Inconclusive("TODO: Implement code to verify target"); } } diff --git a/src/Renci.SshNet.Tests/Classes/Messages/Transport/ServiceAcceptMessageTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/Transport/ServiceAcceptMessageTest.cs index 5c8f40912..143cd7003 100644 --- a/src/Renci.SshNet.Tests/Classes/Messages/Transport/ServiceAcceptMessageTest.cs +++ b/src/Renci.SshNet.Tests/Classes/Messages/Transport/ServiceAcceptMessageTest.cs @@ -1,6 +1,6 @@ -using Renci.SshNet.Messages.Transport; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using System; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +using Renci.SshNet.Messages.Transport; namespace Renci.SshNet.Tests.Classes.Messages.Transport { @@ -18,7 +18,7 @@ public class ServiceAcceptMessageTest [Ignore] // placeholder public void ServiceAcceptMessageConstructorTest() { - ServiceAcceptMessage target = new ServiceAcceptMessage(); + var target = new ServiceAcceptMessage(); Assert.Inconclusive("TODO: Implement code to verify target"); } } diff --git a/src/Renci.SshNet.Tests/Classes/Messages/Transport/ServiceRequestMessageTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/Transport/ServiceRequestMessageTest.cs index dc1db6a42..9806fb862 100644 --- a/src/Renci.SshNet.Tests/Classes/Messages/Transport/ServiceRequestMessageTest.cs +++ b/src/Renci.SshNet.Tests/Classes/Messages/Transport/ServiceRequestMessageTest.cs @@ -1,6 +1,6 @@ -using Renci.SshNet.Messages.Transport; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using System; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +using Renci.SshNet.Messages.Transport; using Renci.SshNet.Messages; namespace Renci.SshNet.Tests.Classes.Messages.Transport @@ -19,8 +19,8 @@ public class ServiceRequestMessageTest [Ignore] // placeholder public void ServiceRequestMessageConstructorTest() { - ServiceName serviceName = new ServiceName(); // TODO: Initialize to an appropriate value - ServiceRequestMessage target = new ServiceRequestMessage(serviceName); + var serviceName = new ServiceName(); // TODO: Initialize to an appropriate value + var target = new ServiceRequestMessage(serviceName); Assert.Inconclusive("TODO: Implement code to verify target"); } } diff --git a/src/Renci.SshNet.Tests/Classes/Messages/Transport/UnimplementedMessageTest.cs b/src/Renci.SshNet.Tests/Classes/Messages/Transport/UnimplementedMessageTest.cs index 8abdd4ad5..5e8d53add 100644 --- a/src/Renci.SshNet.Tests/Classes/Messages/Transport/UnimplementedMessageTest.cs +++ b/src/Renci.SshNet.Tests/Classes/Messages/Transport/UnimplementedMessageTest.cs @@ -1,6 +1,5 @@ using Renci.SshNet.Messages.Transport; using Microsoft.VisualStudio.TestTools.UnitTesting; -using System; using Renci.SshNet.Tests.Common; namespace Renci.SshNet.Tests.Classes.Messages.Transport @@ -19,7 +18,7 @@ public class UnimplementedMessageTest : TestBase [Ignore] // placeholder public void UnimplementedMessageConstructorTest() { - UnimplementedMessage target = new UnimplementedMessage(); + var target = new UnimplementedMessage(); Assert.Inconclusive("TODO: Implement code to verify target"); } } diff --git a/src/Renci.SshNet.Tests/Classes/NetConfClientTestBase.cs b/src/Renci.SshNet.Tests/Classes/NetConfClientTestBase.cs index ee8cb018b..4c6cbe7f0 100644 --- a/src/Renci.SshNet.Tests/Classes/NetConfClientTestBase.cs +++ b/src/Renci.SshNet.Tests/Classes/NetConfClientTestBase.cs @@ -5,13 +5,13 @@ namespace Renci.SshNet.Tests.Classes { public abstract class NetConfClientTestBase : BaseClientTestBase { - internal Mock _netConfSessionMock { get; private set; } + internal Mock NetConfSessionMock { get; private set; } protected override void CreateMocks() { base.CreateMocks(); - _netConfSessionMock = new Mock(MockBehavior.Strict); + NetConfSessionMock = new Mock(MockBehavior.Strict); } } } diff --git a/src/Renci.SshNet.Tests/Classes/NetConfClientTest_Connect_NetConfSessionConnectFailure.cs b/src/Renci.SshNet.Tests/Classes/NetConfClientTest_Connect_NetConfSessionConnectFailure.cs index 980c574a1..88410acc1 100644 --- a/src/Renci.SshNet.Tests/Classes/NetConfClientTest_Connect_NetConfSessionConnectFailure.cs +++ b/src/Renci.SshNet.Tests/Classes/NetConfClientTest_Connect_NetConfSessionConnectFailure.cs @@ -1,10 +1,12 @@ using System; using System.Reflection; using System.Threading; + using Microsoft.VisualStudio.TestTools.UnitTesting; + using Moq; + using Renci.SshNet.Common; -using Renci.SshNet.NetConf; using Renci.SshNet.Security; namespace Renci.SshNet.Tests.Classes @@ -21,31 +23,31 @@ protected override void SetupData() { _connectionInfo = new ConnectionInfo("host", "user", new NoneAuthenticationMethod("userauth")); _netConfSessionConnectionException = new ApplicationException(); - _netConfClient = new NetConfClient(_connectionInfo, false, _serviceFactoryMock.Object); + _netConfClient = new NetConfClient(_connectionInfo, false, ServiceFactoryMock.Object); } protected override void SetupMocks() { var sequence = new MockSequence(); - _serviceFactoryMock.InSequence(sequence) - .Setup(p => p.CreateSocketFactory()) - .Returns(_socketFactoryMock.Object); - _serviceFactoryMock.InSequence(sequence) - .Setup(p => p.CreateSession(_connectionInfo, _socketFactoryMock.Object)) - .Returns(_sessionMock.Object); - _sessionMock.InSequence(sequence) - .Setup(p => p.Connect()); - _serviceFactoryMock.InSequence(sequence) - .Setup(p => p.CreateNetConfSession(_sessionMock.Object, -1)) - .Returns(_netConfSessionMock.Object); - _netConfSessionMock.InSequence(sequence) - .Setup(p => p.Connect()) - .Throws(_netConfSessionConnectionException); - _netConfSessionMock.InSequence(sequence) + _ = ServiceFactoryMock.InSequence(sequence) + .Setup(p => p.CreateSocketFactory()) + .Returns(SocketFactoryMock.Object); + _ = ServiceFactoryMock.InSequence(sequence) + .Setup(p => p.CreateSession(_connectionInfo, SocketFactoryMock.Object)) + .Returns(SessionMock.Object); + _ = SessionMock.InSequence(sequence) + .Setup(p => p.Connect()); + _ = ServiceFactoryMock.InSequence(sequence) + .Setup(p => p.CreateNetConfSession(SessionMock.Object, -1)) + .Returns(NetConfSessionMock.Object); + _ = NetConfSessionMock.InSequence(sequence) + .Setup(p => p.Connect()) + .Throws(_netConfSessionConnectionException); + _ = NetConfSessionMock.InSequence(sequence) + .Setup(p => p.Dispose()); + _ = SessionMock.InSequence(sequence) .Setup(p => p.Dispose()); - _sessionMock.InSequence(sequence) - .Setup(p => p.Dispose()); } protected override void Act() @@ -87,7 +89,7 @@ public void ErrorOccuredOnSessionShouldNoLongerBeSignaledViaErrorOccurredOnNetCo _netConfClient.ErrorOccurred += (sender, args) => Interlocked.Increment(ref errorOccurredSignalCount); - _sessionMock.Raise(p => p.ErrorOccured += null, new ExceptionEventArgs(new Exception())); + SessionMock.Raise(p => p.ErrorOccured += null, new ExceptionEventArgs(new Exception())); Assert.AreEqual(0, errorOccurredSignalCount); } @@ -99,7 +101,7 @@ public void HostKeyReceivedOnSessionShouldNoLongerBeSignaledViaHostKeyReceivedOn _netConfClient.HostKeyReceived += (sender, args) => Interlocked.Increment(ref hostKeyReceivedSignalCount); - _sessionMock.Raise(p => p.HostKeyReceived += null, new HostKeyEventArgs(GetKeyHostAlgorithm())); + SessionMock.Raise(p => p.HostKeyReceived += null, new HostKeyEventArgs(GetKeyHostAlgorithm())); Assert.AreEqual(0, hostKeyReceivedSignalCount); } diff --git a/src/Renci.SshNet.Tests/Classes/NetConfClientTest_Dispose_Connected.cs b/src/Renci.SshNet.Tests/Classes/NetConfClientTest_Dispose_Connected.cs index ba86a7c94..ed0103837 100644 --- a/src/Renci.SshNet.Tests/Classes/NetConfClientTest_Dispose_Connected.cs +++ b/src/Renci.SshNet.Tests/Classes/NetConfClientTest_Dispose_Connected.cs @@ -1,7 +1,8 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using System; + +using Microsoft.VisualStudio.TestTools.UnitTesting; + using Moq; -using Renci.SshNet.NetConf; -using System; namespace Renci.SshNet.Tests.Classes { @@ -16,35 +17,37 @@ protected override void SetupData() { _connectionInfo = new ConnectionInfo("host", "user", new NoneAuthenticationMethod("userauth")); _operationTimeout = new Random().Next(1000, 10000); - _netConfClient = new NetConfClient(_connectionInfo, false, _serviceFactoryMock.Object); - _netConfClient.OperationTimeout = TimeSpan.FromMilliseconds(_operationTimeout); + _netConfClient = new NetConfClient(_connectionInfo, false, ServiceFactoryMock.Object) + { + OperationTimeout = TimeSpan.FromMilliseconds(_operationTimeout) + }; } protected override void SetupMocks() { var sequence = new MockSequence(); - _serviceFactoryMock.InSequence(sequence) - .Setup(p => p.CreateSocketFactory()) - .Returns(_socketFactoryMock.Object); - _serviceFactoryMock.InSequence(sequence) - .Setup(p => p.CreateSession(_connectionInfo, _socketFactoryMock.Object)) - .Returns(_sessionMock.Object); - _sessionMock.InSequence(sequence) - .Setup(p => p.Connect()); - _serviceFactoryMock.InSequence(sequence) - .Setup(p => p.CreateNetConfSession(_sessionMock.Object, _operationTimeout)) - .Returns(_netConfSessionMock.Object); - _netConfSessionMock.InSequence(sequence) - .Setup(p => p.Connect()); - _sessionMock.InSequence(sequence) - .Setup(p => p.OnDisconnecting()); - _netConfSessionMock.InSequence(sequence) - .Setup(p => p.Disconnect()); - _sessionMock.InSequence(sequence) - .Setup(p => p.Dispose()); - _netConfSessionMock.InSequence(sequence) - .Setup(p => p.Dispose()); + _ = ServiceFactoryMock.InSequence(sequence) + .Setup(p => p.CreateSocketFactory()) + .Returns(SocketFactoryMock.Object); + _ = ServiceFactoryMock.InSequence(sequence) + .Setup(p => p.CreateSession(_connectionInfo, SocketFactoryMock.Object)) + .Returns(SessionMock.Object); + _ = SessionMock.InSequence(sequence) + .Setup(p => p.Connect()); + _ = ServiceFactoryMock.InSequence(sequence) + .Setup(p => p.CreateNetConfSession(SessionMock.Object, _operationTimeout)) + .Returns(NetConfSessionMock.Object); + _ = NetConfSessionMock.InSequence(sequence) + .Setup(p => p.Connect()); + _ = SessionMock.InSequence(sequence) + .Setup(p => p.OnDisconnecting()); + _ = NetConfSessionMock.InSequence(sequence) + .Setup(p => p.Disconnect()); + _ = SessionMock.InSequence(sequence) + .Setup(p => p.Dispose()); + _ = NetConfSessionMock.InSequence(sequence) + .Setup(p => p.Dispose()); } protected override void Arrange() @@ -62,50 +65,50 @@ protected override void Act() [TestMethod] public void CreateNetConfSessionOnServiceFactoryShouldBeInvokedOnce() { - _serviceFactoryMock.Verify(p => p.CreateNetConfSession(_sessionMock.Object, _operationTimeout), Times.Once); + ServiceFactoryMock.Verify(p => p.CreateNetConfSession(SessionMock.Object, _operationTimeout), Times.Once); } [TestMethod] public void CreateSocketFactoryOnServiceFactoryShouldBeInvokedOnce() { - _serviceFactoryMock.Verify(p => p.CreateSocketFactory(), Times.Once); + ServiceFactoryMock.Verify(p => p.CreateSocketFactory(), Times.Once); } [TestMethod] public void CreateSessionOnServiceFactoryShouldBeInvokedOnce() { - _serviceFactoryMock.Verify(p => p.CreateSession(_connectionInfo, _socketFactoryMock.Object), + ServiceFactoryMock.Verify(p => p.CreateSession(_connectionInfo, SocketFactoryMock.Object), Times.Once); } [TestMethod] public void DisconnectOnNetConfSessionShouldBeInvokedOnce() { - _netConfSessionMock.Verify(p => p.Disconnect(), Times.Once); + NetConfSessionMock.Verify(p => p.Disconnect(), Times.Once); } [TestMethod] public void DisconnectOnSessionShouldNeverBeInvoked() { - _sessionMock.Verify(p => p.Disconnect(), Times.Never); + SessionMock.Verify(p => p.Disconnect(), Times.Never); } [TestMethod] public void DisposeOnNetConfSessionShouldBeInvokedOnce() { - _netConfSessionMock.Verify(p => p.Dispose(), Times.Once); + NetConfSessionMock.Verify(p => p.Dispose(), Times.Once); } [TestMethod] public void DisposeOnSessionShouldBeInvokedOnce() { - _sessionMock.Verify(p => p.Dispose(), Times.Once); + SessionMock.Verify(p => p.Dispose(), Times.Once); } [TestMethod] public void OnDisconnectingOnSessionShouldBeInvokedOnce() { - _sessionMock.Verify(p => p.OnDisconnecting(), Times.Once); + SessionMock.Verify(p => p.OnDisconnecting(), Times.Once); } } } diff --git a/src/Renci.SshNet.Tests/Classes/NetConfClientTest_Dispose_Disconnected.cs b/src/Renci.SshNet.Tests/Classes/NetConfClientTest_Dispose_Disconnected.cs index 8a4fbcd2e..efbfe7ff2 100644 --- a/src/Renci.SshNet.Tests/Classes/NetConfClientTest_Dispose_Disconnected.cs +++ b/src/Renci.SshNet.Tests/Classes/NetConfClientTest_Dispose_Disconnected.cs @@ -1,6 +1,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; + using Moq; -using Renci.SshNet.NetConf; + using System; namespace Renci.SshNet.Tests.Classes @@ -19,39 +20,43 @@ public void Setup() Act(); } - [TestCleanup] - public void Cleanup() - { - } - protected override void SetupData() { _connectionInfo = new ConnectionInfo("host", "user", new NoneAuthenticationMethod("userauth")); _operationTimeout = new Random().Next(1000, 10000); - _netConfClient = new NetConfClient(_connectionInfo, false, _serviceFactoryMock.Object); - _netConfClient.OperationTimeout = TimeSpan.FromMilliseconds(_operationTimeout); + _netConfClient = new NetConfClient(_connectionInfo, false, ServiceFactoryMock.Object) + { + OperationTimeout = TimeSpan.FromMilliseconds(_operationTimeout) + }; } protected override void SetupMocks() { var sequence = new MockSequence(); - _serviceFactoryMock.InSequence(sequence) - .Setup(p => p.CreateSocketFactory()) - .Returns(_socketFactoryMock.Object); - _serviceFactoryMock.InSequence(sequence) - .Setup(p => p.CreateSession(_connectionInfo, _socketFactoryMock.Object)) - .Returns(_sessionMock.Object); - _sessionMock.InSequence(sequence).Setup(p => p.Connect()); - _serviceFactoryMock.InSequence(sequence) - .Setup(p => p.CreateNetConfSession(_sessionMock.Object, _operationTimeout)) - .Returns(_netConfSessionMock.Object); - _netConfSessionMock.InSequence(sequence).Setup(p => p.Connect()); - _sessionMock.InSequence(sequence).Setup(p => p.OnDisconnecting()); - _netConfSessionMock.InSequence(sequence).Setup(p => p.Disconnect()); - _sessionMock.InSequence(sequence).Setup(p => p.Dispose()); - _netConfSessionMock.InSequence(sequence).Setup(p => p.Disconnect()); - _netConfSessionMock.InSequence(sequence).Setup(p => p.Dispose()); + _ = ServiceFactoryMock.InSequence(sequence) + .Setup(p => p.CreateSocketFactory()) + .Returns(SocketFactoryMock.Object); + _ = ServiceFactoryMock.InSequence(sequence) + .Setup(p => p.CreateSession(_connectionInfo, SocketFactoryMock.Object)) + .Returns(SessionMock.Object); + _ = SessionMock.InSequence(sequence) + .Setup(p => p.Connect()); + _ = ServiceFactoryMock.InSequence(sequence) + .Setup(p => p.CreateNetConfSession(SessionMock.Object, _operationTimeout)) + .Returns(NetConfSessionMock.Object); + _ = NetConfSessionMock.InSequence(sequence) + .Setup(p => p.Connect()); + _ = SessionMock.InSequence(sequence) + .Setup(p => p.OnDisconnecting()); + _ = NetConfSessionMock.InSequence(sequence) + .Setup(p => p.Disconnect()); + _ = SessionMock.InSequence(sequence) + .Setup(p => p.Dispose()); + _ = NetConfSessionMock.InSequence(sequence) + .Setup(p => p.Disconnect()); + _ = NetConfSessionMock.InSequence(sequence) + .Setup(p => p.Dispose()); } protected override void Arrange() @@ -70,50 +75,50 @@ protected override void Act() [TestMethod] public void CreateNetConfSessionOnServiceFactoryShouldBeInvokedOnce() { - _serviceFactoryMock.Verify(p => p.CreateNetConfSession(_sessionMock.Object, _operationTimeout), Times.Once); + ServiceFactoryMock.Verify(p => p.CreateNetConfSession(SessionMock.Object, _operationTimeout), Times.Once); } [TestMethod] public void CreateSocketFactoryOnServiceFactoryShouldBeInvokedOnce() { - _serviceFactoryMock.Verify(p => p.CreateSocketFactory(), Times.Once); + ServiceFactoryMock.Verify(p => p.CreateSocketFactory(), Times.Once); } [TestMethod] public void CreateSessionOnServiceFactoryShouldBeInvokedOnce() { - _serviceFactoryMock.Verify(p => p.CreateSession(_connectionInfo, _socketFactoryMock.Object), + ServiceFactoryMock.Verify(p => p.CreateSession(_connectionInfo, SocketFactoryMock.Object), Times.Once); } [TestMethod] public void DisconnectOnNetConfSessionShouldBeInvokedTwice() { - _netConfSessionMock.Verify(p => p.Disconnect(), Times.Exactly(2)); + NetConfSessionMock.Verify(p => p.Disconnect(), Times.Exactly(2)); } [TestMethod] public void DisconnectOnSessionShouldNeverBeInvoked() { - _sessionMock.Verify(p => p.Disconnect(), Times.Never); + SessionMock.Verify(p => p.Disconnect(), Times.Never); } [TestMethod] public void DisposeOnNetConfSessionShouldBeInvokedOnce() { - _netConfSessionMock.Verify(p => p.Dispose(), Times.Once); + NetConfSessionMock.Verify(p => p.Dispose(), Times.Once); } [TestMethod] public void DisposeOnSessionShouldBeInvokedOnce() { - _sessionMock.Verify(p => p.Dispose(), Times.Once); + SessionMock.Verify(p => p.Dispose(), Times.Once); } [TestMethod] public void OnDisconnectingOnSessionShouldBeInvokedOnce() { - _sessionMock.Verify(p => p.OnDisconnecting(), Times.Once); + SessionMock.Verify(p => p.OnDisconnecting(), Times.Once); } } } diff --git a/src/Renci.SshNet.Tests/Classes/NetConfClientTest_Dispose_Disposed.cs b/src/Renci.SshNet.Tests/Classes/NetConfClientTest_Dispose_Disposed.cs index 9ed692a30..cc5f704f4 100644 --- a/src/Renci.SshNet.Tests/Classes/NetConfClientTest_Dispose_Disposed.cs +++ b/src/Renci.SshNet.Tests/Classes/NetConfClientTest_Dispose_Disposed.cs @@ -1,6 +1,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; + using Moq; -using Renci.SshNet.NetConf; + using System; namespace Renci.SshNet.Tests.Classes @@ -16,29 +17,37 @@ protected override void SetupData() { _connectionInfo = new ConnectionInfo("host", "user", new NoneAuthenticationMethod("userauth")); _operationTimeout = new Random().Next(1000, 10000); - _netConfClient = new NetConfClient(_connectionInfo, false, _serviceFactoryMock.Object); - _netConfClient.OperationTimeout = TimeSpan.FromMilliseconds(_operationTimeout); + _netConfClient = new NetConfClient(_connectionInfo, false, ServiceFactoryMock.Object) + { + OperationTimeout = TimeSpan.FromMilliseconds(_operationTimeout) + }; } protected override void SetupMocks() { var sequence = new MockSequence(); - _serviceFactoryMock.InSequence(sequence) - .Setup(p => p.CreateSocketFactory()) - .Returns(_socketFactoryMock.Object); - _serviceFactoryMock.InSequence(sequence) - .Setup(p => p.CreateSession(_connectionInfo, _socketFactoryMock.Object)) - .Returns(_sessionMock.Object); - _sessionMock.InSequence(sequence).Setup(p => p.Connect()); - _serviceFactoryMock.InSequence(sequence) - .Setup(p => p.CreateNetConfSession(_sessionMock.Object, _operationTimeout)) - .Returns(_netConfSessionMock.Object); - _netConfSessionMock.InSequence(sequence).Setup(p => p.Connect()); - _sessionMock.InSequence(sequence).Setup(p => p.OnDisconnecting()); - _netConfSessionMock.InSequence(sequence).Setup(p => p.Disconnect()); - _sessionMock.InSequence(sequence).Setup(p => p.Dispose()); - _netConfSessionMock.InSequence(sequence).Setup(p => p.Dispose()); + _ = ServiceFactoryMock.InSequence(sequence) + .Setup(p => p.CreateSocketFactory()) + .Returns(SocketFactoryMock.Object); + _ = ServiceFactoryMock.InSequence(sequence) + .Setup(p => p.CreateSession(_connectionInfo, SocketFactoryMock.Object)) + .Returns(SessionMock.Object); + _ = SessionMock.InSequence(sequence) + .Setup(p => p.Connect()); + _ = ServiceFactoryMock.InSequence(sequence) + .Setup(p => p.CreateNetConfSession(SessionMock.Object, _operationTimeout)) + .Returns(NetConfSessionMock.Object); + _ = NetConfSessionMock.InSequence(sequence) + .Setup(p => p.Connect()); + _ = SessionMock.InSequence(sequence) + .Setup(p => p.OnDisconnecting()); + _ = NetConfSessionMock.InSequence(sequence) + .Setup(p => p.Disconnect()); + _ = SessionMock.InSequence(sequence) + .Setup(p => p.Dispose()); + _ = NetConfSessionMock.InSequence(sequence) + .Setup(p => p.Dispose()); } protected override void Arrange() @@ -57,50 +66,50 @@ protected override void Act() [TestMethod] public void CreateNetConfSessionOnServiceFactoryShouldBeInvokedOnce() { - _serviceFactoryMock.Verify(p => p.CreateNetConfSession(_sessionMock.Object, _operationTimeout), Times.Once); + ServiceFactoryMock.Verify(p => p.CreateNetConfSession(SessionMock.Object, _operationTimeout), Times.Once); } [TestMethod] public void CreateSocketFactoryOnServiceFactoryShouldBeInvokedOnce() { - _serviceFactoryMock.Verify(p => p.CreateSocketFactory(), Times.Once); + ServiceFactoryMock.Verify(p => p.CreateSocketFactory(), Times.Once); } [TestMethod] public void CreateSessionOnServiceFactoryShouldBeInvokedOnce() { - _serviceFactoryMock.Verify(p => p.CreateSession(_connectionInfo, _socketFactoryMock.Object), + ServiceFactoryMock.Verify(p => p.CreateSession(_connectionInfo, SocketFactoryMock.Object), Times.Once); } [TestMethod] public void DisconnectOnNetConfSessionShouldBeInvokedOnce() { - _netConfSessionMock.Verify(p => p.Disconnect(), Times.Once); + NetConfSessionMock.Verify(p => p.Disconnect(), Times.Once); } [TestMethod] public void DisconnectOnSessionShouldNeverBeInvoked() { - _sessionMock.Verify(p => p.Disconnect(), Times.Never); + SessionMock.Verify(p => p.Disconnect(), Times.Never); } [TestMethod] public void DisposeOnNetConfSessionShouldBeInvokedOnce() { - _netConfSessionMock.Verify(p => p.Dispose(), Times.Once); + NetConfSessionMock.Verify(p => p.Dispose(), Times.Once); } [TestMethod] public void DisposeOnSessionShouldBeInvokedOnce() { - _sessionMock.Verify(p => p.Dispose(), Times.Once); + SessionMock.Verify(p => p.Dispose(), Times.Once); } [TestMethod] public void OnDisconnectingOnSessionShouldBeInvokedOnce() { - _sessionMock.Verify(p => p.OnDisconnecting(), Times.Once); + SessionMock.Verify(p => p.OnDisconnecting(), Times.Once); } } } diff --git a/src/Renci.SshNet.Tests/Classes/NetConfClientTest_Finalize_Connected.cs b/src/Renci.SshNet.Tests/Classes/NetConfClientTest_Finalize_Connected.cs index 44761e96e..ec827b1e6 100644 --- a/src/Renci.SshNet.Tests/Classes/NetConfClientTest_Finalize_Connected.cs +++ b/src/Renci.SshNet.Tests/Classes/NetConfClientTest_Finalize_Connected.cs @@ -16,8 +16,10 @@ protected override void SetupData() { _connectionInfo = new ConnectionInfo("host", "user", new NoneAuthenticationMethod("userauth")); _operationTimeout = new Random().Next(1000, 10000); - _netConfClient = new NetConfClient(_connectionInfo, false, _serviceFactoryMock.Object); - _netConfClient.OperationTimeout = TimeSpan.FromMilliseconds(_operationTimeout); + _netConfClient = new NetConfClient(_connectionInfo, false, ServiceFactoryMock.Object) + { + OperationTimeout = TimeSpan.FromMilliseconds(_operationTimeout) + }; _netConfClientWeakRefence = new WeakReference(_netConfClient); } @@ -25,19 +27,19 @@ protected override void SetupMocks() { var sequence = new MockSequence(); - _serviceFactoryMock.InSequence(sequence) - .Setup(p => p.CreateSocketFactory()) - .Returns(_socketFactoryMock.Object); - _serviceFactoryMock.InSequence(sequence) - .Setup(p => p.CreateSession(_connectionInfo, _socketFactoryMock.Object)) - .Returns(_sessionMock.Object); - _sessionMock.InSequence(sequence) - .Setup(p => p.Connect()); - _serviceFactoryMock.InSequence(sequence) - .Setup(p => p.CreateNetConfSession(_sessionMock.Object, _operationTimeout)) - .Returns(_netConfSessionMock.Object); - _netConfSessionMock.InSequence(sequence) - .Setup(p => p.Connect()); + _ = ServiceFactoryMock.InSequence(sequence) + .Setup(p => p.CreateSocketFactory()) + .Returns(SocketFactoryMock.Object); + _ = ServiceFactoryMock.InSequence(sequence) + .Setup(p => p.CreateSession(_connectionInfo, SocketFactoryMock.Object)) + .Returns(SessionMock.Object); + _ = SessionMock.InSequence(sequence) + .Setup(p => p.Connect()); + _ = ServiceFactoryMock.InSequence(sequence) + .Setup(p => p.CreateNetConfSession(SessionMock.Object, _operationTimeout)) + .Returns(NetConfSessionMock.Object); + _ = NetConfSessionMock.InSequence(sequence) + .Setup(p => p.Connect()); } protected override void Arrange() @@ -64,7 +66,7 @@ public void DisconnectOnNetConfSessionShouldBeInvokedOnce() // Since we recreated the mocks, this test has no value // We'll leaving ths test just in case we have a solution that does not require us // to recreate the mocks - _netConfSessionMock.Verify(p => p.Disconnect(), Times.Never); + NetConfSessionMock.Verify(p => p.Disconnect(), Times.Never); } [TestMethod] @@ -73,7 +75,7 @@ public void DisposeOnNetConfSessionShouldBeInvokedOnce() // Since we recreated the mocks, this test has no value // We'll leaving ths test just in case we have a solution that does not require us // to recreate the mocks - _netConfSessionMock.Verify(p => p.Dispose(), Times.Never); + NetConfSessionMock.Verify(p => p.Dispose(), Times.Never); } [TestMethod] diff --git a/src/Renci.SshNet.Tests/Classes/PasswordConnectionInfoTest.cs b/src/Renci.SshNet.Tests/Classes/PasswordConnectionInfoTest.cs index 52088160c..824f649f1 100644 --- a/src/Renci.SshNet.Tests/Classes/PasswordConnectionInfoTest.cs +++ b/src/Renci.SshNet.Tests/Classes/PasswordConnectionInfoTest.cs @@ -97,7 +97,7 @@ public void Test_ConnectionInfo_Host_Is_Null() { try { - new PasswordConnectionInfo(null, Resources.USERNAME, Resources.PASSWORD); + _ = new PasswordConnectionInfo(null, Resources.USERNAME, Resources.PASSWORD); Assert.Fail(); } catch (ArgumentNullException ex) @@ -113,7 +113,7 @@ public void Test_ConnectionInfo_Host_Is_Null() [ExpectedException(typeof(ArgumentException))] public void Test_ConnectionInfo_Username_Is_Null() { - var connectionInfo = new PasswordConnectionInfo(Resources.HOST, null, Resources.PASSWORD); + _ = new PasswordConnectionInfo(Resources.HOST, null, Resources.PASSWORD); } [WorkItem(703), TestMethod] @@ -121,7 +121,7 @@ public void Test_ConnectionInfo_Username_Is_Null() [ExpectedException(typeof(ArgumentNullException))] public void Test_ConnectionInfo_Password_Is_Null() { - var connectionInfo = new PasswordConnectionInfo(Resources.HOST, Resources.USERNAME, (string)null); + _ = new PasswordConnectionInfo(Resources.HOST, Resources.USERNAME, (string)null); } [TestMethod] @@ -130,7 +130,7 @@ public void Test_ConnectionInfo_Password_Is_Null() [ExpectedException(typeof(ArgumentException))] public void Test_ConnectionInfo_Username_Is_Whitespace() { - var connectionInfo = new PasswordConnectionInfo(Resources.HOST, " ", Resources.PASSWORD); + _ = new PasswordConnectionInfo(Resources.HOST, " ", Resources.PASSWORD); } [WorkItem(703), TestMethod] @@ -138,7 +138,7 @@ public void Test_ConnectionInfo_Username_Is_Whitespace() [ExpectedException(typeof(ArgumentOutOfRangeException))] public void Test_ConnectionInfo_SmallPortNumber() { - var connectionInfo = new PasswordConnectionInfo(Resources.HOST, IPEndPoint.MinPort - 1, Resources.USERNAME, Resources.PASSWORD); + _ = new PasswordConnectionInfo(Resources.HOST, IPEndPoint.MinPort - 1, Resources.USERNAME, Resources.PASSWORD); } [WorkItem(703), TestMethod] @@ -146,7 +146,7 @@ public void Test_ConnectionInfo_SmallPortNumber() [ExpectedException(typeof(ArgumentOutOfRangeException))] public void Test_ConnectionInfo_BigPortNumber() { - var connectionInfo = new PasswordConnectionInfo(Resources.HOST, IPEndPoint.MaxPort + 1, Resources.USERNAME, Resources.PASSWORD); + _ = new PasswordConnectionInfo(Resources.HOST, IPEndPoint.MaxPort + 1, Resources.USERNAME, Resources.PASSWORD); } [TestMethod] @@ -209,10 +209,10 @@ public void Test_Ssh_Connect_Via_HttpProxy() [Ignore] // placeholder for actual test public void DisposeTest() { - string host = string.Empty; // TODO: Initialize to an appropriate value - string username = string.Empty; // TODO: Initialize to an appropriate value + var host = string.Empty; // TODO: Initialize to an appropriate value + var username = string.Empty; // TODO: Initialize to an appropriate value byte[] password = null; // TODO: Initialize to an appropriate value - PasswordConnectionInfo target = new PasswordConnectionInfo(host, username, password); // TODO: Initialize to an appropriate value + var target = new PasswordConnectionInfo(host, username, password); // TODO: Initialize to an appropriate value target.Dispose(); Assert.Inconclusive("A method that does not return a value cannot be verified."); } @@ -478,4 +478,4 @@ public void PasswordConnectionInfoConstructorTest14() } } -} \ No newline at end of file +} diff --git a/src/Renci.SshNet.Tests/Classes/PrivateKeyFileTest.cs b/src/Renci.SshNet.Tests/Classes/PrivateKeyFileTest.cs index d1c18eabc..4ca6e9544 100644 --- a/src/Renci.SshNet.Tests/Classes/PrivateKeyFileTest.cs +++ b/src/Renci.SshNet.Tests/Classes/PrivateKeyFileTest.cs @@ -24,7 +24,9 @@ public void SetUp() public void TearDown() { if (_temporaryFile != null) + { File.Delete(_temporaryFile); + } } /// @@ -36,7 +38,7 @@ public void ConstructorWithFileNameShouldThrowArgumentNullExceptionWhenFileNameI var fileName = string.Empty; try { - new PrivateKeyFile(fileName); + _ = new PrivateKeyFile(fileName); Assert.Fail(); } catch (ArgumentNullException ex) @@ -55,7 +57,7 @@ public void ConstructorWithFileNameShouldThrowArgumentNullExceptionWhenFileNameI var fileName = string.Empty; try { - new PrivateKeyFile(fileName); + _ = new PrivateKeyFile(fileName); Assert.Fail(); } catch (ArgumentNullException ex) @@ -74,7 +76,7 @@ public void ConstructorWithFileNameAndPassphraseShouldThrowArgumentNullException var fileName = string.Empty; try { - new PrivateKeyFile(fileName, "12345"); + _ = new PrivateKeyFile(fileName, "12345"); Assert.Fail(); } catch (ArgumentNullException ex) @@ -93,7 +95,7 @@ public void ConstructorWithFileNameAndPassphraseShouldThrowArgumentNullException var fileName = string.Empty; try { - new PrivateKeyFile(fileName, "12345"); + _ = new PrivateKeyFile(fileName, "12345"); Assert.Fail(); } catch (ArgumentNullException ex) @@ -109,7 +111,7 @@ public void ConstructorWithPrivateKeyShouldThrowArgumentNullExceptionWhenPrivate Stream privateKey = null; try { - new PrivateKeyFile(privateKey); + _ = new PrivateKeyFile(privateKey); Assert.Fail(); } catch (ArgumentNullException ex) @@ -125,7 +127,7 @@ public void ConstructorWithPrivateKeyAndPassphraseShouldThrowArgumentNullExcepti Stream privateKey = null; try { - new PrivateKeyFile(privateKey, "12345"); + _ = new PrivateKeyFile(privateKey, "12345"); Assert.Fail(); } catch (ArgumentNullException ex) @@ -142,7 +144,7 @@ public void Test_PrivateKey_RSA() { using (var stream = GetData("Key.RSA.txt")) { - new PrivateKeyFile(stream); + _ = new PrivateKeyFile(stream); } } @@ -153,7 +155,7 @@ public void Test_PrivateKey_SSH2_DSA() { using (var stream = GetData("Key.SSH2.DSA.txt")) { - new PrivateKeyFile(stream); + _ = new PrivateKeyFile(stream); } } @@ -164,7 +166,7 @@ public void Test_PrivateKey_SSH2_RSA() { using (var stream = GetData("Key.SSH2.RSA.txt")) { - new PrivateKeyFile(stream); + _ = new PrivateKeyFile(stream); } } @@ -175,7 +177,7 @@ public void Test_PrivateKey_SSH2_Encrypted_DSA_DES_CBC() { using (var stream = GetData("Key.SSH2.DSA.Encrypted.Des.CBC.12345.txt")) { - new PrivateKeyFile(stream, "12345"); + _ = new PrivateKeyFile(stream, "12345"); } } @@ -186,7 +188,7 @@ public void Test_PrivateKey_SSH2_Encrypted_RSA_DES_CBC() { using (var stream = GetData("Key.SSH2.RSA.Encrypted.Des.CBC.12345.txt")) { - new PrivateKeyFile(stream, "12345"); + _ = new PrivateKeyFile(stream, "12345"); } } @@ -199,7 +201,7 @@ public void Test_PrivateKey_SSH2_Encrypted_ShouldThrowSshExceptionWhenPassphrase { try { - new PrivateKeyFile(stream, "34567"); + _ = new PrivateKeyFile(stream, "34567"); Assert.Fail(); } catch (SshException ex) @@ -220,7 +222,7 @@ public void Test_PrivateKey_SSH2_Encrypted_ShouldThrowSshPassPhraseNullOrEmptyEx { try { - new PrivateKeyFile(stream, null); + _ = new PrivateKeyFile(stream, null); Assert.Fail(); } catch (SshPassPhraseNullOrEmptyException ex) @@ -241,7 +243,7 @@ public void Test_PrivateKey_SSH2_Encrypted_ShouldThrowSshPassPhraseNullOrEmptyEx { try { - new PrivateKeyFile(stream, string.Empty); + _ = new PrivateKeyFile(stream, string.Empty); Assert.Fail(); } catch (SshPassPhraseNullOrEmptyException ex) @@ -260,7 +262,7 @@ public void Test_PrivateKey_RSA_DES_CBC() { using (var stream = GetData("Key.RSA.Encrypted.Des.CBC.12345.txt")) { - new PrivateKeyFile(stream, "12345"); + _ = new PrivateKeyFile(stream, "12345"); } } @@ -271,7 +273,7 @@ public void Test_PrivateKey_RSA_DES_EDE3_CBC() { using (var stream = GetData("Key.RSA.Encrypted.Des.Ede3.CBC.12345.txt")) { - new PrivateKeyFile(stream, "12345"); + _ = new PrivateKeyFile(stream, "12345"); } } @@ -282,7 +284,7 @@ public void Test_PrivateKey_RSA_AES_128_CBC() { using (var stream = GetData("Key.RSA.Encrypted.Aes.128.CBC.12345.txt")) { - new PrivateKeyFile(stream, "12345"); + _ = new PrivateKeyFile(stream, "12345"); } } @@ -293,7 +295,7 @@ public void Test_PrivateKey_RSA_AES_192_CBC() { using (var stream = GetData("Key.RSA.Encrypted.Aes.192.CBC.12345.txt")) { - new PrivateKeyFile(stream, "12345"); + _ = new PrivateKeyFile(stream, "12345"); } } @@ -304,7 +306,7 @@ public void Test_PrivateKey_RSA_AES_256_CBC() { using (var stream = GetData("Key.RSA.Encrypted.Aes.256.CBC.12345.txt")) { - new PrivateKeyFile(stream, "12345"); + _ = new PrivateKeyFile(stream, "12345"); } } @@ -315,7 +317,7 @@ public void Test_PrivateKey_RSA_DES_EDE3_CFB() { using (var stream = GetData("Key.RSA.Encrypted.Des.Ede3.CFB.1234567890.txt")) { - new PrivateKeyFile(stream, "1234567890"); + _ = new PrivateKeyFile(stream, "1234567890"); } } @@ -326,7 +328,7 @@ public void Test_PrivateKey_ECDSA() { using (var stream = GetData("Key.ECDSA.txt")) { - new PrivateKeyFile(stream); + _ = new PrivateKeyFile(stream); } } @@ -337,7 +339,7 @@ public void Test_PrivateKey_ECDSA384() { using (var stream = GetData("Key.ECDSA384.txt")) { - new PrivateKeyFile(stream); + _ = new PrivateKeyFile(stream); } } @@ -348,7 +350,7 @@ public void Test_PrivateKey_ECDSA521() { using (var stream = GetData("Key.ECDSA521.txt")) { - new PrivateKeyFile(stream); + _ = new PrivateKeyFile(stream); } } @@ -359,7 +361,7 @@ public void Test_PrivateKey_ECDSA_Encrypted() { using (var stream = GetData("Key.ECDSA.Encrypted.txt")) { - new PrivateKeyFile(stream, "12345"); + _ = new PrivateKeyFile(stream, "12345"); } } @@ -370,7 +372,7 @@ public void Test_PrivateKey_ECDSA384_Encrypted() { using (var stream = GetData("Key.ECDSA384.Encrypted.txt")) { - new PrivateKeyFile(stream, "12345"); + _ = new PrivateKeyFile(stream, "12345"); } } @@ -381,7 +383,7 @@ public void Test_PrivateKey_ECDSA521_Encrypted() { using (var stream = GetData("Key.ECDSA521.Encrypted.txt")) { - new PrivateKeyFile(stream, "12345"); + _ = new PrivateKeyFile(stream, "12345"); } } @@ -446,7 +448,7 @@ public void ConstructorWithFileNameAndPassphraseShouldThrowSshPassPhraseNullOrEm try { - new PrivateKeyFile(_temporaryFile, passphrase); + _ = new PrivateKeyFile(_temporaryFile, passphrase); Assert.Fail(); } catch (SshPassPhraseNullOrEmptyException ex) @@ -471,7 +473,7 @@ public void ConstructorWithFileNameAndPassphraseShouldThrowSshPassPhraseNullOrEm try { - new PrivateKeyFile(_temporaryFile, passphrase); + _ = new PrivateKeyFile(_temporaryFile, passphrase); Assert.Fail(); } catch (SshPassPhraseNullOrEmptyException ex) @@ -552,7 +554,7 @@ public void Test_PrivateKey_OPENSSH_ED25519() { using (var stream = GetData("Key.OPENSSH.ED25519.txt")) { - new PrivateKeyFile(stream); + _ = new PrivateKeyFile(stream); } } @@ -563,7 +565,7 @@ public void Test_PrivateKey_OPENSSH_ED25519_ENCRYPTED() { using (var stream = GetData("Key.OPENSSH.ED25519.Encrypted.txt")) { - new PrivateKeyFile(stream, "password"); + _ = new PrivateKeyFile(stream, "password"); } } @@ -574,7 +576,7 @@ public void Test_PrivateKey_OPENSSH_RSA() { using (var stream = GetData("Key.OPENSSH.RSA.txt")) { - new PrivateKeyFile(stream); + _ = new PrivateKeyFile(stream); } } @@ -585,7 +587,7 @@ public void Test_PrivateKey_OPENSSH_RSA_ENCRYPTED() { using (var stream = GetData("Key.OPENSSH.RSA.Encrypted.txt")) { - new PrivateKeyFile(stream, "12345"); + _ = new PrivateKeyFile(stream, "12345"); } } @@ -596,7 +598,7 @@ public void Test_PrivateKey_OPENSSH_ECDSA() { using (var stream = GetData("Key.OPENSSH.ECDSA.txt")) { - new PrivateKeyFile(stream); + _ = new PrivateKeyFile(stream); } } @@ -607,7 +609,7 @@ public void Test_PrivateKey_OPENSSH_ECDSA_ENCRYPTED() { using (var stream = GetData("Key.OPENSSH.ECDSA.Encrypted.txt")) { - new PrivateKeyFile(stream, "12345"); + _ = new PrivateKeyFile(stream, "12345"); } } @@ -618,7 +620,7 @@ public void Test_PrivateKey_OPENSSH_ECDSA384() { using (var stream = GetData("Key.OPENSSH.ECDSA384.txt")) { - new PrivateKeyFile(stream); + _ = new PrivateKeyFile(stream); } } @@ -629,7 +631,7 @@ public void Test_PrivateKey_OPENSSH_ECDSA384_ENCRYPTED() { using (var stream = GetData("Key.OPENSSH.ECDSA384.Encrypted.txt")) { - new PrivateKeyFile(stream, "12345"); + _ = new PrivateKeyFile(stream, "12345"); } } @@ -640,7 +642,7 @@ public void Test_PrivateKey_OPENSSH_ECDSA521() { using (var stream = GetData("Key.OPENSSH.ECDSA521.txt")) { - new PrivateKeyFile(stream); + _ = new PrivateKeyFile(stream); } } @@ -651,7 +653,7 @@ public void Test_PrivateKey_OPENSSH_ECDSA521_ENCRYPTED() { using (var stream = GetData("Key.OPENSSH.ECDSA521.Encrypted.txt")) { - new PrivateKeyFile(stream, "12345"); + _ = new PrivateKeyFile(stream, "12345"); } } diff --git a/src/Renci.SshNet.Tests/Classes/ScpClientTest.cs b/src/Renci.SshNet.Tests/Classes/ScpClientTest.cs index 038d952e0..a9af0c3dd 100644 --- a/src/Renci.SshNet.Tests/Classes/ScpClientTest.cs +++ b/src/Renci.SshNet.Tests/Classes/ScpClientTest.cs @@ -1,15 +1,15 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Renci.SshNet.Common; -using Renci.SshNet.Tests.Common; -using Renci.SshNet.Tests.Properties; -using System; +using System; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Text; -#if FEATURE_TPL using System.Threading.Tasks; -#endif // FEATURE_TPL + +using Microsoft.VisualStudio.TestTools.UnitTesting; + +using Renci.SshNet.Common; +using Renci.SshNet.Tests.Common; +using Renci.SshNet.Tests.Properties; namespace Renci.SshNet.Tests.Classes { @@ -34,7 +34,7 @@ public void Ctor_ConnectionInfo_Null() try { - new ScpClient(connectionInfo); + _ = new ScpClient(connectionInfo); Assert.Fail(); } catch (ArgumentNullException ex) @@ -230,10 +230,10 @@ public void Test_Scp_File_Upload_Download() { scp.Connect(); - string uploadedFileName = Path.GetTempFileName(); - string downloadedFileName = Path.GetTempFileName(); + var uploadedFileName = Path.GetTempFileName(); + var downloadedFileName = Path.GetTempFileName(); - this.CreateTestFile(uploadedFileName, 1); + CreateTestFile(uploadedFileName, 1); scp.Upload(new FileInfo(uploadedFileName), Path.GetFileName(uploadedFileName)); @@ -263,10 +263,10 @@ public void Test_Scp_Stream_Upload_Download() { scp.Connect(); - string uploadedFileName = Path.GetTempFileName(); - string downloadedFileName = Path.GetTempFileName(); + var uploadedFileName = Path.GetTempFileName(); + var downloadedFileName = Path.GetTempFileName(); - this.CreateTestFile(uploadedFileName, 1); + CreateTestFile(uploadedFileName, 1); // Calculate has value using (var stream = File.OpenRead(uploadedFileName)) @@ -303,10 +303,10 @@ public void Test_Scp_10MB_File_Upload_Download() { scp.Connect(); - string uploadedFileName = Path.GetTempFileName(); - string downloadedFileName = Path.GetTempFileName(); + var uploadedFileName = Path.GetTempFileName(); + var downloadedFileName = Path.GetTempFileName(); - this.CreateTestFile(uploadedFileName, 10); + CreateTestFile(uploadedFileName, 10); scp.Upload(new FileInfo(uploadedFileName), Path.GetFileName(uploadedFileName)); @@ -336,10 +336,10 @@ public void Test_Scp_10MB_Stream_Upload_Download() { scp.Connect(); - string uploadedFileName = Path.GetTempFileName(); - string downloadedFileName = Path.GetTempFileName(); + var uploadedFileName = Path.GetTempFileName(); + var downloadedFileName = Path.GetTempFileName(); - this.CreateTestFile(uploadedFileName, 10); + CreateTestFile(uploadedFileName, 10); // Calculate has value using (var stream = File.OpenRead(uploadedFileName)) @@ -378,15 +378,16 @@ public void Test_Scp_Directory_Upload_Download() var uploadDirectory = Directory.CreateDirectory(string.Format("{0}\\{1}", Path.GetTempPath(), Path.GetRandomFileName())); - for (int i = 0; i < 3; i++) + for (var i = 0; i < 3; i++) { - var subfolder = - Directory.CreateDirectory(string.Format(@"{0}\folder_{1}", uploadDirectory.FullName, i)); - for (int j = 0; j < 5; j++) + var subfolder = Directory.CreateDirectory(string.Format(@"{0}\folder_{1}", uploadDirectory.FullName, i)); + + for (var j = 0; j < 5; j++) { - this.CreateTestFile(string.Format(@"{0}\file_{1}", subfolder.FullName, j), 1); + CreateTestFile(string.Format(@"{0}\file_{1}", subfolder.FullName, j), 1); } - this.CreateTestFile(string.Format(@"{0}\file_{1}", uploadDirectory.FullName, i), 1); + + CreateTestFile(string.Format(@"{0}\file_{1}", uploadDirectory.FullName, i), 1); } scp.Upload(uploadDirectory, "uploaded_dir"); @@ -396,8 +397,8 @@ public void Test_Scp_Directory_Upload_Download() scp.Download("uploaded_dir", downloadDirectory); - var uploadedFiles = uploadDirectory.GetFiles("*.*", System.IO.SearchOption.AllDirectories); - var downloadFiles = downloadDirectory.GetFiles("*.*", System.IO.SearchOption.AllDirectories); + var uploadedFiles = uploadDirectory.GetFiles("*.*", SearchOption.AllDirectories); + var downloadFiles = downloadDirectory.GetFiles("*.*", SearchOption.AllDirectories); var result = from f1 in uploadedFiles from f2 in downloadFiles @@ -423,11 +424,10 @@ from f2 in downloadFiles public void OperationTimeoutTest() { ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value - ScpClient target = new ScpClient(connectionInfo); // TODO: Initialize to an appropriate value - TimeSpan expected = new TimeSpan(); // TODO: Initialize to an appropriate value - TimeSpan actual; + var target = new ScpClient(connectionInfo); // TODO: Initialize to an appropriate value + var expected = new TimeSpan(); // TODO: Initialize to an appropriate value target.OperationTimeout = expected; - actual = target.OperationTimeout; + var actual = target.OperationTimeout; Assert.AreEqual(expected, actual); Assert.Inconclusive("Verify the correctness of this test method."); } @@ -440,7 +440,7 @@ public void OperationTimeoutTest() public void BufferSizeTest() { ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value - ScpClient target = new ScpClient(connectionInfo); // TODO: Initialize to an appropriate value + var target = new ScpClient(connectionInfo); // TODO: Initialize to an appropriate value uint expected = 0; // TODO: Initialize to an appropriate value uint actual; target.BufferSize = expected; @@ -457,9 +457,9 @@ public void BufferSizeTest() public void UploadTest() { ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value - ScpClient target = new ScpClient(connectionInfo); // TODO: Initialize to an appropriate value + var target = new ScpClient(connectionInfo); // TODO: Initialize to an appropriate value DirectoryInfo directoryInfo = null; // TODO: Initialize to an appropriate value - string filename = string.Empty; // TODO: Initialize to an appropriate value + var filename = string.Empty; // TODO: Initialize to an appropriate value target.Upload(directoryInfo, filename); Assert.Inconclusive("A method that does not return a value cannot be verified."); } @@ -472,9 +472,9 @@ public void UploadTest() public void UploadTest1() { ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value - ScpClient target = new ScpClient(connectionInfo); // TODO: Initialize to an appropriate value + var target = new ScpClient(connectionInfo); // TODO: Initialize to an appropriate value FileInfo fileInfo = null; // TODO: Initialize to an appropriate value - string filename = string.Empty; // TODO: Initialize to an appropriate value + var filename = string.Empty; // TODO: Initialize to an appropriate value target.Upload(fileInfo, filename); Assert.Inconclusive("A method that does not return a value cannot be verified."); } @@ -487,9 +487,9 @@ public void UploadTest1() public void UploadTest2() { ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value - ScpClient target = new ScpClient(connectionInfo); // TODO: Initialize to an appropriate value + var target = new ScpClient(connectionInfo); // TODO: Initialize to an appropriate value Stream source = null; // TODO: Initialize to an appropriate value - string filename = string.Empty; // TODO: Initialize to an appropriate value + var filename = string.Empty; // TODO: Initialize to an appropriate value target.Upload(source, filename); Assert.Inconclusive("A method that does not return a value cannot be verified."); } @@ -502,8 +502,8 @@ public void UploadTest2() public void DownloadTest() { ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value - ScpClient target = new ScpClient(connectionInfo); // TODO: Initialize to an appropriate value - string directoryName = string.Empty; // TODO: Initialize to an appropriate value + var target = new ScpClient(connectionInfo); // TODO: Initialize to an appropriate value + var directoryName = string.Empty; // TODO: Initialize to an appropriate value DirectoryInfo directoryInfo = null; // TODO: Initialize to an appropriate value target.Download(directoryName, directoryInfo); Assert.Inconclusive("A method that does not return a value cannot be verified."); @@ -517,8 +517,8 @@ public void DownloadTest() public void DownloadTest1() { ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value - ScpClient target = new ScpClient(connectionInfo); // TODO: Initialize to an appropriate value - string filename = string.Empty; // TODO: Initialize to an appropriate value + var target = new ScpClient(connectionInfo); // TODO: Initialize to an appropriate value + var filename = string.Empty; // TODO: Initialize to an appropriate value FileInfo fileInfo = null; // TODO: Initialize to an appropriate value target.Download(filename, fileInfo); Assert.Inconclusive("A method that does not return a value cannot be verified."); @@ -532,14 +532,13 @@ public void DownloadTest1() public void DownloadTest2() { ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value - ScpClient target = new ScpClient(connectionInfo); // TODO: Initialize to an appropriate value - string filename = string.Empty; // TODO: Initialize to an appropriate value + var target = new ScpClient(connectionInfo); // TODO: Initialize to an appropriate value + var filename = string.Empty; // TODO: Initialize to an appropriate value Stream destination = null; // TODO: Initialize to an appropriate value target.Download(filename, destination); Assert.Inconclusive("A method that does not return a value cannot be verified."); } -#if FEATURE_TPL [TestMethod] [TestCategory("Scp")] [TestCategory("integration")] @@ -550,27 +549,25 @@ public void Test_Scp_File_20_Parallel_Upload_Download() scp.Connect(); var uploadFilenames = new string[20]; - for (int i = 0; i < uploadFilenames.Length; i++) + for (var i = 0; i < uploadFilenames.Length; i++) { uploadFilenames[i] = Path.GetTempFileName(); - this.CreateTestFile(uploadFilenames[i], 1); + CreateTestFile(uploadFilenames[i], 1); } - Parallel.ForEach(uploadFilenames, - (filename) => - { - scp.Upload(new FileInfo(filename), Path.GetFileName(filename)); - }); - - Parallel.ForEach(uploadFilenames, - (filename) => - { - scp.Download(Path.GetFileName(filename), new FileInfo(string.Format("{0}.down", filename))); - }); + _ = Parallel.ForEach(uploadFilenames, + filename => + { + scp.Upload(new FileInfo(filename), Path.GetFileName(filename)); + }); + _ = Parallel.ForEach(uploadFilenames, + filename => + { + scp.Download(Path.GetFileName(filename), new FileInfo(string.Format("{0}.down", filename))); + }); var result = from file in uploadFilenames - where - CalculateMD5(file) == CalculateMD5(string.Format("{0}.down", file)) + where CalculateMD5(file) == CalculateMD5(string.Format("{0}.down", file)) select file; scp.Disconnect(); @@ -590,13 +587,13 @@ public void Test_Scp_File_Upload_Download_Events() var uploadFilenames = new string[10]; - for (int i = 0; i < uploadFilenames.Length; i++) + for (var i = 0; i < uploadFilenames.Length; i++) { uploadFilenames[i] = Path.GetTempFileName(); - this.CreateTestFile(uploadFilenames[i], 1); + CreateTestFile(uploadFilenames[i], 1); } - var uploadedFiles = uploadFilenames.ToDictionary((filename) => Path.GetFileName(filename), (filename) => 0L); + var uploadedFiles = uploadFilenames.ToDictionary(Path.GetFileName, (filename) => 0L); var downloadedFiles = uploadFilenames.ToDictionary((filename) => string.Format("{0}.down", Path.GetFileName(filename)), (filename) => 0L); scp.Uploading += delegate (object sender, ScpUploadEventArgs e) @@ -609,23 +606,20 @@ public void Test_Scp_File_Upload_Download_Events() downloadedFiles[string.Format("{0}.down", e.Filename)] = e.Downloaded; }; - Parallel.ForEach(uploadFilenames, - (filename) => - { - scp.Upload(new FileInfo(filename), Path.GetFileName(filename)); - }); - - Parallel.ForEach(uploadFilenames, - (filename) => - { - scp.Download(Path.GetFileName(filename), new FileInfo(string.Format("{0}.down", filename))); - }); + _ = Parallel.ForEach(uploadFilenames, + filename => + { + scp.Upload(new FileInfo(filename), Path.GetFileName(filename)); + }); + _ = Parallel.ForEach(uploadFilenames, + filename => + { + scp.Download(Path.GetFileName(filename), new FileInfo(string.Format("{0}.down", filename))); + }); var result = from uf in uploadedFiles from df in downloadedFiles - where - string.Format("{0}.down", uf.Key) == df.Key - && uf.Value == df.Value + where string.Format("{0}.down", uf.Key) == df.Key && uf.Value == df.Value select uf; scp.Disconnect(); @@ -633,21 +627,31 @@ from df in downloadedFiles Assert.IsTrue(result.Count() == uploadFilenames.Length && uploadFilenames.Length == uploadedFiles.Count && uploadedFiles.Count == downloadedFiles.Count); } } -#endif // FEATURE_TPL protected static string CalculateMD5(string fileName) { using (var file = new FileStream(fileName, FileMode.Open)) { - var md5 = new MD5CryptoServiceProvider(); - byte[] retVal = md5.ComputeHash(file); +#if NET7_0_OR_GREATER + var hash = MD5.HashData(file); +#else +#if NET6_0 + var md5 = MD5.Create(); +#else + MD5 md5 = new MD5CryptoServiceProvider(); +#endif // NET6_0 + var hash = md5.ComputeHash(file); +#endif // NET7_0_OR_GREATER + file.Close(); var sb = new StringBuilder(); - for (var i = 0; i < retVal.Length; i++) + + for (var i = 0; i < hash.Length; i++) { - sb.Append(i.ToString("x2")); + _ = sb.Append(i.ToString("x2")); } + return sb.ToString(); } } @@ -657,7 +661,7 @@ private static void RemoveAllFiles() using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD)) { client.Connect(); - client.RunCommand("rm -rf *"); + _ = client.RunCommand("rm -rf *"); client.Disconnect(); } } @@ -678,4 +682,4 @@ private PrivateKeyFile GetDsaKey() } } } -} \ No newline at end of file +} diff --git a/src/Renci.SshNet.Tests/Classes/ScpClientTest_Download_PathAndDirectoryInfo_SendExecRequestReturnsFalse.cs b/src/Renci.SshNet.Tests/Classes/ScpClientTest_Download_PathAndDirectoryInfo_SendExecRequestReturnsFalse.cs index 620f3dd29..f64e039ee 100644 --- a/src/Renci.SshNet.Tests/Classes/ScpClientTest_Download_PathAndDirectoryInfo_SendExecRequestReturnsFalse.cs +++ b/src/Renci.SshNet.Tests/Classes/ScpClientTest_Download_PathAndDirectoryInfo_SendExecRequestReturnsFalse.cs @@ -34,18 +34,18 @@ protected override void SetupMocks() { var sequence = new MockSequence(); - _serviceFactoryMock.InSequence(sequence) + ServiceFactoryMock.InSequence(sequence) .Setup(p => p.CreateRemotePathDoubleQuoteTransformation()) .Returns(_remotePathTransformationMock.Object); - _serviceFactoryMock.InSequence(sequence) + ServiceFactoryMock.InSequence(sequence) .Setup(p => p.CreateSocketFactory()) - .Returns(_socketFactoryMock.Object); - _serviceFactoryMock.InSequence(sequence) - .Setup(p => p.CreateSession(_connectionInfo, _socketFactoryMock.Object)) - .Returns(_sessionMock.Object); - _sessionMock.InSequence(sequence).Setup(p => p.Connect()); - _serviceFactoryMock.InSequence(sequence).Setup(p => p.CreatePipeStream()).Returns(_pipeStreamMock.Object); - _sessionMock.InSequence(sequence).Setup(p => p.CreateChannelSession()).Returns(_channelSessionMock.Object); + .Returns(SocketFactoryMock.Object); + ServiceFactoryMock.InSequence(sequence) + .Setup(p => p.CreateSession(_connectionInfo, SocketFactoryMock.Object)) + .Returns(SessionMock.Object); + SessionMock.InSequence(sequence).Setup(p => p.Connect()); + ServiceFactoryMock.InSequence(sequence).Setup(p => p.CreatePipeStream()).Returns(_pipeStreamMock.Object); + SessionMock.InSequence(sequence).Setup(p => p.CreateChannelSession()).Returns(_channelSessionMock.Object); _channelSessionMock.InSequence(sequence).Setup(p => p.Open()); _remotePathTransformationMock.InSequence(sequence) .Setup(p => p.Transform(_path)) @@ -61,7 +61,7 @@ protected override void Arrange() { base.Arrange(); - _scpClient = new ScpClient(_connectionInfo, false, _serviceFactoryMock.Object); + _scpClient = new ScpClient(_connectionInfo, false, ServiceFactoryMock.Object); _scpClient.Uploading += (sender, args) => _uploadingRegister.Add(args); _scpClient.Connect(); } diff --git a/src/Renci.SshNet.Tests/Classes/ScpClientTest_Download_PathAndFileInfo_SendExecRequestReturnsFalse.cs b/src/Renci.SshNet.Tests/Classes/ScpClientTest_Download_PathAndFileInfo_SendExecRequestReturnsFalse.cs index f0ea9758a..08eba4ff8 100644 --- a/src/Renci.SshNet.Tests/Classes/ScpClientTest_Download_PathAndFileInfo_SendExecRequestReturnsFalse.cs +++ b/src/Renci.SshNet.Tests/Classes/ScpClientTest_Download_PathAndFileInfo_SendExecRequestReturnsFalse.cs @@ -34,18 +34,18 @@ protected override void SetupMocks() { var sequence = new MockSequence(); - _serviceFactoryMock.InSequence(sequence) + ServiceFactoryMock.InSequence(sequence) .Setup(p => p.CreateRemotePathDoubleQuoteTransformation()) .Returns(_remotePathTransformationMock.Object); - _serviceFactoryMock.InSequence(sequence) + ServiceFactoryMock.InSequence(sequence) .Setup(p => p.CreateSocketFactory()) - .Returns(_socketFactoryMock.Object); - _serviceFactoryMock.InSequence(sequence) - .Setup(p => p.CreateSession(_connectionInfo, _socketFactoryMock.Object)) - .Returns(_sessionMock.Object); - _sessionMock.InSequence(sequence).Setup(p => p.Connect()); - _serviceFactoryMock.InSequence(sequence).Setup(p => p.CreatePipeStream()).Returns(_pipeStreamMock.Object); - _sessionMock.InSequence(sequence).Setup(p => p.CreateChannelSession()).Returns(_channelSessionMock.Object); + .Returns(SocketFactoryMock.Object); + ServiceFactoryMock.InSequence(sequence) + .Setup(p => p.CreateSession(_connectionInfo, SocketFactoryMock.Object)) + .Returns(SessionMock.Object); + SessionMock.InSequence(sequence).Setup(p => p.Connect()); + ServiceFactoryMock.InSequence(sequence).Setup(p => p.CreatePipeStream()).Returns(_pipeStreamMock.Object); + SessionMock.InSequence(sequence).Setup(p => p.CreateChannelSession()).Returns(_channelSessionMock.Object); _channelSessionMock.InSequence(sequence).Setup(p => p.Open()); _remotePathTransformationMock.InSequence(sequence) .Setup(p => p.Transform(_path)) @@ -60,7 +60,7 @@ protected override void Arrange() { base.Arrange(); - _scpClient = new ScpClient(_connectionInfo, false, _serviceFactoryMock.Object); + _scpClient = new ScpClient(_connectionInfo, false, ServiceFactoryMock.Object); _scpClient.Uploading += (sender, args) => _uploadingRegister.Add(args); _scpClient.Connect(); } diff --git a/src/Renci.SshNet.Tests/Classes/ScpClientTest_Download_PathAndStream_SendExecRequestReturnsFalse.cs b/src/Renci.SshNet.Tests/Classes/ScpClientTest_Download_PathAndStream_SendExecRequestReturnsFalse.cs index bbb025209..143938c38 100644 --- a/src/Renci.SshNet.Tests/Classes/ScpClientTest_Download_PathAndStream_SendExecRequestReturnsFalse.cs +++ b/src/Renci.SshNet.Tests/Classes/ScpClientTest_Download_PathAndStream_SendExecRequestReturnsFalse.cs @@ -34,34 +34,42 @@ protected override void SetupMocks() { var sequence = new MockSequence(); - _serviceFactoryMock.InSequence(sequence) - .Setup(p => p.CreateRemotePathDoubleQuoteTransformation()) - .Returns(_remotePathTransformationMock.Object); - _serviceFactoryMock.InSequence(sequence) - .Setup(p => p.CreateSocketFactory()) - .Returns(_socketFactoryMock.Object); - _serviceFactoryMock.InSequence(sequence) - .Setup(p => p.CreateSession(_connectionInfo, _socketFactoryMock.Object)) - .Returns(_sessionMock.Object); - _sessionMock.InSequence(sequence).Setup(p => p.Connect()); - _serviceFactoryMock.InSequence(sequence).Setup(p => p.CreatePipeStream()).Returns(_pipeStreamMock.Object); - _sessionMock.InSequence(sequence).Setup(p => p.CreateChannelSession()).Returns(_channelSessionMock.Object); - _channelSessionMock.InSequence(sequence).Setup(p => p.Open()); - _remotePathTransformationMock.InSequence(sequence) - .Setup(p => p.Transform(_path)) - .Returns(_transformedPath); - _channelSessionMock.InSequence(sequence) - .Setup(p => p.SendExecRequest(string.Format("scp -f {0}", _transformedPath))) - .Returns(false); - _channelSessionMock.InSequence(sequence).Setup(p => p.Dispose()); - _pipeStreamMock.InSequence(sequence).Setup(p => p.Close()); + _ = ServiceFactoryMock.InSequence(sequence) + .Setup(p => p.CreateRemotePathDoubleQuoteTransformation()) + .Returns(_remotePathTransformationMock.Object); + _ = ServiceFactoryMock.InSequence(sequence) + .Setup(p => p.CreateSocketFactory()) + .Returns(SocketFactoryMock.Object); + _ = ServiceFactoryMock.InSequence(sequence) + .Setup(p => p.CreateSession(_connectionInfo, SocketFactoryMock.Object)) + .Returns(SessionMock.Object); + _ = SessionMock.InSequence(sequence) + .Setup(p => p.Connect()); + _ = ServiceFactoryMock.InSequence(sequence) + .Setup(p => p.CreatePipeStream()) + .Returns(_pipeStreamMock.Object); + _ = SessionMock.InSequence(sequence) + .Setup(p => p.CreateChannelSession()) + .Returns(_channelSessionMock.Object); + _ = _channelSessionMock.InSequence(sequence) + .Setup(p => p.Open()); + _ = _remotePathTransformationMock.InSequence(sequence) + .Setup(p => p.Transform(_path)) + .Returns(_transformedPath); + _ = _channelSessionMock.InSequence(sequence) + .Setup(p => p.SendExecRequest(string.Format("scp -f {0}", _transformedPath))) + .Returns(false); + _ = _channelSessionMock.InSequence(sequence) + .Setup(p => p.Dispose()); + _ = _pipeStreamMock.InSequence(sequence) + .Setup(p => p.Close()); } protected override void Arrange() { base.Arrange(); - _scpClient = new ScpClient(_connectionInfo, false, _serviceFactoryMock.Object); + _scpClient = new ScpClient(_connectionInfo, false, ServiceFactoryMock.Object); _scpClient.Uploading += (sender, args) => _uploadingRegister.Add(args); _scpClient.Connect(); } @@ -70,10 +78,7 @@ protected override void TearDown() { base.TearDown(); - if (_destination != null) - { - _destination.Dispose(); - } + _destination?.Dispose(); } protected override void Act() diff --git a/src/Renci.SshNet.Tests/Classes/ScpClientTest_Upload_DirectoryInfoAndPath_SendExecRequestReturnsFalse.cs b/src/Renci.SshNet.Tests/Classes/ScpClientTest_Upload_DirectoryInfoAndPath_SendExecRequestReturnsFalse.cs index f2521136a..71c1c0cd8 100644 --- a/src/Renci.SshNet.Tests/Classes/ScpClientTest_Upload_DirectoryInfoAndPath_SendExecRequestReturnsFalse.cs +++ b/src/Renci.SshNet.Tests/Classes/ScpClientTest_Upload_DirectoryInfoAndPath_SendExecRequestReturnsFalse.cs @@ -33,18 +33,18 @@ protected override void SetupMocks() { var sequence = new MockSequence(); - _serviceFactoryMock.InSequence(sequence) + ServiceFactoryMock.InSequence(sequence) .Setup(p => p.CreateRemotePathDoubleQuoteTransformation()) .Returns(_remotePathTransformationMock.Object); - _serviceFactoryMock.InSequence(sequence) + ServiceFactoryMock.InSequence(sequence) .Setup(p => p.CreateSocketFactory()) - .Returns(_socketFactoryMock.Object); - _serviceFactoryMock.InSequence(sequence) - .Setup(p => p.CreateSession(_connectionInfo, _socketFactoryMock.Object)) - .Returns(_sessionMock.Object); - _sessionMock.InSequence(sequence).Setup(p => p.Connect()); - _serviceFactoryMock.InSequence(sequence).Setup(p => p.CreatePipeStream()).Returns(_pipeStreamMock.Object); - _sessionMock.InSequence(sequence).Setup(p => p.CreateChannelSession()).Returns(_channelSessionMock.Object); + .Returns(SocketFactoryMock.Object); + ServiceFactoryMock.InSequence(sequence) + .Setup(p => p.CreateSession(_connectionInfo, SocketFactoryMock.Object)) + .Returns(SessionMock.Object); + SessionMock.InSequence(sequence).Setup(p => p.Connect()); + ServiceFactoryMock.InSequence(sequence).Setup(p => p.CreatePipeStream()).Returns(_pipeStreamMock.Object); + SessionMock.InSequence(sequence).Setup(p => p.CreateChannelSession()).Returns(_channelSessionMock.Object); _channelSessionMock.InSequence(sequence).Setup(p => p.Open()); _remotePathTransformationMock.InSequence(sequence) .Setup(p => p.Transform(_path)) @@ -60,7 +60,7 @@ protected override void Arrange() { base.Arrange(); - _scpClient = new ScpClient(_connectionInfo, false, _serviceFactoryMock.Object); + _scpClient = new ScpClient(_connectionInfo, false, ServiceFactoryMock.Object); _scpClient.Uploading += (sender, args) => _uploadingRegister.Add(args); _scpClient.Connect(); } diff --git a/src/Renci.SshNet.Tests/Classes/ScpClientTest_Upload_FileInfoAndPath_SendExecRequestReturnsFalse.cs b/src/Renci.SshNet.Tests/Classes/ScpClientTest_Upload_FileInfoAndPath_SendExecRequestReturnsFalse.cs index 782ffe977..288790d22 100644 --- a/src/Renci.SshNet.Tests/Classes/ScpClientTest_Upload_FileInfoAndPath_SendExecRequestReturnsFalse.cs +++ b/src/Renci.SshNet.Tests/Classes/ScpClientTest_Upload_FileInfoAndPath_SendExecRequestReturnsFalse.cs @@ -39,18 +39,18 @@ protected override void SetupMocks() { var sequence = new MockSequence(); - _serviceFactoryMock.InSequence(sequence) + ServiceFactoryMock.InSequence(sequence) .Setup(p => p.CreateRemotePathDoubleQuoteTransformation()) .Returns(_remotePathTransformationMock.Object); - _serviceFactoryMock.InSequence(sequence) + ServiceFactoryMock.InSequence(sequence) .Setup(p => p.CreateSocketFactory()) - .Returns(_socketFactoryMock.Object); - _serviceFactoryMock.InSequence(sequence) - .Setup(p => p.CreateSession(_connectionInfo, _socketFactoryMock.Object)) - .Returns(_sessionMock.Object); - _sessionMock.InSequence(sequence).Setup(p => p.Connect()); - _serviceFactoryMock.InSequence(sequence).Setup(p => p.CreatePipeStream()).Returns(_pipeStreamMock.Object); - _sessionMock.InSequence(sequence).Setup(p => p.CreateChannelSession()).Returns(_channelSessionMock.Object); + .Returns(SocketFactoryMock.Object); + ServiceFactoryMock.InSequence(sequence) + .Setup(p => p.CreateSession(_connectionInfo, SocketFactoryMock.Object)) + .Returns(SessionMock.Object); + SessionMock.InSequence(sequence).Setup(p => p.Connect()); + ServiceFactoryMock.InSequence(sequence).Setup(p => p.CreatePipeStream()).Returns(_pipeStreamMock.Object); + SessionMock.InSequence(sequence).Setup(p => p.CreateChannelSession()).Returns(_channelSessionMock.Object); _channelSessionMock.InSequence(sequence).Setup(p => p.Open()); _remotePathTransformationMock.InSequence(sequence) .Setup(p => p.Transform(_remoteDirectory)) @@ -66,7 +66,7 @@ protected override void Arrange() { base.Arrange(); - _scpClient = new ScpClient(_connectionInfo, false, _serviceFactoryMock.Object); + _scpClient = new ScpClient(_connectionInfo, false, ServiceFactoryMock.Object); _scpClient.Uploading += (sender, args) => _uploadingRegister.Add(args); _scpClient.Connect(); } diff --git a/src/Renci.SshNet.Tests/Classes/ScpClientTest_Upload_FileInfoAndPath_Success.cs b/src/Renci.SshNet.Tests/Classes/ScpClientTest_Upload_FileInfoAndPath_Success.cs index 6e31f4e2a..1df8d6ac2 100644 --- a/src/Renci.SshNet.Tests/Classes/ScpClientTest_Upload_FileInfoAndPath_Success.cs +++ b/src/Renci.SshNet.Tests/Classes/ScpClientTest_Upload_FileInfoAndPath_Success.cs @@ -46,52 +46,64 @@ protected override void SetupMocks() { var sequence = new MockSequence(); - _serviceFactoryMock.InSequence(sequence) - .Setup(p => p.CreateRemotePathDoubleQuoteTransformation()) - .Returns(_remotePathTransformationMock.Object); - _serviceFactoryMock.InSequence(sequence) - .Setup(p => p.CreateSocketFactory()) - .Returns(_socketFactoryMock.Object); - _serviceFactoryMock.InSequence(sequence) - .Setup(p => p.CreateSession(_connectionInfo, _socketFactoryMock.Object)) - .Returns(_sessionMock.Object); - _sessionMock.InSequence(sequence).Setup(p => p.Connect()); - _serviceFactoryMock.InSequence(sequence).Setup(p => p.CreatePipeStream()).Returns(_pipeStreamMock.Object); - _sessionMock.InSequence(sequence).Setup(p => p.CreateChannelSession()).Returns(_channelSessionMock.Object); - _channelSessionMock.InSequence(sequence).Setup(p => p.Open()); - _remotePathTransformationMock.InSequence(sequence) - .Setup(p => p.Transform(_remoteDirectory)) - .Returns(_transformedPath); - _channelSessionMock.InSequence(sequence) - .Setup(p => p.SendExecRequest(string.Format("scp -t -d {0}", _transformedPath))) - .Returns(true); - _pipeStreamMock.InSequence(sequence).Setup(p => p.ReadByte()).Returns(0); - _channelSessionMock.InSequence(sequence).Setup(p => p.SendData(It.IsAny())); - _pipeStreamMock.InSequence(sequence).Setup(p => p.ReadByte()).Returns(0); - _channelSessionMock.InSequence(sequence) - .Setup(p => p.SendData(It.Is(b => b.SequenceEqual( - CreateData(string.Format("C0644 {0} {1}\n", _fileInfo.Length, _remoteFile), - _connectionInfo.Encoding))))); - _pipeStreamMock.InSequence(sequence).Setup(p => p.ReadByte()).Returns(0); - _channelSessionMock.InSequence(sequence) - .Setup( - p => p.SendData(It.Is(b => b.SequenceEqual(_fileContent.Take(_bufferSize))), 0, _bufferSize)); - _channelSessionMock.InSequence(sequence) - .Setup( - p => p.SendData(It.Is(b => b.Take(0, _fileContent.Length - _bufferSize).SequenceEqual(_fileContent.Take(_bufferSize, _fileContent.Length - _bufferSize))), 0, _fileContent.Length - _bufferSize)); - _channelSessionMock.InSequence(sequence) - .Setup( - p => p.SendData(It.Is(b => b.SequenceEqual(new byte[] {0})))); - _pipeStreamMock.InSequence(sequence).Setup(p => p.ReadByte()).Returns(0); - _channelSessionMock.InSequence(sequence).Setup(p => p.Dispose()); - _pipeStreamMock.InSequence(sequence).Setup(p => p.Close()); + _ = ServiceFactoryMock.InSequence(sequence) + .Setup(p => p.CreateRemotePathDoubleQuoteTransformation()) + .Returns(_remotePathTransformationMock.Object); + _ = ServiceFactoryMock.InSequence(sequence) + .Setup(p => p.CreateSocketFactory()) + .Returns(SocketFactoryMock.Object); + _ = ServiceFactoryMock.InSequence(sequence) + .Setup(p => p.CreateSession(_connectionInfo, SocketFactoryMock.Object)) + .Returns(SessionMock.Object); + _ = SessionMock.InSequence(sequence) + .Setup(p => p.Connect()); + _ = ServiceFactoryMock.InSequence(sequence) + .Setup(p => p.CreatePipeStream()) + .Returns(_pipeStreamMock.Object); + _ = SessionMock.InSequence(sequence) + .Setup(p => p.CreateChannelSession()) + .Returns(_channelSessionMock.Object); + _ = _channelSessionMock.InSequence(sequence) + .Setup(p => p.Open()); + _ = _remotePathTransformationMock.InSequence(sequence) + .Setup(p => p.Transform(_remoteDirectory)) + .Returns(_transformedPath); + _ = _channelSessionMock.InSequence(sequence) + .Setup(p => p.SendExecRequest(string.Format("scp -t -d {0}", _transformedPath))) + .Returns(true); + _ = _pipeStreamMock.InSequence(sequence) + .Setup(p => p.ReadByte()) + .Returns(0); + _ = _channelSessionMock.InSequence(sequence) + .Setup(p => p.SendData(It.IsAny())); + _ = _pipeStreamMock.InSequence(sequence) + .Setup(p => p.ReadByte()) + .Returns(0); + _ = _channelSessionMock.InSequence(sequence) + .Setup(p => p.SendData(It.Is(b => b.SequenceEqual(CreateData(string.Format("C0644 {0} {1}\n", _fileInfo.Length, _remoteFile), _connectionInfo.Encoding))))); + _ = _pipeStreamMock.InSequence(sequence) + .Setup(p => p.ReadByte()) + .Returns(0); + _ = _channelSessionMock.InSequence(sequence) + .Setup(p => p.SendData(It.Is(b => b.SequenceEqual(_fileContent.Take(_bufferSize))), 0, _bufferSize)); + _ = _channelSessionMock.InSequence(sequence) + .Setup(p => p.SendData(It.Is(b => b.Take(0, _fileContent.Length - _bufferSize).SequenceEqual(_fileContent.Take(_bufferSize, _fileContent.Length - _bufferSize))), 0, _fileContent.Length - _bufferSize)); + _ = _channelSessionMock.InSequence(sequence) + .Setup(p => p.SendData(It.Is(b => b.SequenceEqual(new byte[] {0})))); + _ = _pipeStreamMock.InSequence(sequence) + .Setup(p => p.ReadByte()) + .Returns(0); + _ = _channelSessionMock.InSequence(sequence) + .Setup(p => p.Dispose()); + _ = _pipeStreamMock.InSequence(sequence) + .Setup(p => p.Close()); } protected override void Arrange() { base.Arrange(); - _scpClient = new ScpClient(_connectionInfo, false, _serviceFactoryMock.Object) + _scpClient = new ScpClient(_connectionInfo, false, ServiceFactoryMock.Object) { BufferSize = (uint) _bufferSize }; @@ -162,7 +174,10 @@ private static byte[] CreateContent(int length) var content = new byte[length]; for (var i = 0; i < length; i++) + { content[i] = (byte) random.Next(byte.MinValue, byte.MaxValue); + } + return content; } diff --git a/src/Renci.SshNet.Tests/Classes/ScpClientTest_Upload_StreamAndPath_SendExecRequestReturnsFalse.cs b/src/Renci.SshNet.Tests/Classes/ScpClientTest_Upload_StreamAndPath_SendExecRequestReturnsFalse.cs index f253a8da2..64fd8bc24 100644 --- a/src/Renci.SshNet.Tests/Classes/ScpClientTest_Upload_StreamAndPath_SendExecRequestReturnsFalse.cs +++ b/src/Renci.SshNet.Tests/Classes/ScpClientTest_Upload_StreamAndPath_SendExecRequestReturnsFalse.cs @@ -1,8 +1,11 @@ using System; using System.Collections.Generic; using System.IO; + using Microsoft.VisualStudio.TestTools.UnitTesting; + using Moq; + using Renci.SshNet.Common; namespace Renci.SshNet.Tests.Classes @@ -37,34 +40,42 @@ protected override void SetupMocks() { var sequence = new MockSequence(); - _serviceFactoryMock.InSequence(sequence) - .Setup(p => p.CreateRemotePathDoubleQuoteTransformation()) - .Returns(_remotePathTransformationMock.Object); - _serviceFactoryMock.InSequence(sequence) - .Setup(p => p.CreateSocketFactory()) - .Returns(_socketFactoryMock.Object); - _serviceFactoryMock.InSequence(sequence) - .Setup(p => p.CreateSession(_connectionInfo, _socketFactoryMock.Object)) - .Returns(_sessionMock.Object); - _sessionMock.InSequence(sequence).Setup(p => p.Connect()); - _serviceFactoryMock.InSequence(sequence).Setup(p => p.CreatePipeStream()).Returns(_pipeStreamMock.Object); - _sessionMock.InSequence(sequence).Setup(p => p.CreateChannelSession()).Returns(_channelSessionMock.Object); - _channelSessionMock.InSequence(sequence).Setup(p => p.Open()); - _remotePathTransformationMock.InSequence(sequence) - .Setup(p => p.Transform(_remoteDirectory)) - .Returns(_transformedPath); - _channelSessionMock.InSequence(sequence) - .Setup(p => p.SendExecRequest(string.Format("scp -t -d {0}", _transformedPath))) - .Returns(false); - _channelSessionMock.InSequence(sequence).Setup(p => p.Dispose()); - _pipeStreamMock.InSequence(sequence).Setup(p => p.Close()); + _ = ServiceFactoryMock.InSequence(sequence) + .Setup(p => p.CreateRemotePathDoubleQuoteTransformation()) + .Returns(_remotePathTransformationMock.Object); + _ = ServiceFactoryMock.InSequence(sequence) + .Setup(p => p.CreateSocketFactory()) + .Returns(SocketFactoryMock.Object); + _ = ServiceFactoryMock.InSequence(sequence) + .Setup(p => p.CreateSession(_connectionInfo, SocketFactoryMock.Object)) + .Returns(SessionMock.Object); + _ = SessionMock.InSequence(sequence) + .Setup(p => p.Connect()); + _ = ServiceFactoryMock.InSequence(sequence) + .Setup(p => p.CreatePipeStream()) + .Returns(_pipeStreamMock.Object); + _ = SessionMock.InSequence(sequence) + .Setup(p => p.CreateChannelSession()) + .Returns(_channelSessionMock.Object); + _ = _channelSessionMock.InSequence(sequence) + .Setup(p => p.Open()); + _ = _remotePathTransformationMock.InSequence(sequence) + .Setup(p => p.Transform(_remoteDirectory)) + .Returns(_transformedPath); + _ = _channelSessionMock.InSequence(sequence) + .Setup(p => p.SendExecRequest(string.Format("scp -t -d {0}", _transformedPath))) + .Returns(false); + _ = _channelSessionMock.InSequence(sequence) + .Setup(p => p.Dispose()); + _ = _pipeStreamMock.InSequence(sequence) + .Setup(p => p.Close()); } protected override void Arrange() { base.Arrange(); - _scpClient = new ScpClient(_connectionInfo, false, _serviceFactoryMock.Object); + _scpClient = new ScpClient(_connectionInfo, false, ServiceFactoryMock.Object); _scpClient.Uploading += (sender, args) => _uploadingRegister.Add(args); _scpClient.Connect(); } @@ -73,10 +84,7 @@ protected override void TearDown() { base.TearDown(); - if (_source != null) - { - _source.Dispose(); - } + _source?.Dispose(); } protected override void Act() diff --git a/src/Renci.SshNet.Tests/Classes/Security/Cryptography/Ciphers/BlowfishCipherTest.cs b/src/Renci.SshNet.Tests/Classes/Security/Cryptography/Ciphers/BlowfishCipherTest.cs index 1fd7b7d11..1c2d0aec8 100644 --- a/src/Renci.SshNet.Tests/Classes/Security/Cryptography/Ciphers/BlowfishCipherTest.cs +++ b/src/Renci.SshNet.Tests/Classes/Security/Cryptography/Ciphers/BlowfishCipherTest.cs @@ -20,11 +20,13 @@ public void Test_Cipher_Blowfish_128_CBC() var key = new byte[] { 0xe4, 0x94, 0xf9, 0xb1, 0x00, 0x4f, 0x16, 0x2a, 0x80, 0x11, 0xea, 0x73, 0x0d, 0xb9, 0xbf, 0x64 }; var iv = new byte[] { 0x74, 0x8b, 0x4f, 0xe6, 0xc1, 0x29, 0xb3, 0x54, 0xec, 0x77, 0x92, 0xf3, 0x15, 0xa0, 0x41, 0xa8 }; var output = new byte[] { 0x50, 0x49, 0xe0, 0xce, 0x98, 0x93, 0x8b, 0xec, 0x82, 0x7d, 0x14, 0x1b, 0x3e, 0xdc, 0xca, 0x63, 0xef, 0x36, 0x20, 0x67, 0x58, 0x63, 0x1f, 0x9c, 0xd2, 0x12, 0x6b, 0xca, 0xea, 0xd0, 0x78, 0x8b, 0x61, 0x50, 0x4f, 0xc4, 0x5b, 0x32, 0x91, 0xd6, 0x65, 0xcb, 0x74, 0xe5, 0x6e, 0xf5, 0xde, 0x14 }; - var testCipher = new Renci.SshNet.Security.Cryptography.Ciphers.BlowfishCipher(key, new Renci.SshNet.Security.Cryptography.Ciphers.Modes.CbcCipherMode(iv), null); + var testCipher = new BlowfishCipher(key, new CbcCipherMode(iv), null); var r = testCipher.Encrypt(input); if (!r.SequenceEqual(output)) + { Assert.Fail("Invalid encryption"); + } } [TestMethod] @@ -54,7 +56,7 @@ public void BlowfishCipherConstructorTest() byte[] key = null; // TODO: Initialize to an appropriate value CipherMode mode = null; // TODO: Initialize to an appropriate value CipherPadding padding = null; // TODO: Initialize to an appropriate value - BlowfishCipher target = new BlowfishCipher(key, mode, padding); + var target = new BlowfishCipher(key, mode, padding); Assert.Inconclusive("TODO: Implement code to verify target"); } @@ -68,15 +70,14 @@ public void DecryptBlockTest() byte[] key = null; // TODO: Initialize to an appropriate value CipherMode mode = null; // TODO: Initialize to an appropriate value CipherPadding padding = null; // TODO: Initialize to an appropriate value - BlowfishCipher target = new BlowfishCipher(key, mode, padding); // TODO: Initialize to an appropriate value + var target = new BlowfishCipher(key, mode, padding); // TODO: Initialize to an appropriate value byte[] inputBuffer = null; // TODO: Initialize to an appropriate value - int inputOffset = 0; // TODO: Initialize to an appropriate value - int inputCount = 0; // TODO: Initialize to an appropriate value + var inputOffset = 0; // TODO: Initialize to an appropriate value + var inputCount = 0; // TODO: Initialize to an appropriate value byte[] outputBuffer = null; // TODO: Initialize to an appropriate value - int outputOffset = 0; // TODO: Initialize to an appropriate value - int expected = 0; // TODO: Initialize to an appropriate value - int actual; - actual = target.DecryptBlock(inputBuffer, inputOffset, inputCount, outputBuffer, outputOffset); + var outputOffset = 0; // TODO: Initialize to an appropriate value + var expected = 0; // TODO: Initialize to an appropriate value + var actual = target.DecryptBlock(inputBuffer, inputOffset, inputCount, outputBuffer, outputOffset); Assert.AreEqual(expected, actual); Assert.Inconclusive("Verify the correctness of this test method."); } @@ -91,18 +92,17 @@ public void EncryptBlockTest() byte[] key = null; // TODO: Initialize to an appropriate value CipherMode mode = null; // TODO: Initialize to an appropriate value CipherPadding padding = null; // TODO: Initialize to an appropriate value - BlowfishCipher target = new BlowfishCipher(key, mode, padding); // TODO: Initialize to an appropriate value + var target = new BlowfishCipher(key, mode, padding); // TODO: Initialize to an appropriate value byte[] inputBuffer = null; // TODO: Initialize to an appropriate value - int inputOffset = 0; // TODO: Initialize to an appropriate value - int inputCount = 0; // TODO: Initialize to an appropriate value + var inputOffset = 0; // TODO: Initialize to an appropriate value + var inputCount = 0; // TODO: Initialize to an appropriate value byte[] outputBuffer = null; // TODO: Initialize to an appropriate value - int outputOffset = 0; // TODO: Initialize to an appropriate value - int expected = 0; // TODO: Initialize to an appropriate value - int actual; - actual = target.EncryptBlock(inputBuffer, inputOffset, inputCount, outputBuffer, outputOffset); + var outputOffset = 0; // TODO: Initialize to an appropriate value + var expected = 0; // TODO: Initialize to an appropriate value + var actual = target.EncryptBlock(inputBuffer, inputOffset, inputCount, outputBuffer, outputOffset); Assert.AreEqual(expected, actual); Assert.Inconclusive("Verify the correctness of this test method."); } } -} \ No newline at end of file +} diff --git a/src/Renci.SshNet.Tests/Classes/Security/Cryptography/Ciphers/TripleDesCipherTest.cs b/src/Renci.SshNet.Tests/Classes/Security/Cryptography/Ciphers/TripleDesCipherTest.cs index f791c9df5..5b4f97bac 100644 --- a/src/Renci.SshNet.Tests/Classes/Security/Cryptography/Ciphers/TripleDesCipherTest.cs +++ b/src/Renci.SshNet.Tests/Classes/Security/Cryptography/Ciphers/TripleDesCipherTest.cs @@ -1,9 +1,12 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using System.Linq; + +using Microsoft.VisualStudio.TestTools.UnitTesting; + using Renci.SshNet.Security.Cryptography.Ciphers; using Renci.SshNet.Security.Cryptography.Ciphers.Modes; using Renci.SshNet.Tests.Common; using Renci.SshNet.Tests.Properties; -using System.Linq; + namespace Renci.SshNet.Tests.Classes.Security.Cryptography.Ciphers { @@ -24,7 +27,9 @@ public void Test_Cipher_3DES_CBC() var r = testCipher.Encrypt(input); if (!r.SequenceEqual(output)) + { Assert.Fail("Invalid encryption"); + } } [TestMethod] @@ -103,4 +108,4 @@ public void EncryptBlockTest() Assert.Inconclusive("Verify the correctness of this test method."); } } -} \ No newline at end of file +} diff --git a/src/Renci.SshNet.Tests/Classes/Security/Cryptography/DsaDigitalSignatureTest.cs b/src/Renci.SshNet.Tests/Classes/Security/Cryptography/DsaDigitalSignatureTest.cs index 0d3423c95..947ec9c76 100644 --- a/src/Renci.SshNet.Tests/Classes/Security/Cryptography/DsaDigitalSignatureTest.cs +++ b/src/Renci.SshNet.Tests/Classes/Security/Cryptography/DsaDigitalSignatureTest.cs @@ -19,7 +19,7 @@ public class DsaDigitalSignatureTest : TestBase public void DsaDigitalSignatureConstructorTest() { DsaKey key = null; // TODO: Initialize to an appropriate value - DsaDigitalSignature target = new DsaDigitalSignature(key); + var target = new DsaDigitalSignature(key); Assert.Inconclusive("TODO: Implement code to verify target"); } @@ -31,7 +31,7 @@ public void DsaDigitalSignatureConstructorTest() public void DisposeTest() { DsaKey key = null; // TODO: Initialize to an appropriate value - DsaDigitalSignature target = new DsaDigitalSignature(key); // TODO: Initialize to an appropriate value + var target = new DsaDigitalSignature(key); // TODO: Initialize to an appropriate value target.Dispose(); Assert.Inconclusive("A method that does not return a value cannot be verified."); } @@ -44,11 +44,10 @@ public void DisposeTest() public void SignTest() { DsaKey key = null; // TODO: Initialize to an appropriate value - DsaDigitalSignature target = new DsaDigitalSignature(key); // TODO: Initialize to an appropriate value + var target = new DsaDigitalSignature(key); // TODO: Initialize to an appropriate value byte[] input = null; // TODO: Initialize to an appropriate value byte[] expected = null; // TODO: Initialize to an appropriate value - byte[] actual; - actual = target.Sign(input); + var actual = target.Sign(input); Assert.AreEqual(expected, actual); Assert.Inconclusive("Verify the correctness of this test method."); } @@ -61,14 +60,13 @@ public void SignTest() public void VerifyTest() { DsaKey key = null; // TODO: Initialize to an appropriate value - DsaDigitalSignature target = new DsaDigitalSignature(key); // TODO: Initialize to an appropriate value + var target = new DsaDigitalSignature(key); // TODO: Initialize to an appropriate value byte[] input = null; // TODO: Initialize to an appropriate value byte[] signature = null; // TODO: Initialize to an appropriate value - bool expected = false; // TODO: Initialize to an appropriate value - bool actual; - actual = target.Verify(input, signature); + var expected = false; // TODO: Initialize to an appropriate value + var actual = target.Verify(input, signature); Assert.AreEqual(expected, actual); Assert.Inconclusive("Verify the correctness of this test method."); } } -} \ No newline at end of file +} diff --git a/src/Renci.SshNet.Tests/Classes/Security/Cryptography/SymmetricCipherTest.cs b/src/Renci.SshNet.Tests/Classes/Security/Cryptography/SymmetricCipherTest.cs index 8dce88815..92f9da374 100644 --- a/src/Renci.SshNet.Tests/Classes/Security/Cryptography/SymmetricCipherTest.cs +++ b/src/Renci.SshNet.Tests/Classes/Security/Cryptography/SymmetricCipherTest.cs @@ -1,6 +1,6 @@ -using Renci.SshNet.Security.Cryptography; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using System; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +using Renci.SshNet.Security.Cryptography; using Renci.SshNet.Tests.Common; namespace Renci.SshNet.Tests @@ -26,15 +26,14 @@ internal virtual SymmetricCipher CreateSymmetricCipher() [Ignore] // placeholder for actual test public void DecryptBlockTest() { - SymmetricCipher target = CreateSymmetricCipher(); // TODO: Initialize to an appropriate value + var target = CreateSymmetricCipher(); // TODO: Initialize to an appropriate value byte[] inputBuffer = null; // TODO: Initialize to an appropriate value - int inputOffset = 0; // TODO: Initialize to an appropriate value - int inputCount = 0; // TODO: Initialize to an appropriate value + var inputOffset = 0; // TODO: Initialize to an appropriate value + var inputCount = 0; // TODO: Initialize to an appropriate value byte[] outputBuffer = null; // TODO: Initialize to an appropriate value - int outputOffset = 0; // TODO: Initialize to an appropriate value - int expected = 0; // TODO: Initialize to an appropriate value - int actual; - actual = target.DecryptBlock(inputBuffer, inputOffset, inputCount, outputBuffer, outputOffset); + var outputOffset = 0; // TODO: Initialize to an appropriate value + var expected = 0; // TODO: Initialize to an appropriate value + var actual = target.DecryptBlock(inputBuffer, inputOffset, inputCount, outputBuffer, outputOffset); Assert.AreEqual(expected, actual); Assert.Inconclusive("Verify the correctness of this test method."); } @@ -46,15 +45,14 @@ public void DecryptBlockTest() [Ignore] // placeholder for actual test public void EncryptBlockTest() { - SymmetricCipher target = CreateSymmetricCipher(); // TODO: Initialize to an appropriate value + var target = CreateSymmetricCipher(); // TODO: Initialize to an appropriate value byte[] inputBuffer = null; // TODO: Initialize to an appropriate value - int inputOffset = 0; // TODO: Initialize to an appropriate value - int inputCount = 0; // TODO: Initialize to an appropriate value + var inputOffset = 0; // TODO: Initialize to an appropriate value + var inputCount = 0; // TODO: Initialize to an appropriate value byte[] outputBuffer = null; // TODO: Initialize to an appropriate value - int outputOffset = 0; // TODO: Initialize to an appropriate value - int expected = 0; // TODO: Initialize to an appropriate value - int actual; - actual = target.EncryptBlock(inputBuffer, inputOffset, inputCount, outputBuffer, outputOffset); + var outputOffset = 0; // TODO: Initialize to an appropriate value + var expected = 0; // TODO: Initialize to an appropriate value + var actual = target.EncryptBlock(inputBuffer, inputOffset, inputCount, outputBuffer, outputOffset); Assert.AreEqual(expected, actual); Assert.Inconclusive("Verify the correctness of this test method."); } diff --git a/src/Renci.SshNet.Tests/Classes/Security/KeyExchangeDiffieHellmanGroup14Sha256Test.cs b/src/Renci.SshNet.Tests/Classes/Security/KeyExchangeDiffieHellmanGroup14Sha256Test.cs index 744a434ff..915e4b8f7 100644 --- a/src/Renci.SshNet.Tests/Classes/Security/KeyExchangeDiffieHellmanGroup14Sha256Test.cs +++ b/src/Renci.SshNet.Tests/Classes/Security/KeyExchangeDiffieHellmanGroup14Sha256Test.cs @@ -1,8 +1,8 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; + using Renci.SshNet.Common; using Renci.SshNet.Security; using Renci.SshNet.Tests.Common; -using System.Text; namespace Renci.SshNet.Tests.Classes.Security { @@ -58,4 +58,4 @@ public void NameShouldBeDiffieHellmanGroup14Sha256() Assert.AreEqual("diffie-hellman-group14-sha256", _group14.Name); } } -} \ No newline at end of file +} diff --git a/src/Renci.SshNet.Tests/Classes/Security/KeyExchangeTest.cs b/src/Renci.SshNet.Tests/Classes/Security/KeyExchangeTest.cs index 839394e6e..a288292ee 100644 --- a/src/Renci.SshNet.Tests/Classes/Security/KeyExchangeTest.cs +++ b/src/Renci.SshNet.Tests/Classes/Security/KeyExchangeTest.cs @@ -1,6 +1,6 @@ -using Renci.SshNet.Security; +using Microsoft.VisualStudio.TestTools.UnitTesting; + using Renci.SshNet.Tests.Common; -using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Renci.SshNet.Tests { diff --git a/src/Renci.SshNet.Tests/Classes/SessionTest.HttpProxy.cs b/src/Renci.SshNet.Tests/Classes/SessionTest.HttpProxy.cs deleted file mode 100644 index 03ce2491c..000000000 --- a/src/Renci.SshNet.Tests/Classes/SessionTest.HttpProxy.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System; -using System.Net; -using System.Linq; -using System.Text; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Renci.SshNet.Common; -using Renci.SshNet.Tests.Common; -using Renci.SshNet.Connection; - -namespace Renci.SshNet.Tests.Classes -{ - public partial class SessionTest - { - private static ConnectionInfo CreateConnectionInfoWithHttpProxy(IPEndPoint proxyEndPoint, IPEndPoint serverEndPoint, string proxyUserName) - { - return new ConnectionInfo( - serverEndPoint.Address.ToString(), - serverEndPoint.Port, - "eric", - ProxyTypes.Http, - proxyEndPoint.Address.ToString(), - proxyEndPoint.Port, - proxyUserName, - "proxypwd", - new NoneAuthenticationMethod("eric")); - } - - private static string CreateProxyAuthorizationHeader(ConnectionInfo connectionInfo) - { - return string.Format("Proxy-Authorization: Basic {0}", - Convert.ToBase64String( - Encoding.ASCII.GetBytes(string.Format("{0}:{1}", connectionInfo.ProxyUsername, - connectionInfo.ProxyPassword)))); - } - } -} diff --git a/src/Renci.SshNet.Tests/Classes/SessionTest.cs b/src/Renci.SshNet.Tests/Classes/SessionTest.cs index 972757e40..bfb9a4288 100644 --- a/src/Renci.SshNet.Tests/Classes/SessionTest.cs +++ b/src/Renci.SshNet.Tests/Classes/SessionTest.cs @@ -1,7 +1,10 @@ using System; using System.Net; + using Microsoft.VisualStudio.TestTools.UnitTesting; + using Moq; + using Renci.SshNet.Connection; using Renci.SshNet.Tests.Common; @@ -15,8 +18,6 @@ public partial class SessionTest : TestBase { private Mock _serviceFactoryMock; private Mock _socketFactoryMock; - private Mock _connectorMock; - private Mock _protocolVersionExchangeMock; protected override void OnInit() { @@ -24,8 +25,6 @@ protected override void OnInit() _serviceFactoryMock = new Mock(MockBehavior.Strict); _socketFactoryMock = new Mock(MockBehavior.Strict); - _connectorMock = new Mock(MockBehavior.Strict); - _protocolVersionExchangeMock = new Mock(MockBehavior.Strict); } [TestMethod] @@ -35,7 +34,7 @@ public void ConstructorShouldThrowArgumentNullExceptionWhenConnectionInfoIsNull( try { - new Session(connectionInfo, _serviceFactoryMock.Object, _socketFactoryMock.Object); + _ = new Session(connectionInfo, _serviceFactoryMock.Object, _socketFactoryMock.Object); Assert.Fail(); } catch (ArgumentNullException ex) @@ -54,7 +53,7 @@ public void ConstructorShouldThrowArgumentNullExceptionWhenServiceFactoryIsNull( try { - new Session(connectionInfo, serviceFactory, _socketFactoryMock.Object); + _ = new Session(connectionInfo, serviceFactory, _socketFactoryMock.Object); Assert.Fail(); } catch (ArgumentNullException ex) @@ -73,7 +72,7 @@ public void ConstructorShouldThrowArgumentNullExceptionWhenSocketFactoryIsNull() try { - new Session(connectionInfo, _serviceFactoryMock.Object, socketFactory); + _ = new Session(connectionInfo, _serviceFactoryMock.Object, socketFactory); Assert.Fail(); } catch (ArgumentNullException ex) @@ -85,13 +84,10 @@ public void ConstructorShouldThrowArgumentNullExceptionWhenSocketFactoryIsNull() private static ConnectionInfo CreateConnectionInfo(IPEndPoint serverEndPoint, TimeSpan timeout) { - var connectionInfo = new ConnectionInfo( - serverEndPoint.Address.ToString(), - serverEndPoint.Port, - "eric", - new NoneAuthenticationMethod("eric")); - connectionInfo.Timeout = timeout; - return connectionInfo; + return new ConnectionInfo(serverEndPoint.Address.ToString(), serverEndPoint.Port, "eric", new NoneAuthenticationMethod("eric")) + { + Timeout = timeout + }; } } -} \ No newline at end of file +} diff --git a/src/Renci.SshNet.Tests/Classes/SessionTestBase.cs b/src/Renci.SshNet.Tests/Classes/SessionTestBase.cs index cbe69e2af..8b3cce37f 100644 --- a/src/Renci.SshNet.Tests/Classes/SessionTestBase.cs +++ b/src/Renci.SshNet.Tests/Classes/SessionTestBase.cs @@ -6,15 +6,15 @@ namespace Renci.SshNet.Tests.Classes { public abstract class SessionTestBase : TripleATestBase { - internal Mock _serviceFactoryMock { get; private set; } - internal Mock _socketFactoryMock { get; private set; } - internal Mock _connectorMock { get; private set; } + internal Mock ServiceFactoryMock { get; private set; } + internal Mock SocketFactoryMock { get; private set; } + internal Mock ConnectorMock { get; private set; } protected virtual void CreateMocks() { - _serviceFactoryMock = new Mock(MockBehavior.Strict); - _socketFactoryMock = new Mock(MockBehavior.Strict); - _connectorMock = new Mock(MockBehavior.Strict); + ServiceFactoryMock = new Mock(MockBehavior.Strict); + SocketFactoryMock = new Mock(MockBehavior.Strict); + ConnectorMock = new Mock(MockBehavior.Strict); } protected virtual void SetupData() diff --git a/src/Renci.SshNet.Tests/Classes/SessionTest_ConnectToServerFails.cs b/src/Renci.SshNet.Tests/Classes/SessionTest_ConnectToServerFails.cs index df19c8ec8..16cfbb1ed 100644 --- a/src/Renci.SshNet.Tests/Classes/SessionTest_ConnectToServerFails.cs +++ b/src/Renci.SshNet.Tests/Classes/SessionTest_ConnectToServerFails.cs @@ -1,7 +1,9 @@ using System; using System.Net; using System.Threading; + using Microsoft.VisualStudio.TestTools.UnitTesting; + using Renci.SshNet.Common; using Renci.SshNet.Messages.Transport; @@ -21,7 +23,7 @@ protected override void SetupData() var serverEndPoint = new IPEndPoint(IPAddress.Loopback, 8122); _connectionInfo = CreateConnectionInfo(serverEndPoint, TimeSpan.FromSeconds(5)); - _session = new Session(_connectionInfo, _serviceFactoryMock.Object, _socketFactoryMock.Object); + _session = new Session(_connectionInfo, ServiceFactoryMock.Object, SocketFactoryMock.Object); _connectException = new SshConnectionException(); } @@ -29,10 +31,10 @@ protected override void SetupMocks() { base.SetupMocks(); - _serviceFactoryMock.Setup(p => p.CreateConnector(_connectionInfo, _socketFactoryMock.Object)) - .Returns(_connectorMock.Object); - _connectorMock.Setup(p => p.Connect(_connectionInfo)) - .Throws(_connectException); + _ = ServiceFactoryMock.Setup(p => p.CreateConnector(_connectionInfo, SocketFactoryMock.Object)) + .Returns(ConnectorMock.Object); + _ = ConnectorMock.Setup(p => p.Connect(_connectionInfo)) + .Throws(_connectException); } protected override void Act() @@ -163,9 +165,8 @@ public void ISession_TryWait_WaitHandleAndTimeoutAndException_ShouldReturnDiscon { var session = (ISession)_session; var waitHandle = new ManualResetEvent(false); - Exception exception; - var result = session.TryWait(waitHandle, Session.InfiniteTimeSpan, out exception); + var result = session.TryWait(waitHandle, Session.InfiniteTimeSpan, out var exception); Assert.AreEqual(WaitResult.Disconnected, result); Assert.IsNull(exception); @@ -253,13 +254,10 @@ public void ISession_WaitOnHandle_WaitHandleAndTimeout_ShouldThrowArgumentNullEx private static ConnectionInfo CreateConnectionInfo(IPEndPoint serverEndPoint, TimeSpan timeout) { - var connectionInfo = new ConnectionInfo( - serverEndPoint.Address.ToString(), - serverEndPoint.Port, - "eric", - new NoneAuthenticationMethod("eric")); - connectionInfo.Timeout = timeout; - return connectionInfo; + return new ConnectionInfo(serverEndPoint.Address.ToString(), serverEndPoint.Port, "eric", new NoneAuthenticationMethod("eric")) + { + Timeout = timeout + }; } } -} \ No newline at end of file +} diff --git a/src/Renci.SshNet.Tests/Classes/SessionTest_Connected.cs b/src/Renci.SshNet.Tests/Classes/SessionTest_Connected.cs index fa36aed5e..f841926b4 100644 --- a/src/Renci.SshNet.Tests/Classes/SessionTest_Connected.cs +++ b/src/Renci.SshNet.Tests/Classes/SessionTest_Connected.cs @@ -197,7 +197,7 @@ public void ISession_TryWait_WaitHandleAndTimeout_ShouldThrowArgumentNullExcepti try { - session.TryWait(waitHandle, Session.InfiniteTimeSpan); + _ = session.TryWait(waitHandle, Session.InfiniteTimeSpan); Assert.Fail(); } catch (ArgumentNullException ex) @@ -212,9 +212,8 @@ public void ISession_TryWait_WaitHandleAndTimeoutAndException_ShouldReturnSucces { var session = (ISession) Session; var waitHandle = new ManualResetEvent(true); - Exception exception; - var result = session.TryWait(waitHandle, TimeSpan.FromMilliseconds(0), out exception); + var result = session.TryWait(waitHandle, TimeSpan.FromMilliseconds(0), out var exception); Assert.AreEqual(WaitResult.Success, result); Assert.IsNull(exception); @@ -225,9 +224,8 @@ public void ISession_TryWait_WaitHandleAndTimeoutAndException_ShouldReturnTimedO { var session = (ISession) Session; var waitHandle = new ManualResetEvent(false); - Exception exception; - var result = session.TryWait(waitHandle, TimeSpan.FromMilliseconds(0), out exception); + var result = session.TryWait(waitHandle, TimeSpan.FromMilliseconds(0), out var exception); Assert.AreEqual(WaitResult.TimedOut, result); Assert.IsNull(exception); @@ -272,4 +270,4 @@ public void ConnectorOnConnectorShouldHaveBeenInvokedOnce() ConnectorMock.Verify(p => p.Connect(ConnectionInfo), Times.Once()); } } -} \ No newline at end of file +} diff --git a/src/Renci.SshNet.Tests/Classes/SessionTest_ConnectedBase.cs b/src/Renci.SshNet.Tests/Classes/SessionTest_ConnectedBase.cs index a920b1906..8f4bed7c0 100644 --- a/src/Renci.SshNet.Tests/Classes/SessionTest_ConnectedBase.cs +++ b/src/Renci.SshNet.Tests/Classes/SessionTest_ConnectedBase.cs @@ -4,9 +4,11 @@ using System.Net; using System.Net.Sockets; using System.Security.Cryptography; -using System.Text; + using Microsoft.VisualStudio.TestTools.UnitTesting; + using Moq; + using Renci.SshNet.Common; using Renci.SshNet.Compression; using Renci.SshNet.Connection; @@ -111,11 +113,13 @@ protected virtual void SetupData() { var newKeysMessage = new NewKeysMessage(); var newKeys = newKeysMessage.GetPacket(8, null); - ServerSocket.Send(newKeys, 4, newKeys.Length - 4, SocketFlags.None); + _ = ServerSocket.Send(newKeys, 4, newKeys.Length - 4, SocketFlags.None); }; - ServerListener = new AsyncSocketListener(_serverEndPoint); - ServerListener.ShutdownRemoteCommunicationSocket = false; + ServerListener = new AsyncSocketListener(_serverEndPoint) + { + ShutdownRemoteCommunicationSocket = false + }; ServerListener.Connected += socket => { ServerSocket = socket; @@ -137,7 +141,7 @@ protected virtual void SetupData() ServerHostKeyAlgorithms = new string[0] }; var keyExchangeInit = keyExchangeInitMessage.GetPacket(8, null); - ServerSocket.Send(keyExchangeInit, 4, keyExchangeInit.Length - 4, SocketFlags.None); + _ = ServerSocket.Send(keyExchangeInit, 4, keyExchangeInit.Length - 4, SocketFlags.None); }; ServerListener.BytesReceived += (received, socket) => { @@ -147,7 +151,7 @@ protected virtual void SetupData() { var serviceAcceptMessage = ServiceAcceptMessageBuilder.Create(ServiceName.UserAuthentication) .Build(); - ServerSocket.Send(serviceAcceptMessage, 0, serviceAcceptMessage.Length, SocketFlags.None); + _ = ServerSocket.Send(serviceAcceptMessage, 0, serviceAcceptMessage.Length, SocketFlags.None); _authenticationStarted = true; } @@ -169,32 +173,37 @@ private void CreateMocks() private void SetupMocks() { - ServiceFactoryMock.Setup(p => p.CreateConnector(ConnectionInfo, SocketFactoryMock.Object)) - .Returns(ConnectorMock.Object); - ConnectorMock.Setup(p => p.Connect(ConnectionInfo)) - .Returns(ClientSocket); - ServiceFactoryMock.Setup(p => p.CreateProtocolVersionExchange()) - .Returns(_protocolVersionExchangeMock.Object); - _protocolVersionExchangeMock.Setup(p => p.Start(Session.ClientVersion, ClientSocket, ConnectionInfo.Timeout)) - .Returns(ServerIdentification); - - ServiceFactoryMock.Setup( - p => - p.CreateKeyExchange(ConnectionInfo.KeyExchangeAlgorithms, new[] { _keyExchangeAlgorithm })).Returns(_keyExchangeMock.Object); - _keyExchangeMock.Setup(p => p.Name).Returns(_keyExchangeAlgorithm); - _keyExchangeMock.Setup(p => p.Start(Session, It.IsAny())); - _keyExchangeMock.Setup(p => p.ExchangeHash).Returns(SessionId); - _keyExchangeMock.Setup(p => p.CreateServerCipher()).Returns((Cipher) null); - _keyExchangeMock.Setup(p => p.CreateClientCipher()).Returns((Cipher) null); - _keyExchangeMock.Setup(p => p.CreateServerHash()).Returns((HashAlgorithm) null); - _keyExchangeMock.Setup(p => p.CreateClientHash()).Returns((HashAlgorithm) null); - _keyExchangeMock.Setup(p => p.CreateCompressor()).Returns((Compressor) null); - _keyExchangeMock.Setup(p => p.CreateDecompressor()).Returns((Compressor) null); - _keyExchangeMock.Setup(p => p.Dispose()); - ServiceFactoryMock.Setup(p => p.CreateClientAuthentication()) - .Callback(ClientAuthentication_Callback) - .Returns(_clientAuthenticationMock.Object); - _clientAuthenticationMock.Setup(p => p.Authenticate(ConnectionInfo, Session)); + _ = ServiceFactoryMock.Setup(p => p.CreateConnector(ConnectionInfo, SocketFactoryMock.Object)) + .Returns(ConnectorMock.Object); + _ = ConnectorMock.Setup(p => p.Connect(ConnectionInfo)) + .Returns(ClientSocket); + _ = ServiceFactoryMock.Setup(p => p.CreateProtocolVersionExchange()) + .Returns(_protocolVersionExchangeMock.Object); + _ = _protocolVersionExchangeMock.Setup(p => p.Start(Session.ClientVersion, ClientSocket, ConnectionInfo.Timeout)) + .Returns(ServerIdentification); + _ = ServiceFactoryMock.Setup(p => p.CreateKeyExchange(ConnectionInfo.KeyExchangeAlgorithms, new[] { _keyExchangeAlgorithm })).Returns(_keyExchangeMock.Object); + _ = _keyExchangeMock.Setup(p => p.Name) + .Returns(_keyExchangeAlgorithm); + _ = _keyExchangeMock.Setup(p => p.Start(Session, It.IsAny())); + _ = _keyExchangeMock.Setup(p => p.ExchangeHash) + .Returns(SessionId); + _ = _keyExchangeMock.Setup(p => p.CreateServerCipher()) + .Returns((Cipher) null); + _ = _keyExchangeMock.Setup(p => p.CreateClientCipher()) + .Returns((Cipher) null); + _ = _keyExchangeMock.Setup(p => p.CreateServerHash()) + .Returns((HashAlgorithm) null); + _ = _keyExchangeMock.Setup(p => p.CreateClientHash()) + .Returns((HashAlgorithm) null); + _ = _keyExchangeMock.Setup(p => p.CreateCompressor()) + .Returns((Compressor) null); + _ = _keyExchangeMock.Setup(p => p.CreateDecompressor()) + .Returns((Compressor) null); + _ = _keyExchangeMock.Setup(p => p.Dispose()); + _ = ServiceFactoryMock.Setup(p => p.CreateClientAuthentication()) + .Callback(ClientAuthentication_Callback) + .Returns(_clientAuthenticationMock.Object); + _ = _clientAuthenticationMock.Setup(p => p.Authenticate(ConnectionInfo, Session)); } protected void Arrange() diff --git a/src/Renci.SshNet.Tests/Classes/SessionTest_Connected_ConnectionReset.cs b/src/Renci.SshNet.Tests/Classes/SessionTest_Connected_ConnectionReset.cs index f17209beb..fb49e66e8 100644 --- a/src/Renci.SshNet.Tests/Classes/SessionTest_Connected_ConnectionReset.cs +++ b/src/Renci.SshNet.Tests/Classes/SessionTest_Connected_ConnectionReset.cs @@ -1,8 +1,8 @@ -using System; -using System.Diagnostics; -using System.Net.Sockets; +using System.Diagnostics; using System.Threading; + using Microsoft.VisualStudio.TestTools.UnitTesting; + using Renci.SshNet.Common; using Renci.SshNet.Messages.Transport; using Renci.SshNet.Tests.Common; @@ -187,12 +187,11 @@ public void ISession_TryWait_WaitHandleAndTimeoutAndException_ShouldReturnDiscon { var session = (ISession) Session; var waitHandle = new ManualResetEvent(false); - Exception exception; - var result = session.TryWait(waitHandle, Session.InfiniteTimeSpan, out exception); + var result = session.TryWait(waitHandle, Session.InfiniteTimeSpan, out var exception); Assert.AreEqual(WaitResult.Disconnected, result); Assert.IsNull(exception); } } -} \ No newline at end of file +} diff --git a/src/Renci.SshNet.Tests/Classes/SessionTest_Connected_Disconnect.cs b/src/Renci.SshNet.Tests/Classes/SessionTest_Connected_Disconnect.cs index eacb27c39..3b0c9b554 100644 --- a/src/Renci.SshNet.Tests/Classes/SessionTest_Connected_Disconnect.cs +++ b/src/Renci.SshNet.Tests/Classes/SessionTest_Connected_Disconnect.cs @@ -1,8 +1,9 @@ -using System; -using System.Diagnostics; +using System.Diagnostics; using System.Net.Sockets; using System.Threading; + using Microsoft.VisualStudio.TestTools.UnitTesting; + using Renci.SshNet.Common; using Renci.SshNet.Messages.Transport; using Renci.SshNet.Tests.Common; @@ -100,7 +101,7 @@ public void ISession_MessageListenerCompletedShouldBeSignaled() Assert.IsTrue(session.MessageListenerCompleted.WaitOne()); } - [TestMethodAttribute] + [TestMethod] public void ISession_SendMessageShouldThrowSshConnectionException() { var session = (ISession) Session; @@ -182,9 +183,8 @@ public void ISession_TryWait_WaitHandleAndTimeoutAndException_ShouldReturnDiscon { var session = (ISession) Session; var waitHandle = new ManualResetEvent(false); - Exception exception; - var result = session.TryWait(waitHandle, Session.InfiniteTimeSpan, out exception); + var result = session.TryWait(waitHandle, Session.InfiniteTimeSpan, out var exception); Assert.AreEqual(WaitResult.Disconnected, result); Assert.IsNull(exception); @@ -197,4 +197,4 @@ public void ClientSocketShouldNotBeConnected() Assert.IsFalse(ClientSocket.Connected); } } -} \ No newline at end of file +} diff --git a/src/Renci.SshNet.Tests/Classes/SessionTest_Connected_ServerAndClientDisconnectRace.cs b/src/Renci.SshNet.Tests/Classes/SessionTest_Connected_ServerAndClientDisconnectRace.cs index 68bcbdaac..b565fe1fb 100644 --- a/src/Renci.SshNet.Tests/Classes/SessionTest_Connected_ServerAndClientDisconnectRace.cs +++ b/src/Renci.SshNet.Tests/Classes/SessionTest_Connected_ServerAndClientDisconnectRace.cs @@ -47,15 +47,8 @@ public class SessionTest_Connected_ServerAndClientDisconnectRace private void TearDown() { - if (ServerListener != null) - { - ServerListener.Dispose(); - } - - if (Session != null) - { - Session.Dispose(); - } + ServerListener?.Dispose(); + Session?.Dispose(); if (ClientSocket != null && ClientSocket.Connected) { @@ -95,7 +88,7 @@ protected virtual void SetupData() { var newKeysMessage = new NewKeysMessage(); var newKeys = newKeysMessage.GetPacket(8, null); - ServerSocket.Send(newKeys, 4, newKeys.Length - 4, SocketFlags.None); + _ = ServerSocket.Send(newKeys, 4, newKeys.Length - 4, SocketFlags.None); }; ServerListener = new AsyncSocketListener(_serverEndPoint); @@ -120,7 +113,7 @@ protected virtual void SetupData() ServerHostKeyAlgorithms = new string[0] }; var keyExchangeInit = keyExchangeInitMessage.GetPacket(8, null); - ServerSocket.Send(keyExchangeInit, 4, keyExchangeInit.Length - 4, SocketFlags.None); + _ = ServerSocket.Send(keyExchangeInit, 4, keyExchangeInit.Length - 4, SocketFlags.None); }; ServerListener.BytesReceived += (received, socket) => { @@ -129,7 +122,7 @@ protected virtual void SetupData() if (!_authenticationStarted) { var serviceAcceptMessage =ServiceAcceptMessageBuilder.Create(ServiceName.UserAuthentication).Build(); - ServerSocket.Send(serviceAcceptMessage, 0, serviceAcceptMessage.Length, SocketFlags.None); + _ = ServerSocket.Send(serviceAcceptMessage, 0, serviceAcceptMessage.Length, SocketFlags.None); _authenticationStarted = true; } }; @@ -151,29 +144,37 @@ private void CreateMocks() private void SetupMocks() { - _serviceFactoryMock.Setup(p => p.CreateConnector(ConnectionInfo, _socketFactoryMock.Object)) - .Returns(_connectorMock.Object); - _connectorMock.Setup(p => p.Connect(ConnectionInfo)) - .Returns(ClientSocket); - _serviceFactoryMock.Setup(p => p.CreateProtocolVersionExchange()) - .Returns(_protocolVersionExchangeMock.Object); - _protocolVersionExchangeMock.Setup(p => p.Start(Session.ClientVersion, ClientSocket, ConnectionInfo.Timeout)) - .Returns(ServerIdentification); - _serviceFactoryMock.Setup( - p => - p.CreateKeyExchange(ConnectionInfo.KeyExchangeAlgorithms, new[] { _keyExchangeAlgorithm })).Returns(_keyExchangeMock.Object); - _keyExchangeMock.Setup(p => p.Name).Returns(_keyExchangeAlgorithm); - _keyExchangeMock.Setup(p => p.Start(Session, It.IsAny())); - _keyExchangeMock.Setup(p => p.ExchangeHash).Returns(SessionId); - _keyExchangeMock.Setup(p => p.CreateServerCipher()).Returns((Cipher)null); - _keyExchangeMock.Setup(p => p.CreateClientCipher()).Returns((Cipher)null); - _keyExchangeMock.Setup(p => p.CreateServerHash()).Returns((HashAlgorithm)null); - _keyExchangeMock.Setup(p => p.CreateClientHash()).Returns((HashAlgorithm)null); - _keyExchangeMock.Setup(p => p.CreateCompressor()).Returns((Compressor)null); - _keyExchangeMock.Setup(p => p.CreateDecompressor()).Returns((Compressor)null); - _keyExchangeMock.Setup(p => p.Dispose()); - _serviceFactoryMock.Setup(p => p.CreateClientAuthentication()).Returns(_clientAuthenticationMock.Object); - _clientAuthenticationMock.Setup(p => p.Authenticate(ConnectionInfo, Session)); + _ = _serviceFactoryMock.Setup(p => p.CreateConnector(ConnectionInfo, _socketFactoryMock.Object)) + .Returns(_connectorMock.Object); + _ = _connectorMock.Setup(p => p.Connect(ConnectionInfo)) + .Returns(ClientSocket); + _ = _serviceFactoryMock.Setup(p => p.CreateProtocolVersionExchange()) + .Returns(_protocolVersionExchangeMock.Object); + _ = _protocolVersionExchangeMock.Setup(p => p.Start(Session.ClientVersion, ClientSocket, ConnectionInfo.Timeout)) + .Returns(ServerIdentification); + _ = _serviceFactoryMock.Setup(p => p.CreateKeyExchange(ConnectionInfo.KeyExchangeAlgorithms, new[] { _keyExchangeAlgorithm })) + .Returns(_keyExchangeMock.Object); + _ = _keyExchangeMock.Setup(p => p.Name) + .Returns(_keyExchangeAlgorithm); + _ = _keyExchangeMock.Setup(p => p.Start(Session, It.IsAny())); + _ = _keyExchangeMock.Setup(p => p.ExchangeHash) + .Returns(SessionId); + _ = _keyExchangeMock.Setup(p => p.CreateServerCipher()) + .Returns((Cipher) null); + _ = _keyExchangeMock.Setup(p => p.CreateClientCipher()) + .Returns((Cipher) null); + _ = _keyExchangeMock.Setup(p => p.CreateServerHash()) + .Returns((HashAlgorithm) null); + _ = _keyExchangeMock.Setup(p => p.CreateClientHash()) + .Returns((HashAlgorithm) null); + _ = _keyExchangeMock.Setup(p => p.CreateCompressor()) + .Returns((Compressor) null); + _ = _keyExchangeMock.Setup(p => p.CreateDecompressor()) + .Returns((Compressor) null); + _ = _keyExchangeMock.Setup(p => p.Dispose()); + _ = _serviceFactoryMock.Setup(p => p.CreateClientAuthentication()) + .Returns(_clientAuthenticationMock.Object); + _ = _clientAuthenticationMock.Setup(p => p.Authenticate(ConnectionInfo, Session)); } protected virtual void Arrange() @@ -194,7 +195,7 @@ public void Act() try { var disconnect = _disconnectMessage.GetPacket(8, null); - ServerSocket.Send(disconnect, 4, disconnect.Length - 4, SocketFlags.None); + _ = ServerSocket.Send(disconnect, 4, disconnect.Length - 4, SocketFlags.None); Session.Disconnect(); } finally diff --git a/src/Renci.SshNet.Tests/Classes/SessionTest_Connected_ServerSendsBadPacket.cs b/src/Renci.SshNet.Tests/Classes/SessionTest_Connected_ServerSendsBadPacket.cs index df9790f93..c1f0fb5b2 100644 --- a/src/Renci.SshNet.Tests/Classes/SessionTest_Connected_ServerSendsBadPacket.cs +++ b/src/Renci.SshNet.Tests/Classes/SessionTest_Connected_ServerSendsBadPacket.cs @@ -1,8 +1,9 @@ -using System; -using System.Diagnostics; +using System.Diagnostics; using System.Net.Sockets; using System.Threading; + using Microsoft.VisualStudio.TestTools.UnitTesting; + using Renci.SshNet.Common; using Renci.SshNet.Messages.Transport; using Renci.SshNet.Tests.Common; @@ -23,7 +24,7 @@ protected override void SetupData() protected override void Act() { - ServerSocket.Send(_packet, 0, _packet.Length, SocketFlags.None); + _ = ServerSocket.Send(_packet, 0, _packet.Length, SocketFlags.None); // give session some time to process packet Thread.Sleep(200); @@ -124,7 +125,7 @@ public void ISession_MessageListenerCompletedShouldBeSignaled() Assert.IsTrue(session.MessageListenerCompleted.WaitOne()); } - [TestMethodAttribute] + [TestMethod] public void ISession_SendMessageShouldThrowSshConnectionException() { var session = (ISession) Session; @@ -206,12 +207,11 @@ public void ISession_TryWait_WaitHandleAndTimeoutAndException_ShouldReturnDiscon { var session = (ISession) Session; var waitHandle = new ManualResetEvent(false); - Exception exception; - var result = session.TryWait(waitHandle, Session.InfiniteTimeSpan, out exception); + var result = session.TryWait(waitHandle, Session.InfiniteTimeSpan, out var exception); Assert.AreEqual(WaitResult.Disconnected, result); Assert.IsNull(exception); } } -} \ No newline at end of file +} diff --git a/src/Renci.SshNet.Tests/Classes/SessionTest_Connected_ServerSendsDisconnectMessage.cs b/src/Renci.SshNet.Tests/Classes/SessionTest_Connected_ServerSendsDisconnectMessage.cs index 36a73d822..7000a2233 100644 --- a/src/Renci.SshNet.Tests/Classes/SessionTest_Connected_ServerSendsDisconnectMessage.cs +++ b/src/Renci.SshNet.Tests/Classes/SessionTest_Connected_ServerSendsDisconnectMessage.cs @@ -1,9 +1,10 @@ -using System; -using System.Diagnostics; +using System.Diagnostics; using System.Globalization; using System.Net.Sockets; using System.Threading; + using Microsoft.VisualStudio.TestTools.UnitTesting; + using Renci.SshNet.Common; using Renci.SshNet.Messages.Transport; using Renci.SshNet.Tests.Common; @@ -26,7 +27,7 @@ protected override void SetupData() protected override void Act() { - ServerSocket.Send(_packet, 4, _packet.Length - 4, SocketFlags.None); + _ = ServerSocket.Send(_packet, 4, _packet.Length - 4, SocketFlags.None); // give session some time to process packet Thread.Sleep(200); @@ -121,7 +122,7 @@ public void ISession_MessageListenerCompletedShouldBeSignaled() Assert.IsTrue(session.MessageListenerCompleted.WaitOne()); } - [TestMethodAttribute] + [TestMethod] public void ISession_SendMessageShouldThrowSshConnectionException() { var session = (ISession) Session; @@ -211,12 +212,11 @@ public void ISession_TryWait_WaitHandleAndTimeoutAndException_ShouldReturnDiscon { var session = (ISession) Session; var waitHandle = new ManualResetEvent(false); - Exception exception; - var result = session.TryWait(waitHandle, Session.InfiniteTimeSpan, out exception); + var result = session.TryWait(waitHandle, Session.InfiniteTimeSpan, out var exception); Assert.AreEqual(WaitResult.Disconnected, result); Assert.IsNull(exception); } } -} \ No newline at end of file +} diff --git a/src/Renci.SshNet.Tests/Classes/SessionTest_Connected_ServerSendsDisconnectMessageAndShutsDownSocket.cs b/src/Renci.SshNet.Tests/Classes/SessionTest_Connected_ServerSendsDisconnectMessageAndShutsDownSocket.cs index f3bb98773..b91832a40 100644 --- a/src/Renci.SshNet.Tests/Classes/SessionTest_Connected_ServerSendsDisconnectMessageAndShutsDownSocket.cs +++ b/src/Renci.SshNet.Tests/Classes/SessionTest_Connected_ServerSendsDisconnectMessageAndShutsDownSocket.cs @@ -1,9 +1,10 @@ -using System; -using System.Diagnostics; +using System.Diagnostics; using System.Globalization; using System.Net.Sockets; using System.Threading; + using Microsoft.VisualStudio.TestTools.UnitTesting; + using Renci.SshNet.Common; using Renci.SshNet.Messages.Transport; using Renci.SshNet.Tests.Common; @@ -26,7 +27,8 @@ protected override void Act() { // server sends SSH_MSG_DISCONNECT var disconnect = _disconnectMessage.GetPacket(8, null); - ServerSocket.Send(disconnect, 4, disconnect.Length - 4, SocketFlags.None); + + _ = ServerSocket.Send(disconnect, 4, disconnect.Length - 4, SocketFlags.None); // server shuts down the socket ServerSocket.Shutdown(SocketShutdown.Send); @@ -124,7 +126,7 @@ public void ISession_MessageListenerCompletedShouldBeSignaled() Assert.IsTrue(session.MessageListenerCompleted.WaitOne()); } - [TestMethodAttribute] + [TestMethod] public void ISession_SendMessageShouldThrowSshConnectionException() { var session = (ISession) Session; @@ -191,12 +193,11 @@ public void ISession_TryWait_WaitHandleAndTimeoutAndException_ShouldReturnDiscon { var session = (ISession) Session; var waitHandle = new ManualResetEvent(false); - Exception exception; - var result = session.TryWait(waitHandle, Session.InfiniteTimeSpan, out exception); + var result = session.TryWait(waitHandle, Session.InfiniteTimeSpan, out var exception); Assert.AreEqual(WaitResult.Disconnected, result); Assert.IsNull(exception); } } -} \ No newline at end of file +} diff --git a/src/Renci.SshNet.Tests/Classes/SessionTest_Connected_ServerSendsUnsupportedMessageType.cs b/src/Renci.SshNet.Tests/Classes/SessionTest_Connected_ServerSendsUnsupportedMessageType.cs index a40f6e031..a748eae43 100644 --- a/src/Renci.SshNet.Tests/Classes/SessionTest_Connected_ServerSendsUnsupportedMessageType.cs +++ b/src/Renci.SshNet.Tests/Classes/SessionTest_Connected_ServerSendsUnsupportedMessageType.cs @@ -1,8 +1,9 @@ -using System; -using System.Diagnostics; +using System.Diagnostics; using System.Net.Sockets; using System.Threading; + using Microsoft.VisualStudio.TestTools.UnitTesting; + using Renci.SshNet.Common; using Renci.SshNet.Messages.Transport; using Renci.SshNet.Tests.Common; @@ -28,7 +29,7 @@ protected override void SetupData() protected override void Act() { - ServerSocket.Send(_packet, 0, _packet.Length, SocketFlags.None); + _ = ServerSocket.Send(_packet, 0, _packet.Length, SocketFlags.None); // give session some time to process packet Thread.Sleep(200); @@ -101,7 +102,7 @@ public void ReceiveOnServerSocketShouldTimeout() ServerSocket.ReceiveTimeout = 500; try { - ServerSocket.Receive(buffer, 0, buffer.Length, SocketFlags.None); + _ = ServerSocket.Receive(buffer, 0, buffer.Length, SocketFlags.None); Assert.Fail(); } catch (SocketException ex) @@ -134,7 +135,7 @@ public void ISession_MessageListenerCompletedShouldBeSignaled() Assert.IsTrue(session.MessageListenerCompleted.WaitOne()); } - [TestMethodAttribute] + [TestMethod] public void ISession_SendMessageShouldSendMessageToServer() { var session = (ISession) Session; @@ -204,9 +205,8 @@ public void ISession_TryWait_WaitHandleAndTimeoutAndException_ShouldReturnFailed { var session = (ISession) Session; var waitHandle = new ManualResetEvent(false); - Exception exception; - var result = session.TryWait(waitHandle, Session.InfiniteTimeSpan, out exception); + var result = session.TryWait(waitHandle, Session.InfiniteTimeSpan, out var exception); Assert.AreEqual(WaitResult.Failed, result); Assert.IsNotNull(exception); @@ -234,4 +234,4 @@ private static byte[] CreatePacketForUnsupportedMessageType() return sshDataStream.ToArray(); } } -} \ No newline at end of file +} diff --git a/src/Renci.SshNet.Tests/Classes/SessionTest_Connected_ServerShutsDownSendAfterSendingIncompletePacket.cs b/src/Renci.SshNet.Tests/Classes/SessionTest_Connected_ServerShutsDownSendAfterSendingIncompletePacket.cs index 5fbfb8a2a..23db91667 100644 --- a/src/Renci.SshNet.Tests/Classes/SessionTest_Connected_ServerShutsDownSendAfterSendingIncompletePacket.cs +++ b/src/Renci.SshNet.Tests/Classes/SessionTest_Connected_ServerShutsDownSendAfterSendingIncompletePacket.cs @@ -1,8 +1,9 @@ -using System; -using System.Diagnostics; +using System.Diagnostics; using System.Net.Sockets; using System.Threading; + using Microsoft.VisualStudio.TestTools.UnitTesting; + using Renci.SshNet.Common; using Renci.SshNet.Messages.Transport; using Renci.SshNet.Tests.Common; @@ -15,7 +16,8 @@ public class SessionTest_Connected_ServerShutsDownSendAfterSendingIncompletePack protected override void Act() { var incompletePacket = new byte[] {0x0a, 0x05, 0x05}; - ServerSocket.Send(incompletePacket, 0, incompletePacket.Length, SocketFlags.None); + + _ = ServerSocket.Send(incompletePacket, 0, incompletePacket.Length, SocketFlags.None); // give session some time to start reading packet Thread.Sleep(100); @@ -199,12 +201,11 @@ public void ISession_TryWait_WaitHandleAndTimeoutAndException_ShouldReturnDiscon { var session = (ISession) Session; var waitHandle = new ManualResetEvent(false); - Exception exception; - var result = session.TryWait(waitHandle, Session.InfiniteTimeSpan, out exception); + var result = session.TryWait(waitHandle, Session.InfiniteTimeSpan, out var exception); Assert.AreEqual(WaitResult.Disconnected, result); Assert.IsNull(exception); } } -} \ No newline at end of file +} diff --git a/src/Renci.SshNet.Tests/Classes/SessionTest_Connected_ServerShutsDownSocket.cs b/src/Renci.SshNet.Tests/Classes/SessionTest_Connected_ServerShutsDownSocket.cs index 02d1f4c7f..00a8cd546 100644 --- a/src/Renci.SshNet.Tests/Classes/SessionTest_Connected_ServerShutsDownSocket.cs +++ b/src/Renci.SshNet.Tests/Classes/SessionTest_Connected_ServerShutsDownSocket.cs @@ -114,7 +114,7 @@ public void ISession_MessageListenerCompletedShouldBeSignaled() Assert.IsTrue(session.MessageListenerCompleted.WaitOne()); } - [TestMethodAttribute] + [TestMethod] public void ISession_SendMessageShouldThrowSshConnectionException() { var session = (ISession) Session; @@ -197,7 +197,7 @@ public void ISession_TryWait_WaitHandleAndTimeout_ShouldThrowArgumentNullExcepti try { - session.TryWait(waitHandle, timeout); + _ = session.TryWait(waitHandle, timeout); Assert.Fail(); } catch (ArgumentNullException ex) @@ -212,9 +212,8 @@ public void ISession_TryWait_WaitHandleAndTimeoutAndException_ShouldReturnDiscon { var session = (ISession) Session; var waitHandle = new ManualResetEvent(false); - Exception exception; - var result = session.TryWait(waitHandle, Session.InfiniteTimeSpan, out exception); + var result = session.TryWait(waitHandle, Session.InfiniteTimeSpan, out var exception); Assert.AreEqual(WaitResult.Disconnected, result); Assert.IsNull(exception); @@ -230,7 +229,7 @@ public void ISession_TryWait_WaitHandleAndTimeoutAndException_ShouldThrowArgumen try { - session.TryWait(waitHandle, timeout, out exception); + _ = session.TryWait(waitHandle, timeout, out exception); Assert.Fail(); } catch (ArgumentNullException ex) @@ -242,4 +241,4 @@ public void ISession_TryWait_WaitHandleAndTimeoutAndException_ShouldThrowArgumen Assert.IsNull(exception); } } -} \ No newline at end of file +} diff --git a/src/Renci.SshNet.Tests/Classes/SessionTest_NotConnected.cs b/src/Renci.SshNet.Tests/Classes/SessionTest_NotConnected.cs index 97a49a0ec..04491fbc7 100644 --- a/src/Renci.SshNet.Tests/Classes/SessionTest_NotConnected.cs +++ b/src/Renci.SshNet.Tests/Classes/SessionTest_NotConnected.cs @@ -1,12 +1,11 @@ using System; using System.Net; using System.Threading; + using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; + using Renci.SshNet.Common; -using Renci.SshNet.Connection; using Renci.SshNet.Messages.Transport; -using Renci.SshNet.Tests.Common; namespace Renci.SshNet.Tests.Classes { @@ -24,7 +23,7 @@ protected override void SetupData() protected override void Act() { - _session = new Session(_connectionInfo, _serviceFactoryMock.Object, _socketFactoryMock.Object); + _session = new Session(_connectionInfo, ServiceFactoryMock.Object, SocketFactoryMock.Object); } [TestMethod] @@ -136,9 +135,8 @@ public void ISession_TryWait_WaitHandleAndTimeoutAndException_ShouldReturnDiscon { var session = (ISession) _session; var waitHandle = new ManualResetEvent(false); - Exception exception; - var result = session.TryWait(waitHandle, Session.InfiniteTimeSpan, out exception); + var result = session.TryWait(waitHandle, Session.InfiniteTimeSpan, out var exception); Assert.AreEqual(WaitResult.Disconnected, result); Assert.IsNull(exception); @@ -226,13 +224,10 @@ public void ISession_WaitOnHandle_WaitHandleAndTimeout_ShouldThrowArgumentNullEx private static ConnectionInfo CreateConnectionInfo(IPEndPoint serverEndPoint, TimeSpan timeout) { - var connectionInfo = new ConnectionInfo( - serverEndPoint.Address.ToString(), - serverEndPoint.Port, - "eric", - new NoneAuthenticationMethod("eric")); - connectionInfo.Timeout = timeout; - return connectionInfo; + return new ConnectionInfo(serverEndPoint.Address.ToString(), serverEndPoint.Port, "eric", new NoneAuthenticationMethod("eric")) + { + Timeout = timeout + }; } } -} \ No newline at end of file +} diff --git a/src/Renci.SshNet.Tests/Classes/SessionTest_SocketConnected_BadPacketAndDispose.cs b/src/Renci.SshNet.Tests/Classes/SessionTest_SocketConnected_BadPacketAndDispose.cs index f5fb4d79a..a077c774f 100644 --- a/src/Renci.SshNet.Tests/Classes/SessionTest_SocketConnected_BadPacketAndDispose.cs +++ b/src/Renci.SshNet.Tests/Classes/SessionTest_SocketConnected_BadPacketAndDispose.cs @@ -1,8 +1,11 @@ using System; using System.Net; using System.Net.Sockets; + using Microsoft.VisualStudio.TestTools.UnitTesting; + using Moq; + using Renci.SshNet.Common; using Renci.SshNet.Connection; using Renci.SshNet.Messages.Transport; @@ -36,10 +39,7 @@ public void Setup() [TestCleanup] public void TearDown() { - if (_serverListener != null) - { - _serverListener.Dispose(); - } + _serverListener?.Dispose(); } protected void CreateMocks() @@ -53,12 +53,10 @@ protected void CreateMocks() protected void SetupData() { _serverEndPoint = new IPEndPoint(IPAddress.Loopback, 8122); - _connectionInfo = new ConnectionInfo( - _serverEndPoint.Address.ToString(), - _serverEndPoint.Port, - "user", - new PasswordAuthenticationMethod("user", "password")); - _connectionInfo.Timeout = TimeSpan.FromMilliseconds(200); + _connectionInfo = new ConnectionInfo(_serverEndPoint.Address.ToString(), _serverEndPoint.Port, "user", new PasswordAuthenticationMethod("user", "password")) + { + Timeout = TimeSpan.FromMilliseconds(200) + }; _actualException = null; _socketFactory = new SocketFactory(); @@ -71,7 +69,9 @@ protected void SetupData() // packet upon establishing the connection var badPacket = new byte[] { 0x0a, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05 }; - _serverSocket.Send(badPacket, 0, badPacket.Length, SocketFlags.None); + + _ = _serverSocket.Send(badPacket, 0, badPacket.Length, SocketFlags.None); + _serverSocket.Shutdown(SocketShutdown.Send); }; _serverListener.Start(); @@ -83,14 +83,14 @@ protected void SetupData() protected void SetupMocks() { - _serviceFactoryMock.Setup(p => p.CreateConnector(_connectionInfo, _socketFactoryMock.Object)) - .Returns(_connectorMock.Object); - _connectorMock.Setup(p => p.Connect(_connectionInfo)) - .Returns(_clientSocket); - _serviceFactoryMock.Setup(p => p.CreateProtocolVersionExchange()) - .Returns(_protocolVersionExchangeMock.Object); - _protocolVersionExchangeMock.Setup(p => p.Start(_session.ClientVersion, _clientSocket, _connectionInfo.Timeout)) - .Returns(new SshIdentification("2.0", "XXX")); + _ = _serviceFactoryMock.Setup(p => p.CreateConnector(_connectionInfo, _socketFactoryMock.Object)) + .Returns(_connectorMock.Object); + _ = _connectorMock.Setup(p => p.Connect(_connectionInfo)) + .Returns(_clientSocket); + _ = _serviceFactoryMock.Setup(p => p.CreateProtocolVersionExchange()) + .Returns(_protocolVersionExchangeMock.Object); + _ = _protocolVersionExchangeMock.Setup(p => p.Start(_session.ClientVersion, _clientSocket, _connectionInfo.Timeout)) + .Returns(new SshIdentification("2.0", "XXX")); } protected void Arrange() @@ -104,10 +104,8 @@ protected virtual void Act() { try { - - { - _session.Connect(); - } + _session.Connect(); + Assert.Fail(); } catch (SshConnectionException ex) { diff --git a/src/Renci.SshNet.Tests/Classes/Sftp/Requests/SftpRmDirRequestTest.cs b/src/Renci.SshNet.Tests/Classes/Sftp/Requests/SftpRmDirRequestTest.cs index bd7f12c3c..f171a1278 100644 --- a/src/Renci.SshNet.Tests/Classes/Sftp/Requests/SftpRmDirRequestTest.cs +++ b/src/Renci.SshNet.Tests/Classes/Sftp/Requests/SftpRmDirRequestTest.cs @@ -3,12 +3,13 @@ using System.Globalization; using System.Linq; using System.Text; + using Microsoft.VisualStudio.TestTools.UnitTesting; + using Renci.SshNet.Common; using Renci.SshNet.Sftp; using Renci.SshNet.Sftp.Requests; using Renci.SshNet.Sftp.Responses; -using Renci.SshNet.Tests.Common; namespace Renci.SshNet.Tests.Classes.Sftp.Requests { @@ -87,10 +88,10 @@ public void GetBytes() Assert.AreEqual((uint) _pathBytes.Length, sshDataStream.ReadUInt32()); var actualPath = new byte[_pathBytes.Length]; - sshDataStream.Read(actualPath, 0, actualPath.Length); + _ = sshDataStream.Read(actualPath, 0, actualPath.Length); Assert.IsTrue(_pathBytes.SequenceEqual(actualPath)); Assert.IsTrue(sshDataStream.IsEndOfData); } } -} \ No newline at end of file +} diff --git a/src/Renci.SshNet.Tests/Classes/Sftp/Requests/SftpUnblockRequestTest.cs b/src/Renci.SshNet.Tests/Classes/Sftp/Requests/SftpUnblockRequestTest.cs index 40ea7c3dc..aabd4d857 100644 --- a/src/Renci.SshNet.Tests/Classes/Sftp/Requests/SftpUnblockRequestTest.cs +++ b/src/Renci.SshNet.Tests/Classes/Sftp/Requests/SftpUnblockRequestTest.cs @@ -1,12 +1,13 @@ using System; using System.Collections.Generic; using System.Linq; + using Microsoft.VisualStudio.TestTools.UnitTesting; + using Renci.SshNet.Common; using Renci.SshNet.Sftp; using Renci.SshNet.Sftp.Requests; using Renci.SshNet.Sftp.Responses; -using Renci.SshNet.Tests.Common; namespace Renci.SshNet.Tests.Classes.Sftp.Requests { @@ -84,7 +85,7 @@ public void GetBytes() Assert.AreEqual((uint) _handle.Length, sshDataStream.ReadUInt32()); var actualHandle = new byte[_handle.Length]; - sshDataStream.Read(actualHandle, 0, actualHandle.Length); + _ = sshDataStream.Read(actualHandle, 0, actualHandle.Length); Assert.IsTrue(_handle.SequenceEqual(actualHandle)); Assert.AreEqual(_offset, sshDataStream.ReadUInt64()); diff --git a/src/Renci.SshNet.Tests/Classes/Sftp/Responses/ExtendedReplies/StatVfsReplyInfoTest.cs b/src/Renci.SshNet.Tests/Classes/Sftp/Responses/ExtendedReplies/StatVfsReplyInfoTest.cs index d2b4f6c83..4ea375652 100644 --- a/src/Renci.SshNet.Tests/Classes/Sftp/Responses/ExtendedReplies/StatVfsReplyInfoTest.cs +++ b/src/Renci.SshNet.Tests/Classes/Sftp/Responses/ExtendedReplies/StatVfsReplyInfoTest.cs @@ -1,5 +1,7 @@ using System; + using Microsoft.VisualStudio.TestTools.UnitTesting; + using Renci.SshNet.Common; using Renci.SshNet.Sftp; using Renci.SshNet.Sftp.Responses; @@ -88,4 +90,4 @@ public void Load() Assert.AreEqual(_files, information.TotalNodes); } } -} \ No newline at end of file +} diff --git a/src/Renci.SshNet.Tests/Classes/Sftp/Responses/SftpExtendedReplyResponseTest.cs b/src/Renci.SshNet.Tests/Classes/Sftp/Responses/SftpExtendedReplyResponseTest.cs index 6596459be..ff5f9ac39 100644 --- a/src/Renci.SshNet.Tests/Classes/Sftp/Responses/SftpExtendedReplyResponseTest.cs +++ b/src/Renci.SshNet.Tests/Classes/Sftp/Responses/SftpExtendedReplyResponseTest.cs @@ -1,5 +1,7 @@ using System; + using Microsoft.VisualStudio.TestTools.UnitTesting; + using Renci.SshNet.Common; using Renci.SshNet.Sftp; using Renci.SshNet.Sftp.Responses; @@ -60,8 +62,10 @@ public void GetReply_StatVfsReplyInfo() var sid = (ulong) _random.Next(0, int.MaxValue); var namemax = (ulong) _random.Next(0, int.MaxValue); - var sshDataStream = new SshDataStream(4 + 1 + 4 + 88); - sshDataStream.Position = 4; // skip 4 bytes for SSH packet length + var sshDataStream = new SshDataStream(4 + 1 + 4 + 88) + { + Position = 4 // skip 4 bytes for SSH packet length + }; sshDataStream.WriteByte((byte)SftpMessageTypes.Attrs); sshDataStream.Write(_responseId); sshDataStream.Write(bsize); @@ -100,4 +104,4 @@ public void GetReply_StatVfsReplyInfo() Assert.AreEqual(files, information.TotalNodes); } } -} \ No newline at end of file +} diff --git a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileReaderTestBase.cs b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileReaderTestBase.cs index 2f2f1bbf0..0e952d337 100644 --- a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileReaderTestBase.cs +++ b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileReaderTestBase.cs @@ -38,8 +38,8 @@ public void SetUp() protected static SftpFileAttributes CreateSftpFileAttributes(long size) { - var utcDefault = DateTime.SpecifyKind(default(DateTime), DateTimeKind.Utc); - return new SftpFileAttributes(utcDefault, utcDefault, size, default(int), default(int), default(uint), null); + var utcDefault = DateTime.SpecifyKind(default, DateTimeKind.Utc); + return new SftpFileAttributes(utcDefault, utcDefault, size, default, default, default, null); } protected static byte[] CreateByteArray(Random random, int length) @@ -54,7 +54,10 @@ protected static int WaitAny(WaitHandle[] waitHandles, int millisecondsTimeout) var result = WaitHandle.WaitAny(waitHandles, millisecondsTimeout); if (result == WaitHandle.WaitTimeout) + { throw new SshOperationTimeoutException(); + } + return result; } } diff --git a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileReaderTest_DisposeShouldUnblockReadAndReadAhead.cs b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileReaderTest_DisposeShouldUnblockReadAndReadAhead.cs index 2e90f9ce3..b49de6e34 100644 --- a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileReaderTest_DisposeShouldUnblockReadAndReadAhead.cs +++ b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileReaderTest_DisposeShouldUnblockReadAndReadAhead.cs @@ -1,13 +1,14 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using System; +using System.Diagnostics; +using System.Threading; + +using Microsoft.VisualStudio.TestTools.UnitTesting; + using Moq; -#if !FEATURE_EVENTWAITHANDLE_DISPOSE -using Renci.SshNet.Common; -#endif // !FEATURE_EVENTWAITHANDLE_DISPOSE + using Renci.SshNet.Abstractions; using Renci.SshNet.Sftp; -using System; -using System.Diagnostics; -using System.Threading; + using BufferedRead = Renci.SshNet.Sftp.SftpFileReader.BufferedRead; namespace Renci.SshNet.Tests.Classes.Sftp @@ -31,10 +32,7 @@ public class SftpFileReaderTest_DisposeShouldUnblockReadAndReadAhead : SftpFileR [TestCleanup] public void TearDown() { - if (_disposeCompleted != null) - { - _disposeCompleted.Dispose(); - } + _disposeCompleted?.Dispose(); } protected override void SetupData() @@ -54,39 +52,41 @@ protected override void SetupMocks() { _seq = new MockSequence(); - SftpSessionMock.InSequence(_seq) - .Setup(p => p.CreateWaitHandleArray(It.IsNotNull(), It.IsNotNull())) - .Returns((disposingWaitHandle, semaphoreAvailableWaitHandle) => - { - _waitHandleArray[0] = disposingWaitHandle; - _waitHandleArray[1] = semaphoreAvailableWaitHandle; - return _waitHandleArray; - }); - SftpSessionMock.InSequence(_seq) - .Setup(p => p.OperationTimeout) - .Returns(_operationTimeout); - SftpSessionMock.InSequence(_seq) - .Setup(p => p.WaitAny(_waitHandleArray, _operationTimeout)) - .Returns(() => WaitAny(_waitHandleArray, _operationTimeout)); - SftpSessionMock.InSequence(_seq) - .Setup(p => p.BeginRead(_handle, 0, ChunkLength, It.IsNotNull(), It.IsAny())) - .Returns((handle, offset, length, callback, state) => - { - _readAsyncCallback = callback; - return null; - }); - SftpSessionMock.InSequence(_seq).Setup(p => p.OperationTimeout).Returns(_operationTimeout); - SftpSessionMock.InSequence(_seq) - .Setup(p => p.WaitAny(_waitHandleArray, _operationTimeout)) - .Returns(() => WaitAny(_waitHandleArray, _operationTimeout)); - SftpSessionMock.InSequence(_seq) - .Setup(p => p.IsOpen) - .Returns(true); - SftpSessionMock.InSequence(_seq) - .Setup(p => p.BeginClose(_handle, null, null)) - .Returns(_closeAsyncResult); - SftpSessionMock.InSequence(_seq) - .Setup(p => p.EndClose(_closeAsyncResult)); + _ = SftpSessionMock.InSequence(_seq) + .Setup(p => p.CreateWaitHandleArray(It.IsNotNull(), It.IsNotNull())) + .Returns((disposingWaitHandle, semaphoreAvailableWaitHandle) => + { + _waitHandleArray[0] = disposingWaitHandle; + _waitHandleArray[1] = semaphoreAvailableWaitHandle; + return _waitHandleArray; + }); + _ = SftpSessionMock.InSequence(_seq) + .Setup(p => p.OperationTimeout) + .Returns(_operationTimeout); + _ = SftpSessionMock.InSequence(_seq) + .Setup(p => p.WaitAny(_waitHandleArray, _operationTimeout)) + .Returns(() => WaitAny(_waitHandleArray, _operationTimeout)); + _ = SftpSessionMock.InSequence(_seq) + .Setup(p => p.BeginRead(_handle, 0, ChunkLength, It.IsNotNull(), It.IsAny())) + .Returns((handle, offset, length, callback, state) => + { + _readAsyncCallback = callback; + return null; + }); + _ = SftpSessionMock.InSequence(_seq) + .Setup(p => p.OperationTimeout) + .Returns(_operationTimeout); + _ = SftpSessionMock.InSequence(_seq) + .Setup(p => p.WaitAny(_waitHandleArray, _operationTimeout)) + .Returns(() => WaitAny(_waitHandleArray, _operationTimeout)); + _ = SftpSessionMock.InSequence(_seq) + .Setup(p => p.IsOpen) + .Returns(true); + _ = SftpSessionMock.InSequence(_seq) + .Setup(p => p.BeginClose(_handle, null, null)) + .Returns(_closeAsyncResult); + _ = SftpSessionMock.InSequence(_seq) + .Setup(p => p.EndClose(_closeAsyncResult)); } protected override void Arrange() @@ -99,15 +99,15 @@ protected override void Arrange() protected override void Act() { ThreadAbstraction.ExecuteThread(() => - { - Thread.Sleep(500); - _reader.Dispose(); - _disposeCompleted.Set(); - }); + { + Thread.Sleep(500); + _reader.Dispose(); + _ = _disposeCompleted.Set(); + }); try { - _reader.Read(); + _ = _reader.Read(); Assert.Fail(); } catch (ObjectDisposedException ex) @@ -117,7 +117,7 @@ protected override void Act() // Dispose may unblock Read() before the dispose has fully completed, so // let's wait until it has completed - _disposeCompleted.WaitOne(500); + _ = _disposeCompleted.WaitOne(500); } [TestMethod] @@ -132,7 +132,7 @@ public void ReadAfterDisposeShouldThrowObjectDisposedException() { try { - _reader.Read(); + _ = _reader.Read(); Assert.Fail(); } catch (ObjectDisposedException ex) diff --git a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileReaderTest_Dispose_SftpSessionIsNotOpen.cs b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileReaderTest_Dispose_SftpSessionIsNotOpen.cs index 7c2d87ce8..6b8612ab7 100644 --- a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileReaderTest_Dispose_SftpSessionIsNotOpen.cs +++ b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileReaderTest_Dispose_SftpSessionIsNotOpen.cs @@ -1,11 +1,12 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using System; +using System.Threading; + +using Microsoft.VisualStudio.TestTools.UnitTesting; + using Moq; -#if !FEATURE_EVENTWAITHANDLE_DISPOSE -using Renci.SshNet.Common; -#endif // !FEATURE_EVENTWAITHANDLE_DISPOSE + using Renci.SshNet.Sftp; -using System; -using System.Threading; + using BufferedRead = Renci.SshNet.Sftp.SftpFileReader.BufferedRead; namespace Renci.SshNet.Tests.Classes.Sftp @@ -28,15 +29,8 @@ public class SftpFileReaderTest_Dispose_SftpSessionIsNotOpen : SftpFileReaderTes [TestCleanup] public void TearDown() { - if (_beginReadInvoked != null) - { - _beginReadInvoked.Dispose(); - } - - if (_disposeCompleted != null) - { - _disposeCompleted.Dispose(); - } + _beginReadInvoked?.Dispose(); + _disposeCompleted?.Dispose(); } protected override void SetupData() @@ -56,41 +50,41 @@ protected override void SetupMocks() { _seq = new MockSequence(); - SftpSessionMock.InSequence(_seq) - .Setup(p => p.CreateWaitHandleArray(It.IsNotNull(), It.IsNotNull())) - .Returns((disposingWaitHandle, semaphoreAvailableWaitHandle) => - { - _waitHandleArray[0] = disposingWaitHandle; - _waitHandleArray[1] = semaphoreAvailableWaitHandle; - return _waitHandleArray; - }); - SftpSessionMock.InSequence(_seq) - .Setup(p => p.OperationTimeout) - .Returns(_operationTimeout); - SftpSessionMock.InSequence(_seq) - .Setup(p => p.WaitAny(_waitHandleArray, _operationTimeout)) - .Returns(() => WaitAny(_waitHandleArray, _operationTimeout)); - SftpSessionMock.InSequence(_seq) - .Setup(p => p.BeginRead(_handle, 0, ChunkLength, It.IsNotNull(), It.IsAny())) - .Callback(() => - { - // harden test by making sure that we've invoked BeginRead before Dispose is invoked - _beginReadInvoked.Set(); - }) - .Returns((handle, offset, length, callback, state) => - { - _readAsyncCallback = callback; - return null; - }) - .Callback(() => - { - // wait until Dispose has been invoked on reader to allow us to harden test, and - // verify whether Dispose will prevent us from entering the read-ahead loop again - _waitHandleArray[0].WaitOne(); - }); - SftpSessionMock.InSequence(_seq) - .Setup(p => p.IsOpen) - .Returns(false); + _ = SftpSessionMock.InSequence(_seq) + .Setup(p => p.CreateWaitHandleArray(It.IsNotNull(), It.IsNotNull())) + .Returns((disposingWaitHandle, semaphoreAvailableWaitHandle) => + { + _waitHandleArray[0] = disposingWaitHandle; + _waitHandleArray[1] = semaphoreAvailableWaitHandle; + return _waitHandleArray; + }); + _ = SftpSessionMock.InSequence(_seq) + .Setup(p => p.OperationTimeout) + .Returns(_operationTimeout); + _ = SftpSessionMock.InSequence(_seq) + .Setup(p => p.WaitAny(_waitHandleArray, _operationTimeout)) + .Returns(() => WaitAny(_waitHandleArray, _operationTimeout)); + _ = SftpSessionMock.InSequence(_seq) + .Setup(p => p.BeginRead(_handle, 0, ChunkLength, It.IsNotNull(), It.IsAny())) + .Callback(() => + { + // harden test by making sure that we've invoked BeginRead before Dispose is invoked + _ = _beginReadInvoked.Set(); + }) + .Returns((handle, offset, length, callback, state) => + { + _readAsyncCallback = callback; + return null; + }) + .Callback(() => + { + // wait until Dispose has been invoked on reader to allow us to harden test, and + // verify whether Dispose will prevent us from entering the read-ahead loop again + _ = _waitHandleArray[0].WaitOne(); + }); + _ = SftpSessionMock.InSequence(_seq) + .Setup(p => p.IsOpen) + .Returns(false); } protected override void Arrange() @@ -111,7 +105,7 @@ public void ReadAfterDisposeShouldThrowObjectDisposedException() { try { - _reader.Read(); + _ = _reader.Read(); Assert.Fail(); } catch (ObjectDisposedException ex) diff --git a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileReaderTest_Dispose_SftpSessionIsOpen_BeginCloseThrowsException.cs b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileReaderTest_Dispose_SftpSessionIsOpen_BeginCloseThrowsException.cs index 015aba53e..a678dfffb 100644 --- a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileReaderTest_Dispose_SftpSessionIsOpen_BeginCloseThrowsException.cs +++ b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileReaderTest_Dispose_SftpSessionIsOpen_BeginCloseThrowsException.cs @@ -1,11 +1,13 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using System; +using System.Threading; + +using Microsoft.VisualStudio.TestTools.UnitTesting; + using Moq; -#if !FEATURE_EVENTWAITHANDLE_DISPOSE + using Renci.SshNet.Common; -#endif // !FEATURE_EVENTWAITHANDLE_DISPOSE using Renci.SshNet.Sftp; -using System; -using System.Threading; + using BufferedRead = Renci.SshNet.Sftp.SftpFileReader.BufferedRead; namespace Renci.SshNet.Tests.Classes.Sftp @@ -28,15 +30,8 @@ public class SftpFileReaderTest_Dispose_SftpSessionIsOpen_BeginCloseThrowsExcept [TestCleanup] public void TearDown() { - if (_beginReadInvoked != null) - { - _beginReadInvoked.Dispose(); - } - - if (_disposeCompleted != null) - { - _disposeCompleted.Dispose(); - } + _beginReadInvoked?.Dispose(); + _disposeCompleted?.Dispose(); } protected override void SetupData() @@ -56,44 +51,44 @@ protected override void SetupMocks() { _seq = new MockSequence(); - SftpSessionMock.InSequence(_seq) - .Setup(p => p.CreateWaitHandleArray(It.IsNotNull(), It.IsNotNull())) - .Returns((disposingWaitHandle, semaphoreAvailableWaitHandle) => - { - _waitHandleArray[0] = disposingWaitHandle; - _waitHandleArray[1] = semaphoreAvailableWaitHandle; - return _waitHandleArray; - }); - SftpSessionMock.InSequence(_seq) - .Setup(p => p.OperationTimeout) - .Returns(_operationTimeout); - SftpSessionMock.InSequence(_seq) - .Setup(p => p.WaitAny(_waitHandleArray, _operationTimeout)) - .Returns(() => WaitAny(_waitHandleArray, _operationTimeout)); - SftpSessionMock.InSequence(_seq) - .Setup(p => p.BeginRead(_handle, 0, ChunkLength, It.IsNotNull(), It.IsAny())) - .Callback(() => - { - // harden test by making sure that we've invoked BeginRead before Dispose is invoked - _beginReadInvoked.Set(); - }) - .Returns((handle, offset, length, callback, state) => - { - _readAsyncCallback = callback; - return null; - }) - .Callback(() => - { - // wait until Dispose has been invoked on reader to allow us to harden test, and - // verify whether Dispose will prevent us from entering the read-ahead loop again - _waitHandleArray[0].WaitOne(); - }); - SftpSessionMock.InSequence(_seq) - .Setup(p => p.IsOpen) - .Returns(true); - SftpSessionMock.InSequence(_seq) - .Setup(p => p.BeginClose(_handle, null, null)) - .Throws(new SshException()); + _ = SftpSessionMock.InSequence(_seq) + .Setup(p => p.CreateWaitHandleArray(It.IsNotNull(), It.IsNotNull())) + .Returns((disposingWaitHandle, semaphoreAvailableWaitHandle) => + { + _waitHandleArray[0] = disposingWaitHandle; + _waitHandleArray[1] = semaphoreAvailableWaitHandle; + return _waitHandleArray; + }); + _ = SftpSessionMock.InSequence(_seq) + .Setup(p => p.OperationTimeout) + .Returns(_operationTimeout); + _ = SftpSessionMock.InSequence(_seq) + .Setup(p => p.WaitAny(_waitHandleArray, _operationTimeout)) + .Returns(() => WaitAny(_waitHandleArray, _operationTimeout)); + _ = SftpSessionMock.InSequence(_seq) + .Setup(p => p.BeginRead(_handle, 0, ChunkLength, It.IsNotNull(), It.IsAny())) + .Callback(() => + { + // harden test by making sure that we've invoked BeginRead before Dispose is invoked + _ = _beginReadInvoked.Set(); + }) + .Returns((handle, offset, length, callback, state) => + { + _readAsyncCallback = callback; + return null; + }) + .Callback(() => + { + // wait until Dispose has been invoked on reader to allow us to harden test, and + // verify whether Dispose will prevent us from entering the read-ahead loop again + _ = _waitHandleArray[0].WaitOne(); + }); + _ = SftpSessionMock.InSequence(_seq) + .Setup(p => p.IsOpen) + .Returns(true); + _ = SftpSessionMock.InSequence(_seq) + .Setup(p => p.BeginClose(_handle, null, null)) + .Throws(new SshException()); } protected override void Arrange() @@ -114,7 +109,7 @@ public void ReadAfterDisposeShouldThrowObjectDisposedException() { try { - _reader.Read(); + _ = _reader.Read(); Assert.Fail(); } catch (ObjectDisposedException ex) diff --git a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileReaderTest_Dispose_SftpSessionIsOpen_EndCloseThrowsException.cs b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileReaderTest_Dispose_SftpSessionIsOpen_EndCloseThrowsException.cs index 4a175648e..6f6002e3e 100644 --- a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileReaderTest_Dispose_SftpSessionIsOpen_EndCloseThrowsException.cs +++ b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileReaderTest_Dispose_SftpSessionIsOpen_EndCloseThrowsException.cs @@ -1,11 +1,15 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using System; +using System.Threading; + +using Microsoft.VisualStudio.TestTools.UnitTesting; + using Moq; + #if !FEATURE_EVENTWAITHANDLE_DISPOSE using Renci.SshNet.Common; #endif // !FEATURE_EVENTWAITHANDLE_DISPOSE using Renci.SshNet.Sftp; -using System; -using System.Threading; + using BufferedRead = Renci.SshNet.Sftp.SftpFileReader.BufferedRead; namespace Renci.SshNet.Tests.Classes.Sftp @@ -29,15 +33,8 @@ public class SftpFileReaderTest_Dispose_SftpSessionIsOpen_EndCloseThrowsExceptio [TestCleanup] public void TearDown() { - if (_beginReadInvoked != null) - { - _beginReadInvoked.Dispose(); - } - - if (_disposeCompleted != null) - { - _disposeCompleted.Dispose(); - } + _beginReadInvoked?.Dispose(); + _disposeCompleted?.Dispose(); } protected override void SetupData() @@ -58,47 +55,47 @@ protected override void SetupMocks() { _seq = new MockSequence(); - SftpSessionMock.InSequence(_seq) - .Setup(p => p.CreateWaitHandleArray(It.IsNotNull(), It.IsNotNull())) - .Returns((disposingWaitHandle, semaphoreAvailableWaitHandle) => - { - _waitHandleArray[0] = disposingWaitHandle; - _waitHandleArray[1] = semaphoreAvailableWaitHandle; - return _waitHandleArray; - }); - SftpSessionMock.InSequence(_seq) - .Setup(p => p.OperationTimeout) - .Returns(_operationTimeout); - SftpSessionMock.InSequence(_seq) - .Setup(p => p.WaitAny(_waitHandleArray, _operationTimeout)) - .Returns(() => WaitAny(_waitHandleArray, _operationTimeout)); - SftpSessionMock.InSequence(_seq) - .Setup(p => p.BeginRead(_handle, 0, ChunkLength, It.IsNotNull(), It.IsAny())) - .Callback(() => - { - // harden test by making sure that we've invoked BeginRead before Dispose is invoked - _beginReadInvoked.Set(); - }) - .Returns((handle, offset, length, callback, state) => - { - _readAsyncCallback = callback; - return null; - }) - .Callback(() => - { - // wait until Dispose has been invoked on reader to allow us to harden test, and - // verify whether Dispose will prevent us from entering the read-ahead loop again - _waitHandleArray[0].WaitOne(); - }); - SftpSessionMock.InSequence(_seq) - .Setup(p => p.IsOpen) - .Returns(true); - SftpSessionMock.InSequence(_seq) - .Setup(p => p.BeginClose(_handle, null, null)) - .Returns(_closeAsyncResult); - SftpSessionMock.InSequence(_seq) - .Setup(p => p.EndClose(_closeAsyncResult)) - .Throws(new SshException()); + _ = SftpSessionMock.InSequence(_seq) + .Setup(p => p.CreateWaitHandleArray(It.IsNotNull(), It.IsNotNull())) + .Returns((disposingWaitHandle, semaphoreAvailableWaitHandle) => + { + _waitHandleArray[0] = disposingWaitHandle; + _waitHandleArray[1] = semaphoreAvailableWaitHandle; + return _waitHandleArray; + }); + _ = SftpSessionMock.InSequence(_seq) + .Setup(p => p.OperationTimeout) + .Returns(_operationTimeout); + _ = SftpSessionMock.InSequence(_seq) + .Setup(p => p.WaitAny(_waitHandleArray, _operationTimeout)) + .Returns(() => WaitAny(_waitHandleArray, _operationTimeout)); + _ = SftpSessionMock.InSequence(_seq) + .Setup(p => p.BeginRead(_handle, 0, ChunkLength, It.IsNotNull(), It.IsAny())) + .Callback(() => + { + // harden test by making sure that we've invoked BeginRead before Dispose is invoked + _ = _beginReadInvoked.Set(); + }) + .Returns((handle, offset, length, callback, state) => + { + _readAsyncCallback = callback; + return null; + }) + .Callback(() => + { + // wait until Dispose has been invoked on reader to allow us to harden test, and + // verify whether Dispose will prevent us from entering the read-ahead loop again + _ = _waitHandleArray[0].WaitOne(); + }); + _ = SftpSessionMock.InSequence(_seq) + .Setup(p => p.IsOpen) + .Returns(true); + _ = SftpSessionMock.InSequence(_seq) + .Setup(p => p.BeginClose(_handle, null, null)) + .Returns(_closeAsyncResult); + _ = SftpSessionMock.InSequence(_seq) + .Setup(p => p.EndClose(_closeAsyncResult)) + .Throws(new SshException()); } protected override void Arrange() @@ -119,7 +116,7 @@ public void ReadAfterDisposeShouldThrowObjectDisposedException() { try { - _reader.Read(); + _ = _reader.Read(); Assert.Fail(); } catch (ObjectDisposedException ex) diff --git a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileReaderTest_PreviousChunkIsIncompleteAndEofIsNotReached.cs b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileReaderTest_PreviousChunkIsIncompleteAndEofIsNotReached.cs index 8c38a000f..cedcff5cb 100644 --- a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileReaderTest_PreviousChunkIsIncompleteAndEofIsNotReached.cs +++ b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileReaderTest_PreviousChunkIsIncompleteAndEofIsNotReached.cs @@ -75,99 +75,111 @@ protected override void SetupMocks() { _seq = new MockSequence(); - SftpSessionMock.InSequence(_seq) - .Setup(p => p.CreateWaitHandleArray(It.IsNotNull(), It.IsNotNull())) - .Returns((disposingWaitHandle, semaphoreAvailableWaitHandle) => - { - _waitHandleArray[0] = disposingWaitHandle; - _waitHandleArray[1] = semaphoreAvailableWaitHandle; - return _waitHandleArray; - }); - SftpSessionMock.InSequence(_seq).Setup(p => p.OperationTimeout).Returns(_operationTimeout); - SftpSessionMock.InSequence(_seq) - .Setup(p => p.WaitAny(_waitHandleArray, _operationTimeout)) - .Returns(() => WaitAny(_waitHandleArray, _operationTimeout)); - SftpSessionMock.InSequence(_seq) - .Setup(p => p.BeginRead(_handle, 0, ChunkLength, It.IsNotNull(), It.IsAny())) - .Callback((handle, offset, length, callback, state) => - { - _chunk1BeginRead.Set(); - var asyncResult = new SftpReadAsyncResult(callback, state); - asyncResult.SetAsCompleted(_chunk1, false); - }) - .Returns((SftpReadAsyncResult)null); - SftpSessionMock.InSequence(_seq).Setup(p => p.OperationTimeout).Returns(_operationTimeout); - SftpSessionMock.InSequence(_seq) - .Setup(p => p.WaitAny(_waitHandleArray, _operationTimeout)) - .Returns(() => WaitAny(_waitHandleArray, _operationTimeout)); - SftpSessionMock.InSequence(_seq) - .Setup(p => p.BeginRead(_handle, ChunkLength, ChunkLength, It.IsNotNull(), It.IsAny())) - .Callback((handle, offset, length, callback, state) => - { - _chunk2BeginRead.Set(); - var asyncResult = new SftpReadAsyncResult(callback, state); - asyncResult.SetAsCompleted(_chunk2, false); - }) - .Returns((SftpReadAsyncResult)null); - SftpSessionMock.InSequence(_seq).Setup(p => p.OperationTimeout).Returns(_operationTimeout); - SftpSessionMock.InSequence(_seq) - .Setup(p => p.WaitAny(_waitHandleArray, _operationTimeout)) - .Returns(() => WaitAny(_waitHandleArray, _operationTimeout)); - SftpSessionMock.InSequence(_seq) - .Setup(p => p.BeginRead(_handle, 2 * ChunkLength, ChunkLength, It.IsNotNull(), It.IsAny())) - .Callback((handle, offset, length, callback, state) => - { - _chunk3BeginRead.Set(); - var asyncResult = new SftpReadAsyncResult(callback, state); - asyncResult.SetAsCompleted(_chunk3, false); - }) - .Returns((SftpReadAsyncResult)null); - SftpSessionMock.InSequence(_seq).Setup(p => p.OperationTimeout).Returns(_operationTimeout); - SftpSessionMock.InSequence(_seq) - .Setup(p => p.WaitAny(_waitHandleArray, _operationTimeout)) - .Returns(() => WaitAny(_waitHandleArray, _operationTimeout)); - SftpSessionMock.InSequence(_seq) - .Setup(p => p.BeginRead(_handle, 3 * ChunkLength, ChunkLength, It.IsNotNull(), It.IsAny())) - .Callback((handle, offset, length, callback, state) => - { - _chunk4BeginRead.Set(); - var asyncResult = new SftpReadAsyncResult(callback, state); - asyncResult.SetAsCompleted(_chunk4, false); - }) - .Returns((SftpReadAsyncResult)null); - SftpSessionMock.InSequence(_seq).Setup(p => p.OperationTimeout).Returns(_operationTimeout); - SftpSessionMock.InSequence(_seq) - .Setup(p => p.WaitAny(_waitHandleArray, _operationTimeout)) - .Returns(() => WaitAny(_waitHandleArray, _operationTimeout)); - SftpSessionMock.InSequence(_seq) - .Setup(p => p.BeginRead(_handle, 4 * ChunkLength, ChunkLength, It.IsNotNull(), It.IsAny())) - .Callback((handle, offset, length, callback, state) => - { - _chunk5BeginRead.Set(); - var asyncResult = new SftpReadAsyncResult(callback, state); - asyncResult.SetAsCompleted(_chunk5, false); - }) - .Returns((SftpReadAsyncResult)null); - SftpSessionMock.InSequence(_seq).Setup(p => p.OperationTimeout).Returns(_operationTimeout); - SftpSessionMock.InSequence(_seq) - .Setup(p => p.WaitAny(_waitHandleArray, _operationTimeout)) - .Callback(() => _waitBeforeChunk6.Set()) - .Returns(() => WaitAny(_waitHandleArray, _operationTimeout)); - SftpSessionMock.InSequence(_seq) - .Setup(p => p.RequestRead(_handle, 2 * ChunkLength - 17, 17)) - .Returns(_chunk2CatchUp1); - SftpSessionMock.InSequence(_seq) - .Setup(p => p.RequestRead(_handle, 2 * ChunkLength - 7, 7)) - .Returns(_chunk2CatchUp2); - SftpSessionMock.InSequence(_seq) - .Setup(p => p.BeginRead(_handle, 5 * ChunkLength, ChunkLength, It.IsNotNull(), It.IsAny())) - .Callback((handle, offset, length, callback, state) => - { - _chunk6BeginRead.Set(); - var asyncResult = new SftpReadAsyncResult(callback, state); - asyncResult.SetAsCompleted(_chunk6, false); - }) - .Returns((SftpReadAsyncResult)null); + _ = SftpSessionMock.InSequence(_seq) + .Setup(p => p.CreateWaitHandleArray(It.IsNotNull(), It.IsNotNull())) + .Returns((disposingWaitHandle, semaphoreAvailableWaitHandle) => + { + _waitHandleArray[0] = disposingWaitHandle; + _waitHandleArray[1] = semaphoreAvailableWaitHandle; + return _waitHandleArray; + }); + _ = SftpSessionMock.InSequence(_seq) + .Setup(p => p.OperationTimeout) + .Returns(_operationTimeout); + _ = SftpSessionMock.InSequence(_seq) + .Setup(p => p.WaitAny(_waitHandleArray, _operationTimeout)) + .Returns(() => WaitAny(_waitHandleArray, _operationTimeout)); + _ = SftpSessionMock.InSequence(_seq) + .Setup(p => p.BeginRead(_handle, 0, ChunkLength, It.IsNotNull(), It.IsAny())) + .Callback((handle, offset, length, callback, state) => + { + _ = _chunk1BeginRead.Set(); + var asyncResult = new SftpReadAsyncResult(callback, state); + asyncResult.SetAsCompleted(_chunk1, false); + }) + .Returns((SftpReadAsyncResult)null); + _ = SftpSessionMock.InSequence(_seq) + .Setup(p => p.OperationTimeout) + .Returns(_operationTimeout); + _ = SftpSessionMock.InSequence(_seq) + .Setup(p => p.WaitAny(_waitHandleArray, _operationTimeout)) + .Returns(() => WaitAny(_waitHandleArray, _operationTimeout)); + _ = SftpSessionMock.InSequence(_seq) + .Setup(p => p.BeginRead(_handle, ChunkLength, ChunkLength, It.IsNotNull(), It.IsAny())) + .Callback((handle, offset, length, callback, state) => + { + _ = _chunk2BeginRead.Set(); + var asyncResult = new SftpReadAsyncResult(callback, state); + asyncResult.SetAsCompleted(_chunk2, false); + }) + .Returns((SftpReadAsyncResult) null); + _ = SftpSessionMock.InSequence(_seq) + .Setup(p => p.OperationTimeout) + .Returns(_operationTimeout); + _ = SftpSessionMock.InSequence(_seq) + .Setup(p => p.WaitAny(_waitHandleArray, _operationTimeout)) + .Returns(() => WaitAny(_waitHandleArray, _operationTimeout)); + _ = SftpSessionMock.InSequence(_seq) + .Setup(p => p.BeginRead(_handle, 2 * ChunkLength, ChunkLength, It.IsNotNull(), It.IsAny())) + .Callback((handle, offset, length, callback, state) => + { + _ = _chunk3BeginRead.Set(); + var asyncResult = new SftpReadAsyncResult(callback, state); + asyncResult.SetAsCompleted(_chunk3, false); + }) + .Returns((SftpReadAsyncResult) null); + _ = SftpSessionMock.InSequence(_seq) + .Setup(p => p.OperationTimeout) + .Returns(_operationTimeout); + _ = SftpSessionMock.InSequence(_seq) + .Setup(p => p.WaitAny(_waitHandleArray, _operationTimeout)) + .Returns(() => WaitAny(_waitHandleArray, _operationTimeout)); + _ = SftpSessionMock.InSequence(_seq) + .Setup(p => p.BeginRead(_handle, 3 * ChunkLength, ChunkLength, It.IsNotNull(), It.IsAny())) + .Callback((handle, offset, length, callback, state) => + { + _ = _chunk4BeginRead.Set(); + var asyncResult = new SftpReadAsyncResult(callback, state); + asyncResult.SetAsCompleted(_chunk4, false); + }) + .Returns((SftpReadAsyncResult) null); + _ = SftpSessionMock.InSequence(_seq) + .Setup(p => p.OperationTimeout) + .Returns(_operationTimeout); + _ = SftpSessionMock.InSequence(_seq) + .Setup(p => p.WaitAny(_waitHandleArray, _operationTimeout)) + .Returns(() => WaitAny(_waitHandleArray, _operationTimeout)); + _ = SftpSessionMock.InSequence(_seq) + .Setup(p => p.BeginRead(_handle, 4 * ChunkLength, ChunkLength, It.IsNotNull(), It.IsAny())) + .Callback((handle, offset, length, callback, state) => + { + _ = _chunk5BeginRead.Set(); + var asyncResult = new SftpReadAsyncResult(callback, state); + asyncResult.SetAsCompleted(_chunk5, false); + }) + .Returns((SftpReadAsyncResult) null); + _ = SftpSessionMock.InSequence(_seq) + .Setup(p => p.OperationTimeout) + .Returns(_operationTimeout); + _ = SftpSessionMock.InSequence(_seq) + .Setup(p => p.WaitAny(_waitHandleArray, _operationTimeout)) + .Callback(() => _waitBeforeChunk6.Set()) + .Returns(() => WaitAny(_waitHandleArray, _operationTimeout)); + _ = SftpSessionMock.InSequence(_seq) + .Setup(p => p.RequestRead(_handle, (2 * ChunkLength) - 17, 17)) + .Returns(_chunk2CatchUp1); + _ = SftpSessionMock.InSequence(_seq) + .Setup(p => p.RequestRead(_handle, (2 * ChunkLength) - 7, 7)) + .Returns(_chunk2CatchUp2); + _ = SftpSessionMock.InSequence(_seq) + .Setup(p => p.BeginRead(_handle, 5 * ChunkLength, ChunkLength, It.IsNotNull(), It.IsAny())) + .Callback((handle, offset, length, callback, state) => + { + _ = _chunk6BeginRead.Set(); + var asyncResult = new SftpReadAsyncResult(callback, state); + asyncResult.SetAsCompleted(_chunk6, false); + }) + .Returns((SftpReadAsyncResult) null); } protected override void Arrange() @@ -271,7 +283,7 @@ public void ReadAfterEndOfFileShouldThrowSshException() { try { - _reader.Read(); + _ = _reader.Read(); Assert.Fail(); } catch (SshException ex) @@ -284,9 +296,14 @@ public void ReadAfterEndOfFileShouldThrowSshException() [TestMethod] public void DisposeShouldCloseHandleAndCompleteImmediately() { - SftpSessionMock.InSequence(_seq).Setup(p => p.IsOpen).Returns(true); - SftpSessionMock.InSequence(_seq).Setup(p => p.BeginClose(_handle, null, null)).Returns(_closeAsyncResult); - SftpSessionMock.InSequence(_seq).Setup(p => p.EndClose(_closeAsyncResult)); + _ = SftpSessionMock.InSequence(_seq) + .Setup(p => p.IsOpen) + .Returns(true); + _ = SftpSessionMock.InSequence(_seq) + .Setup(p => p.BeginClose(_handle, null, null)) + .Returns(_closeAsyncResult); + _ = SftpSessionMock.InSequence(_seq) + .Setup(p => p.EndClose(_closeAsyncResult)); var stopwatch = Stopwatch.StartNew(); _reader.Dispose(); diff --git a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileReaderTest_PreviousChunkIsIncompleteAndEofIsReached.cs b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileReaderTest_PreviousChunkIsIncompleteAndEofIsReached.cs index 2b5cc0f2e..5d2ed04f3 100644 --- a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileReaderTest_PreviousChunkIsIncompleteAndEofIsReached.cs +++ b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileReaderTest_PreviousChunkIsIncompleteAndEofIsReached.cs @@ -55,56 +55,62 @@ protected override void SetupMocks() { _seq = new MockSequence(); - SftpSessionMock.InSequence(_seq) - .Setup(p => p.CreateWaitHandleArray(It.IsNotNull(), It.IsNotNull())) - .Returns((disposingWaitHandle, semaphoreAvailableWaitHandle) => - { - _waitHandleArray[0] = disposingWaitHandle; - _waitHandleArray[1] = semaphoreAvailableWaitHandle; - return _waitHandleArray; - }); - SftpSessionMock.InSequence(_seq).Setup(p => p.OperationTimeout).Returns(_operationTimeout); - SftpSessionMock.InSequence(_seq) - .Setup(p => p.WaitAny(_waitHandleArray, _operationTimeout)) - .Returns(() => WaitAny(_waitHandleArray, _operationTimeout)); - SftpSessionMock.InSequence(_seq) - .Setup(p => p.BeginRead(_handle, 0, ChunkLength, It.IsNotNull(), It.IsAny())) - .Callback((handle, offset, length, callback, state) => - { - _chunk1BeginRead.Set(); - var asyncResult = new SftpReadAsyncResult(callback, state); - asyncResult.SetAsCompleted(_chunk1, false); - }) - .Returns((SftpReadAsyncResult)null); - SftpSessionMock.InSequence(_seq).Setup(p => p.OperationTimeout).Returns(_operationTimeout); - SftpSessionMock.InSequence(_seq) - .Setup(p => p.WaitAny(_waitHandleArray, _operationTimeout)) - .Returns(() => WaitAny(_waitHandleArray, _operationTimeout)); - SftpSessionMock.InSequence(_seq) - .Setup(p => p.BeginRead(_handle, ChunkLength, ChunkLength, It.IsNotNull(), It.IsAny())) - .Callback((handle, offset, length, callback, state) => - { - _chunk2BeginRead.Set(); - var asyncResult = new SftpReadAsyncResult(callback, state); - asyncResult.SetAsCompleted(_chunk2, false); - }) - .Returns((SftpReadAsyncResult)null); - SftpSessionMock.InSequence(_seq).Setup(p => p.OperationTimeout).Returns(_operationTimeout); - SftpSessionMock.InSequence(_seq) - .Setup(p => p.WaitAny(_waitHandleArray, _operationTimeout)) - .Returns(() => WaitAny(_waitHandleArray, _operationTimeout)); - SftpSessionMock.InSequence(_seq) - .Setup(p => p.BeginRead(_handle, 2 * ChunkLength, ChunkLength, It.IsNotNull(), It.IsAny())) - .Callback((handle, offset, length, callback, state) => - { - _chunk3BeginRead.Set(); - var asyncResult = new SftpReadAsyncResult(callback, state); - asyncResult.SetAsCompleted(_chunk3, false); - }) - .Returns((SftpReadAsyncResult)null); - SftpSessionMock.InSequence(_seq) - .Setup(p => p.RequestRead(_handle, 2 * ChunkLength - 10, 10)) - .Returns(_chunk2CatchUp); + _ = SftpSessionMock.InSequence(_seq) + .Setup(p => p.CreateWaitHandleArray(It.IsNotNull(), It.IsNotNull())) + .Returns((disposingWaitHandle, semaphoreAvailableWaitHandle) => + { + _waitHandleArray[0] = disposingWaitHandle; + _waitHandleArray[1] = semaphoreAvailableWaitHandle; + return _waitHandleArray; + }); + _ = SftpSessionMock.InSequence(_seq) + .Setup(p => p.OperationTimeout) + .Returns(_operationTimeout); + _ = SftpSessionMock.InSequence(_seq) + .Setup(p => p.WaitAny(_waitHandleArray, _operationTimeout)) + .Returns(() => WaitAny(_waitHandleArray, _operationTimeout)); + _ = SftpSessionMock.InSequence(_seq) + .Setup(p => p.BeginRead(_handle, 0, ChunkLength, It.IsNotNull(), It.IsAny())) + .Callback((handle, offset, length, callback, state) => + { + _ = _chunk1BeginRead.Set(); + var asyncResult = new SftpReadAsyncResult(callback, state); + asyncResult.SetAsCompleted(_chunk1, false); + }) + .Returns((SftpReadAsyncResult) null); + _ = SftpSessionMock.InSequence(_seq) + .Setup(p => p.OperationTimeout) + .Returns(_operationTimeout); + _ = SftpSessionMock.InSequence(_seq) + .Setup(p => p.WaitAny(_waitHandleArray, _operationTimeout)) + .Returns(() => WaitAny(_waitHandleArray, _operationTimeout)); + _ = SftpSessionMock.InSequence(_seq) + .Setup(p => p.BeginRead(_handle, ChunkLength, ChunkLength, It.IsNotNull(), It.IsAny())) + .Callback((handle, offset, length, callback, state) => + { + _ = _chunk2BeginRead.Set(); + var asyncResult = new SftpReadAsyncResult(callback, state); + asyncResult.SetAsCompleted(_chunk2, false); + }) + .Returns((SftpReadAsyncResult) null); + _ = SftpSessionMock.InSequence(_seq) + .Setup(p => p.OperationTimeout) + .Returns(_operationTimeout); + _ = SftpSessionMock.InSequence(_seq) + .Setup(p => p.WaitAny(_waitHandleArray, _operationTimeout)) + .Returns(() => WaitAny(_waitHandleArray, _operationTimeout)); + _ = SftpSessionMock.InSequence(_seq) + .Setup(p => p.BeginRead(_handle, 2 * ChunkLength, ChunkLength, It.IsNotNull(), It.IsAny())) + .Callback((handle, offset, length, callback, state) => + { + _ = _chunk3BeginRead.Set(); + var asyncResult = new SftpReadAsyncResult(callback, state); + asyncResult.SetAsCompleted(_chunk3, false); + }) + .Returns((SftpReadAsyncResult) null); + _ = SftpSessionMock.InSequence(_seq) + .Setup(p => p.RequestRead(_handle, (2 * ChunkLength) - 10, 10)) + .Returns(_chunk2CatchUp); } protected override void Arrange() @@ -161,7 +167,7 @@ public void ReadAfterEndOfFileShouldThrowSshException() { try { - _reader.Read(); + _ = _reader.Read(); Assert.Fail(); } catch (SshException ex) @@ -174,9 +180,14 @@ public void ReadAfterEndOfFileShouldThrowSshException() [TestMethod] public void DisposeShouldCloseHandleAndCompleteImmediately() { - SftpSessionMock.InSequence(_seq).Setup(p => p.IsOpen).Returns(true); - SftpSessionMock.InSequence(_seq).Setup(p => p.BeginClose(_handle, null, null)).Returns(_closeAsyncResult); - SftpSessionMock.InSequence(_seq).Setup(p => p.EndClose(_closeAsyncResult)); + _ = SftpSessionMock.InSequence(_seq) + .Setup(p => p.IsOpen) + .Returns(true); + _ = SftpSessionMock.InSequence(_seq) + .Setup(p => p.BeginClose(_handle, null, null)) + .Returns(_closeAsyncResult); + _ = SftpSessionMock.InSequence(_seq) + .Setup(p => p.EndClose(_closeAsyncResult)); var stopwatch = Stopwatch.StartNew(); _reader.Dispose(); diff --git a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileReaderTest_ReadAheadEndInvokeException_PreventsFurtherReadAheads.cs b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileReaderTest_ReadAheadEndInvokeException_PreventsFurtherReadAheads.cs index 0e4e65eaf..06f2c5433 100644 --- a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileReaderTest_ReadAheadEndInvokeException_PreventsFurtherReadAheads.cs +++ b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileReaderTest_ReadAheadEndInvokeException_PreventsFurtherReadAheads.cs @@ -1,11 +1,15 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using System; +using System.Diagnostics; +using System.Threading; + +using Microsoft.VisualStudio.TestTools.UnitTesting; + using Moq; + using Renci.SshNet.Abstractions; using Renci.SshNet.Common; using Renci.SshNet.Sftp; -using System; -using System.Diagnostics; -using System.Threading; + using BufferedRead = Renci.SshNet.Sftp.SftpFileReader.BufferedRead; namespace Renci.SshNet.Tests.Classes.Sftp @@ -22,7 +26,6 @@ public class SftpFileReaderTest_ReadAheadEndInvokeException_PreventsFurtherReadA private int _operationTimeout; private SftpCloseAsyncResult _closeAsyncResult; private byte[] _chunk1; - private byte[] _chunk3; private SftpFileReader _reader; private ManualResetEvent _readAheadChunk2; private ManualResetEvent _readChunk2; @@ -35,7 +38,6 @@ protected override void SetupData() _handle = CreateByteArray(random, 5); _chunk1 = CreateByteArray(random, ChunkLength); - _chunk3 = CreateByteArray(random, ChunkLength); _fileSize = 3 * _chunk1.Length; _waitHandleArray = new WaitHandle[2]; _operationTimeout = random.Next(10000, 20000); @@ -51,52 +53,58 @@ protected override void SetupMocks() { _seq = new MockSequence(); - SftpSessionMock.InSequence(_seq) - .Setup(p => p.CreateWaitHandleArray(It.IsNotNull(), It.IsNotNull())) - .Returns((disposingWaitHandle, semaphoreAvailableWaitHandle) => - { - _waitHandleArray[0] = disposingWaitHandle; - _waitHandleArray[1] = semaphoreAvailableWaitHandle; - return _waitHandleArray; - }); - SftpSessionMock.InSequence(_seq).Setup(p => p.OperationTimeout).Returns(_operationTimeout); - SftpSessionMock.InSequence(_seq) - .Setup(p => p.WaitAny(_waitHandleArray, _operationTimeout)) - .Returns(() => WaitAny(_waitHandleArray, _operationTimeout)); - SftpSessionMock.InSequence(_seq) - .Setup(p => p.BeginRead(_handle, 0, ChunkLength, It.IsNotNull(), It.IsAny())) - .Callback((handle, offset, length, callback, state) => - { - var asyncResult = new SftpReadAsyncResult(callback, state); - asyncResult.SetAsCompleted(_chunk1, false); - }) - .Returns((SftpReadAsyncResult)null); - SftpSessionMock.InSequence(_seq).Setup(p => p.OperationTimeout).Returns(_operationTimeout); - SftpSessionMock.InSequence(_seq) - .Setup(p => p.WaitAny(_waitHandleArray, _operationTimeout)) - .Returns(() => WaitAny(_waitHandleArray, _operationTimeout)); - SftpSessionMock.InSequence(_seq) - .Setup(p => p.BeginRead(_handle, ChunkLength, ChunkLength, It.IsNotNull(), It.IsAny())) - .Callback((handle, offset, length, callback, state) => - { - ThreadAbstraction.ExecuteThread(() => - { - // signal that we're in the read-ahead for chunk2 - _readAheadChunk2.Set(); - // wait for client to start reading this chunk - _readChunk2.WaitOne(TimeSpan.FromSeconds(5)); - // sleep a short time to make sure the client is in the blocking wait - Thread.Sleep(500); - // complete async read of chunk2 with exception - var asyncResult = new SftpReadAsyncResult(callback, state); - asyncResult.SetAsCompleted(_exception, false); - }); - }) - .Returns((SftpReadAsyncResult)null); - SftpSessionMock.InSequence(_seq).Setup(p => p.OperationTimeout).Returns(_operationTimeout); - SftpSessionMock.InSequence(_seq) - .Setup(p => p.WaitAny(_waitHandleArray, _operationTimeout)) - .Returns(() => WaitAny(_waitHandleArray, _operationTimeout)); + _ = SftpSessionMock.InSequence(_seq) + .Setup(p => p.CreateWaitHandleArray(It.IsNotNull(), It.IsNotNull())) + .Returns((disposingWaitHandle, semaphoreAvailableWaitHandle) => + { + _waitHandleArray[0] = disposingWaitHandle; + _waitHandleArray[1] = semaphoreAvailableWaitHandle; + return _waitHandleArray; + }); + _ = SftpSessionMock.InSequence(_seq) + .Setup(p => p.OperationTimeout) + .Returns(_operationTimeout); + _ = SftpSessionMock.InSequence(_seq) + .Setup(p => p.WaitAny(_waitHandleArray, _operationTimeout)) + .Returns(() => WaitAny(_waitHandleArray, _operationTimeout)); + _ = SftpSessionMock.InSequence(_seq) + .Setup(p => p.BeginRead(_handle, 0, ChunkLength, It.IsNotNull(), It.IsAny())) + .Callback((handle, offset, length, callback, state) => + { + var asyncResult = new SftpReadAsyncResult(callback, state); + asyncResult.SetAsCompleted(_chunk1, false); + }) + .Returns((SftpReadAsyncResult) null); + _ = SftpSessionMock.InSequence(_seq) + .Setup(p => p.OperationTimeout) + .Returns(_operationTimeout); + _ = SftpSessionMock.InSequence(_seq) + .Setup(p => p.WaitAny(_waitHandleArray, _operationTimeout)) + .Returns(() => WaitAny(_waitHandleArray, _operationTimeout)); + _ = SftpSessionMock.InSequence(_seq) + .Setup(p => p.BeginRead(_handle, ChunkLength, ChunkLength, It.IsNotNull(), It.IsAny())) + .Callback((handle, offset, length, callback, state) => + { + ThreadAbstraction.ExecuteThread(() => + { + // signal that we're in the read-ahead for chunk2 + _ = _readAheadChunk2.Set(); + // wait for client to start reading this chunk + _ = _readChunk2.WaitOne(TimeSpan.FromSeconds(5)); + // sleep a short time to make sure the client is in the blocking wait + Thread.Sleep(500); + // complete async read of chunk2 with exception + var asyncResult = new SftpReadAsyncResult(callback, state); + asyncResult.SetAsCompleted(_exception, false); + }); + }) + .Returns((SftpReadAsyncResult)null); + _ = SftpSessionMock.InSequence(_seq) + .Setup(p => p.OperationTimeout) + .Returns(_operationTimeout); + _ = SftpSessionMock.InSequence(_seq) + .Setup(p => p.WaitAny(_waitHandleArray, _operationTimeout)) + .Returns(() => WaitAny(_waitHandleArray, _operationTimeout)); } protected override void Arrange() @@ -110,16 +118,16 @@ protected override void Arrange() protected override void Act() { - _reader.Read(); + _ = _reader.Read(); // wait until SftpFileReader has starting reading ahead chunk 2 Assert.IsTrue(_readAheadChunk2.WaitOne(TimeSpan.FromSeconds(5))); // signal that we are about to read chunk 2 - _readChunk2.Set(); + _ = _readChunk2.Set(); try { - _reader.Read(); + _ = _reader.Read(); Assert.Fail(); } catch (SshException ex) @@ -140,7 +148,7 @@ public void ReadAfterReadAheadExceptionShouldRethrowExceptionThatOccurredInReadA { try { - _reader.Read(); + _ = _reader.Read(); Assert.Fail(); } catch (SshException ex) @@ -152,9 +160,14 @@ public void ReadAfterReadAheadExceptionShouldRethrowExceptionThatOccurredInReadA [TestMethod] public void DisposeShouldCloseHandleAndCompleteImmediately() { - SftpSessionMock.InSequence(_seq).Setup(p => p.IsOpen).Returns(true); - SftpSessionMock.InSequence(_seq).Setup(p => p.BeginClose(_handle, null, null)).Returns(_closeAsyncResult); - SftpSessionMock.InSequence(_seq).Setup(p => p.EndClose(_closeAsyncResult)); + _ = SftpSessionMock.InSequence(_seq) + .Setup(p => p.IsOpen) + .Returns(true); + _ = SftpSessionMock.InSequence(_seq) + .Setup(p => p.BeginClose(_handle, null, null)) + .Returns(_closeAsyncResult); + _ = SftpSessionMock.InSequence(_seq) + .Setup(p => p.EndClose(_closeAsyncResult)); var stopwatch = Stopwatch.StartNew(); _reader.Dispose(); diff --git a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileReaderTest_ReadBackBeginReadException.cs b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileReaderTest_ReadBackBeginReadException.cs index f00a0273a..a89d4c977 100644 --- a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileReaderTest_ReadBackBeginReadException.cs +++ b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileReaderTest_ReadBackBeginReadException.cs @@ -1,9 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace Renci.SshNet.Tests.Classes.Sftp +namespace Renci.SshNet.Tests.Classes.Sftp { class SftpFileReaderTest_ReadBackBeginReadException { diff --git a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileReaderTest_ReadBackEndInvokeException.cs b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileReaderTest_ReadBackEndInvokeException.cs index 19c816fc8..324dbd3d4 100644 --- a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileReaderTest_ReadBackEndInvokeException.cs +++ b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileReaderTest_ReadBackEndInvokeException.cs @@ -1,9 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace Renci.SshNet.Tests.Classes.Sftp +namespace Renci.SshNet.Tests.Classes.Sftp { class SftpFileReaderTest_ReadBackEndInvokeException { diff --git a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_CanWrite_Disposed_FileAccessWrite.cs b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_CanWrite_Disposed_FileAccessWrite.cs index 1d8c3393c..4474cafdf 100644 --- a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_CanWrite_Disposed_FileAccessWrite.cs +++ b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_CanWrite_Disposed_FileAccessWrite.cs @@ -31,17 +31,20 @@ protected override void SetupData() protected override void SetupMocks() { - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.RequestOpen(_path, Flags.Write, false)) - .Returns(_handle); - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.CalculateOptimalReadLength(_bufferSize)) - .Returns(_readBufferSize); - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.CalculateOptimalWriteLength(_bufferSize, _handle)) - .Returns(_writeBufferSize); - SftpSessionMock.InSequence(MockSequence).Setup(p => p.IsOpen).Returns(true); - SftpSessionMock.InSequence(MockSequence).Setup(p => p.RequestClose(_handle)); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.RequestOpen(_path, Flags.Write, false)) + .Returns(_handle); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.CalculateOptimalReadLength(_bufferSize)) + .Returns(_readBufferSize); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.CalculateOptimalWriteLength(_bufferSize, _handle)) + .Returns(_writeBufferSize); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.IsOpen) + .Returns(true); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.RequestClose(_handle)); } protected override void Arrange() diff --git a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_Close_Closed.cs b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_Close_Closed.cs index 760b65eae..b52537fb8 100644 --- a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_Close_Closed.cs +++ b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_Close_Closed.cs @@ -1,8 +1,11 @@ using System; using System.Globalization; using System.IO; + using Microsoft.VisualStudio.TestTools.UnitTesting; + using Moq; + using Renci.SshNet.Sftp; namespace Renci.SshNet.Tests.Classes.Sftp @@ -37,20 +40,21 @@ protected void Arrange() _sftpSessionMock = new Mock(MockBehavior.Strict); var sequence = new MockSequence(); - _sftpSessionMock.InSequence(sequence) - .Setup(p => p.RequestOpen(_path, Flags.Read, false)) - .Returns(_handle); - _sftpSessionMock.InSequence(sequence) - .Setup(p => p.CalculateOptimalReadLength(_bufferSize)) - .Returns(_readBufferSize); - _sftpSessionMock.InSequence(sequence) - .Setup(p => p.CalculateOptimalWriteLength(_bufferSize, _handle)) - .Returns(_writeBufferSize); - _sftpSessionMock.InSequence(sequence) - .Setup(p => p.IsOpen) - .Returns(true); - _sftpSessionMock.InSequence(sequence) - .Setup(p => p.RequestClose(_handle)); + + _ = _sftpSessionMock.InSequence(sequence) + .Setup(p => p.RequestOpen(_path, Flags.Read, false)) + .Returns(_handle); + _ = _sftpSessionMock.InSequence(sequence) + .Setup(p => p.CalculateOptimalReadLength(_bufferSize)) + .Returns(_readBufferSize); + _ = _sftpSessionMock.InSequence(sequence) + .Setup(p => p.CalculateOptimalWriteLength(_bufferSize, _handle)) + .Returns(_writeBufferSize); + _ = _sftpSessionMock.InSequence(sequence) + .Setup(p => p.IsOpen) + .Returns(true); + _ = _sftpSessionMock.InSequence(sequence) + .Setup(p => p.RequestClose(_handle)); _sftpFileStream = new SftpFileStream(_sftpSessionMock.Object, _path, FileMode.Open, FileAccess.Read, (int)_bufferSize); _sftpFileStream.Close(); diff --git a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_Close_Disposed.cs b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_Close_Disposed.cs index 08a3399ea..59a6357b5 100644 --- a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_Close_Disposed.cs +++ b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_Close_Disposed.cs @@ -30,17 +30,20 @@ protected override void SetupData() protected override void SetupMocks() { - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.RequestOpen(_path, Flags.Read, false)) - .Returns(_handle); - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.CalculateOptimalReadLength(_bufferSize)) - .Returns(_readBufferSize); - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.CalculateOptimalWriteLength(_bufferSize, _handle)) - .Returns(_writeBufferSize); - SftpSessionMock.InSequence(MockSequence).Setup(p => p.IsOpen).Returns(true); - SftpSessionMock.InSequence(MockSequence).Setup(p => p.RequestClose(_handle)); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.RequestOpen(_path, Flags.Read, false)) + .Returns(_handle); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.CalculateOptimalReadLength(_bufferSize)) + .Returns(_readBufferSize); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.CalculateOptimalWriteLength(_bufferSize, _handle)) + .Returns(_writeBufferSize); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.IsOpen) + .Returns(true); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.RequestClose(_handle)); } protected override void Arrange() diff --git a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_Close_SessionOpen.cs b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_Close_SessionOpen.cs index c2ec5c4c1..8ad19bce6 100644 --- a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_Close_SessionOpen.cs +++ b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_Close_SessionOpen.cs @@ -1,8 +1,10 @@ using System; -using System.Globalization; using System.IO; + using Microsoft.VisualStudio.TestTools.UnitTesting; + using Moq; + using Renci.SshNet.Sftp; namespace Renci.SshNet.Tests.Classes.Sftp @@ -31,20 +33,20 @@ protected override void SetupData() protected override void SetupMocks() { - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.RequestOpen(_path, Flags.Read, false)) - .Returns(_handle); - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.CalculateOptimalReadLength(_bufferSize)) - .Returns(_readBufferSize); - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.CalculateOptimalWriteLength(_bufferSize, _handle)) - .Returns(_writeBufferSize); - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.IsOpen) - .Returns(true); - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.RequestClose(_handle)); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.RequestOpen(_path, Flags.Read, false)) + .Returns(_handle); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.CalculateOptimalReadLength(_bufferSize)) + .Returns(_readBufferSize); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.CalculateOptimalWriteLength(_bufferSize, _handle)) + .Returns(_writeBufferSize); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.IsOpen) + .Returns(true); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.RequestClose(_handle)); } protected override void Arrange() diff --git a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_Ctor_FileModeAppend_FileAccessWrite.cs b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_Ctor_FileModeAppend_FileAccessWrite.cs index 871830670..25171b9f3 100644 --- a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_Ctor_FileModeAppend_FileAccessWrite.cs +++ b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_Ctor_FileModeAppend_FileAccessWrite.cs @@ -45,18 +45,18 @@ protected override void SetupData() protected override void SetupMocks() { - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.RequestOpen(_path, Flags.Write | Flags.Append | Flags.CreateNewOrOpen, false)) - .Returns(_handle); - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.CalculateOptimalReadLength((uint) _bufferSize)) - .Returns(_readBufferSize); - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.CalculateOptimalWriteLength((uint) _bufferSize, _handle)) - .Returns(_writeBufferSize); - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.RequestFStat(_handle, false)) - .Returns(_fileAttributes); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.RequestOpen(_path, Flags.Write | Flags.Append | Flags.CreateNewOrOpen, false)) + .Returns(_handle); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.CalculateOptimalReadLength((uint) _bufferSize)) + .Returns(_readBufferSize); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.CalculateOptimalWriteLength((uint) _bufferSize, _handle)) + .Returns(_writeBufferSize); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.RequestFStat(_handle, false)) + .Returns(_fileAttributes); } protected override void Act() @@ -95,7 +95,9 @@ public void CanTimeoutShouldReturnTrue() [TestMethod] public void PositionShouldReturnSizeOfFile() { - SftpSessionMock.InSequence(MockSequence).Setup(p => p.IsOpen).Returns(true); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.IsOpen) + .Returns(true); var actual = _target.Position; @@ -109,11 +111,13 @@ public void ReadShouldThrowNotSupportedException() { var buffer = new byte[_readBufferSize]; - SftpSessionMock.InSequence(MockSequence).Setup(p => p.IsOpen).Returns(true); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.IsOpen) + .Returns(true); try { - _target.Read(buffer, 0, buffer.Length); + _ = _target.Read(buffer, 0, buffer.Length); Assert.Fail(); } catch (NotSupportedException ex) @@ -128,11 +132,13 @@ public void ReadShouldThrowNotSupportedException() [TestMethod] public void ReadByteShouldThrowNotSupportedException() { - SftpSessionMock.InSequence(MockSequence).Setup(p => p.IsOpen).Returns(true); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.IsOpen) + .Returns(true); try { - _target.ReadByte(); + _ = _target.ReadByte(); Assert.Fail(); } catch (NotSupportedException ex) @@ -149,8 +155,11 @@ public void WriteShouldStartWritingAtEndOfFile() { var buffer = new byte[_writeBufferSize]; - SftpSessionMock.InSequence(MockSequence).Setup(p => p.IsOpen).Returns(true); - SftpSessionMock.InSequence(MockSequence).Setup(p => p.RequestWrite(_handle, (ulong) _fileAttributes.Size, buffer, 0, buffer.Length, It.IsNotNull(), null)); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.IsOpen) + .Returns(true); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.RequestWrite(_handle, (ulong) _fileAttributes.Size, buffer, 0, buffer.Length, It.IsNotNull(), null)); _target.Write(buffer, 0, buffer.Length); diff --git a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_Ctor_FileModeCreateNew_FileAccessRead.cs b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_Ctor_FileModeCreateNew_FileAccessRead.cs index bce4afba1..47cabd2a6 100644 --- a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_Ctor_FileModeCreateNew_FileAccessRead.cs +++ b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_Ctor_FileModeCreateNew_FileAccessRead.cs @@ -1,6 +1,8 @@ using System; using System.IO; + using Microsoft.VisualStudio.TestTools.UnitTesting; + using Renci.SshNet.Sftp; namespace Renci.SshNet.Tests.Classes.Sftp @@ -34,7 +36,7 @@ protected override void Act() { try { - new SftpFileStream(SftpSessionMock.Object, _path, _fileMode, _fileAccess, _bufferSize); + _ = new SftpFileStream(SftpSessionMock.Object, _path, _fileMode, _fileAccess, _bufferSize); Assert.Fail(); } catch (ArgumentException ex) @@ -48,7 +50,7 @@ public void CtorShouldHaveThrownArgumentException() { Assert.IsNotNull(_actualException); Assert.IsNull(_actualException.InnerException); - Assert.AreEqual(string.Format("Combining {0}: {1} with {2}: {3} is invalid.", typeof(FileMode).Name, _fileMode, typeof(FileAccess).Name, _fileAccess), _actualException.Message); + Assert.AreEqual(string.Format("Combining {0}: {1} with {2}: {3} is invalid.", nameof(FileMode), _fileMode, nameof(FileAccess), _fileAccess), _actualException.Message); Assert.IsNull(_actualException.ParamName); } } diff --git a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_Ctor_FileModeCreateNew_FileAccessReadWrite.cs b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_Ctor_FileModeCreateNew_FileAccessReadWrite.cs index c6a87ce12..c8e46a2b2 100644 --- a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_Ctor_FileModeCreateNew_FileAccessReadWrite.cs +++ b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_Ctor_FileModeCreateNew_FileAccessReadWrite.cs @@ -37,15 +37,15 @@ protected override void SetupData() protected override void SetupMocks() { - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.RequestOpen(_path, Flags.Read | Flags.Write | Flags.CreateNew, false)) - .Returns(_handle); - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.CalculateOptimalReadLength((uint) _bufferSize)) - .Returns(_readBufferSize); - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.CalculateOptimalWriteLength((uint) _bufferSize, _handle)) - .Returns(_writeBufferSize); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.RequestOpen(_path, Flags.Read | Flags.Write | Flags.CreateNew, false)) + .Returns(_handle); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.CalculateOptimalReadLength((uint) _bufferSize)) + .Returns(_readBufferSize); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.CalculateOptimalWriteLength((uint) _bufferSize, _handle)) + .Returns(_writeBufferSize); } protected override void Act() @@ -84,7 +84,9 @@ public void CanTimeoutShouldReturnTrue() [TestMethod] public void PositionShouldReturnZero() { - SftpSessionMock.InSequence(MockSequence).Setup(p => p.IsOpen).Returns(true); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.IsOpen) + .Returns(true); var actual = _target.Position; @@ -100,8 +102,12 @@ public void ReadShouldStartReadingAtBeginningOfFile() var data = new byte[] { 5, 4, 3, 2, 1 }; var expected = new byte[] { 0, 5, 4, 3, 2, 1, 0, 0 }; - SftpSessionMock.InSequence(MockSequence).Setup(p => p.IsOpen).Returns(true); - SftpSessionMock.InSequence(MockSequence).Setup(p => p.RequestRead(_handle, 0UL, _readBufferSize)).Returns(data); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.IsOpen) + .Returns(true); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.RequestRead(_handle, 0UL, _readBufferSize)) + .Returns(data); var actual = _target.Read(buffer, 1, data.Length); @@ -117,9 +123,12 @@ public void ReadByteShouldStartReadingAtBeginningOfFile() { var data = GenerateRandom(5, _random); - SftpSessionMock.InSequence(MockSequence).Setup(p => p.IsOpen).Returns(true); - SftpSessionMock.InSequence(MockSequence).Setup(p => p.RequestRead(_handle, 0UL, _readBufferSize)) - .Returns(data); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.IsOpen) + .Returns(true); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.RequestRead(_handle, 0UL, _readBufferSize)) + .Returns(data); var actual = _target.ReadByte(); @@ -134,8 +143,11 @@ public void WriteShouldStartWritingAtBeginningOfFile() { var buffer = new byte[_writeBufferSize]; - SftpSessionMock.InSequence(MockSequence).Setup(p => p.IsOpen).Returns(true); - SftpSessionMock.InSequence(MockSequence).Setup(p => p.RequestWrite(_handle, 0UL, buffer, 0, buffer.Length, It.IsNotNull(), null)); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.IsOpen) + .Returns(true); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.RequestWrite(_handle, 0UL, buffer, 0, buffer.Length, It.IsNotNull(), null)); _target.Write(buffer, 0, buffer.Length); diff --git a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_Ctor_FileModeCreate_FileAccessRead.cs b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_Ctor_FileModeCreate_FileAccessRead.cs index 493e48192..29e4956ac 100644 --- a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_Ctor_FileModeCreate_FileAccessRead.cs +++ b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_Ctor_FileModeCreate_FileAccessRead.cs @@ -1,6 +1,8 @@ using System; using System.IO; + using Microsoft.VisualStudio.TestTools.UnitTesting; + using Renci.SshNet.Sftp; namespace Renci.SshNet.Tests.Classes.Sftp @@ -34,7 +36,7 @@ protected override void Act() { try { - new SftpFileStream(SftpSessionMock.Object, _path, _fileMode, _fileAccess, _bufferSize); + _ =new SftpFileStream(SftpSessionMock.Object, _path, _fileMode, _fileAccess, _bufferSize); Assert.Fail(); } catch (ArgumentException ex) @@ -48,7 +50,7 @@ public void CtorShouldHaveThrownArgumentException() { Assert.IsNotNull(_actualException); Assert.IsNull(_actualException.InnerException); - Assert.AreEqual(string.Format("Combining {0}: {1} with {2}: {3} is invalid.", typeof(FileMode).Name, _fileMode, typeof(FileAccess).Name, _fileAccess), _actualException.Message); + Assert.AreEqual(string.Format("Combining {0}: {1} with {2}: {3} is invalid.", nameof(FileMode), _fileMode, nameof(FileAccess), _fileAccess), _actualException.Message); Assert.IsNull(_actualException.ParamName); } } diff --git a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_Ctor_FileModeCreate_FileAccessReadWrite_FileDoesNotExist.cs b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_Ctor_FileModeCreate_FileAccessReadWrite_FileDoesNotExist.cs index 8b8f50fba..73052060a 100644 --- a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_Ctor_FileModeCreate_FileAccessReadWrite_FileDoesNotExist.cs +++ b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_Ctor_FileModeCreate_FileAccessReadWrite_FileDoesNotExist.cs @@ -37,18 +37,18 @@ protected override void SetupData() protected override void SetupMocks() { - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.RequestOpen(_path, Flags.Read | Flags.Write | Flags.Truncate, true)) - .Returns((byte[]) null); - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.RequestOpen(_path, Flags.Read | Flags.Write | Flags.CreateNew, false)) - .Returns(_handle); - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.CalculateOptimalReadLength((uint) _bufferSize)) - .Returns(_readBufferSize); - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.CalculateOptimalWriteLength((uint) _bufferSize, _handle)) - .Returns(_writeBufferSize); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.RequestOpen(_path, Flags.Read | Flags.Write | Flags.Truncate, true)) + .Returns((byte[]) null); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.RequestOpen(_path, Flags.Read | Flags.Write | Flags.CreateNew, false)) + .Returns(_handle); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.CalculateOptimalReadLength((uint) _bufferSize)) + .Returns(_readBufferSize); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.CalculateOptimalWriteLength((uint) _bufferSize, _handle)) + .Returns(_writeBufferSize); } protected override void Act() @@ -87,7 +87,9 @@ public void CanTimeoutShouldReturnTrue() [TestMethod] public void PositionShouldReturnZero() { - SftpSessionMock.InSequence(MockSequence).Setup(p => p.IsOpen).Returns(true); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.IsOpen) + .Returns(true); var actual = _target.Position; @@ -103,8 +105,12 @@ public void ReadShouldStartReadingAtBeginningOfFile() var data = new byte[] { 5, 4, 3, 2, 1 }; var expected = new byte[] { 0, 5, 4, 3, 2, 1, 0, 0 }; - SftpSessionMock.InSequence(MockSequence).Setup(p => p.IsOpen).Returns(true); - SftpSessionMock.InSequence(MockSequence).Setup(p => p.RequestRead(_handle, 0UL, _readBufferSize)).Returns(data); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.IsOpen) + .Returns(true); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.RequestRead(_handle, 0UL, _readBufferSize)) + .Returns(data); var actual = _target.Read(buffer, 1, data.Length); @@ -120,9 +126,12 @@ public void ReadByteShouldStartReadingAtBeginningOfFile() { var data = GenerateRandom(5, _random); - SftpSessionMock.InSequence(MockSequence).Setup(p => p.IsOpen).Returns(true); - SftpSessionMock.InSequence(MockSequence).Setup(p => p.RequestRead(_handle, 0UL, _readBufferSize)) - .Returns(data); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.IsOpen) + .Returns(true); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.RequestRead(_handle, 0UL, _readBufferSize)) + .Returns(data); var actual = _target.ReadByte(); @@ -137,8 +146,11 @@ public void WriteShouldStartWritingAtBeginningOfFile() { var buffer = new byte[_writeBufferSize]; - SftpSessionMock.InSequence(MockSequence).Setup(p => p.IsOpen).Returns(true); - SftpSessionMock.InSequence(MockSequence).Setup(p => p.RequestWrite(_handle, 0UL, buffer, 0, buffer.Length, It.IsNotNull(), null)); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.IsOpen) + .Returns(true); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.RequestWrite(_handle, 0UL, buffer, 0, buffer.Length, It.IsNotNull(), null)); _target.Write(buffer, 0, buffer.Length); diff --git a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_Ctor_FileModeTruncate_FileAccessRead.cs b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_Ctor_FileModeTruncate_FileAccessRead.cs index c0a216671..2ed977784 100644 --- a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_Ctor_FileModeTruncate_FileAccessRead.cs +++ b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_Ctor_FileModeTruncate_FileAccessRead.cs @@ -34,7 +34,7 @@ protected override void Act() { try { - new SftpFileStream(SftpSessionMock.Object, _path, _fileMode, _fileAccess, _bufferSize); + _ = new SftpFileStream(SftpSessionMock.Object, _path, _fileMode, _fileAccess, _bufferSize); Assert.Fail(); } catch (ArgumentException ex) @@ -48,7 +48,7 @@ public void CtorShouldHaveThrownArgumentException() { Assert.IsNotNull(_actualException); Assert.IsNull(_actualException.InnerException); - Assert.AreEqual(string.Format("Combining {0}: {1} with {2}: {3} is invalid.", typeof(FileMode).Name, _fileMode, typeof(FileAccess).Name, _fileAccess), _actualException.Message); + Assert.AreEqual(string.Format("Combining {0}: {1} with {2}: {3} is invalid.", nameof(FileMode), _fileMode, nameof(FileAccess), _fileAccess), _actualException.Message); Assert.IsNull(_actualException.ParamName); } } diff --git a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_Ctor_FileModeTruncate_FileAccessReadWrite.cs b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_Ctor_FileModeTruncate_FileAccessReadWrite.cs index db3d9b997..59e669c55 100644 --- a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_Ctor_FileModeTruncate_FileAccessReadWrite.cs +++ b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_Ctor_FileModeTruncate_FileAccessReadWrite.cs @@ -1,8 +1,11 @@ using System; using System.IO; using System.Threading; + using Microsoft.VisualStudio.TestTools.UnitTesting; + using Moq; + using Renci.SshNet.Common; using Renci.SshNet.Sftp; @@ -37,15 +40,15 @@ protected override void SetupData() protected override void SetupMocks() { - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.RequestOpen(_path, Flags.Read | Flags.Write | Flags.Truncate, false)) - .Returns(_handle); - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.CalculateOptimalReadLength((uint) _bufferSize)) - .Returns(_readBufferSize); - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.CalculateOptimalWriteLength((uint) _bufferSize, _handle)) - .Returns(_writeBufferSize); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.RequestOpen(_path, Flags.Read | Flags.Write | Flags.Truncate, false)) + .Returns(_handle); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.CalculateOptimalReadLength((uint) _bufferSize)) + .Returns(_readBufferSize); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.CalculateOptimalWriteLength((uint) _bufferSize, _handle)) + .Returns(_writeBufferSize); } protected override void Act() @@ -84,7 +87,9 @@ public void CanTimeoutShouldReturnTrue() [TestMethod] public void PositionShouldReturnZero() { - SftpSessionMock.InSequence(MockSequence).Setup(p => p.IsOpen).Returns(true); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.IsOpen) + .Returns(true); var actual = _target.Position; @@ -100,8 +105,12 @@ public void ReadShouldStartReadingAtBeginningOfFile() var data = new byte[] { 5, 4, 3, 2, 1 }; var expected = new byte[] { 0, 5, 4, 3, 2, 1, 0, 0 }; - SftpSessionMock.InSequence(MockSequence).Setup(p => p.IsOpen).Returns(true); - SftpSessionMock.InSequence(MockSequence).Setup(p => p.RequestRead(_handle, 0UL, _readBufferSize)).Returns(data); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.IsOpen) + .Returns(true); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.RequestRead(_handle, 0UL, _readBufferSize)) + .Returns(data); var actual = _target.Read(buffer, 1, data.Length); @@ -117,9 +126,12 @@ public void ReadByteShouldStartReadingAtBeginningOfFile() { var data = GenerateRandom(5, _random); - SftpSessionMock.InSequence(MockSequence).Setup(p => p.IsOpen).Returns(true); - SftpSessionMock.InSequence(MockSequence).Setup(p => p.RequestRead(_handle, 0UL, _readBufferSize)) - .Returns(data); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.IsOpen) + .Returns(true); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.RequestRead(_handle, 0UL, _readBufferSize)) + .Returns(data); var actual = _target.ReadByte(); @@ -134,8 +146,11 @@ public void WriteShouldStartWritingAtBeginningOfFile() { var buffer = new byte[_writeBufferSize]; - SftpSessionMock.InSequence(MockSequence).Setup(p => p.IsOpen).Returns(true); - SftpSessionMock.InSequence(MockSequence).Setup(p => p.RequestWrite(_handle, 0UL, buffer, 0, buffer.Length, It.IsNotNull(), null)); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.IsOpen) + .Returns(true); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.RequestWrite(_handle, 0UL, buffer, 0, buffer.Length, It.IsNotNull(), null)); _target.Write(buffer, 0, buffer.Length); diff --git a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_Dispose_Closed.cs b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_Dispose_Closed.cs index 2bfe54285..0c6986242 100644 --- a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_Dispose_Closed.cs +++ b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_Dispose_Closed.cs @@ -1,7 +1,10 @@ using System; using System.IO; + using Microsoft.VisualStudio.TestTools.UnitTesting; + using Moq; + using Renci.SshNet.Sftp; namespace Renci.SshNet.Tests.Classes.Sftp @@ -30,17 +33,20 @@ protected override void SetupData() protected override void SetupMocks() { - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.RequestOpen(_path, Flags.Read, false)) - .Returns(_handle); - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.CalculateOptimalReadLength(_bufferSize)) - .Returns(_readBufferSize); - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.CalculateOptimalWriteLength(_bufferSize, _handle)) - .Returns(_writeBufferSize); - SftpSessionMock.InSequence(MockSequence).Setup(p => p.IsOpen).Returns(true); - SftpSessionMock.InSequence(MockSequence).Setup(p => p.RequestClose(_handle)); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.RequestOpen(_path, Flags.Read, false)) + .Returns(_handle); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.CalculateOptimalReadLength(_bufferSize)) + .Returns(_readBufferSize); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.CalculateOptimalWriteLength(_bufferSize, _handle)) + .Returns(_writeBufferSize); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.IsOpen) + .Returns(true); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.RequestClose(_handle)); } protected override void Arrange() diff --git a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_Dispose_SessionNotOpen.cs b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_Dispose_SessionNotOpen.cs index d340b4034..e1aae67bc 100644 --- a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_Dispose_SessionNotOpen.cs +++ b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_Dispose_SessionNotOpen.cs @@ -1,7 +1,10 @@ using System; using System.IO; + using Microsoft.VisualStudio.TestTools.UnitTesting; + using Moq; + using Renci.SshNet.Sftp; namespace Renci.SshNet.Tests.Classes.Sftp @@ -30,17 +33,20 @@ protected override void SetupData() protected override void SetupMocks() { - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.RequestOpen(_path, Flags.Write | Flags.CreateNew, false)) - .Returns(_handle); - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.CalculateOptimalReadLength(_bufferSize)) - .Returns(_readBufferSize); - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.CalculateOptimalWriteLength(_bufferSize, _handle)) - .Returns(_writeBufferSize); - SftpSessionMock.InSequence(MockSequence).Setup(p => p.IsOpen).Returns(false); - SftpSessionMock.InSequence(MockSequence).Setup(p => p.RequestClose(_handle)); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.RequestOpen(_path, Flags.Write | Flags.CreateNew, false)) + .Returns(_handle); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.CalculateOptimalReadLength(_bufferSize)) + .Returns(_readBufferSize); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.CalculateOptimalWriteLength(_bufferSize, _handle)) + .Returns(_writeBufferSize); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.IsOpen) + .Returns(false); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.RequestClose(_handle)); } protected override void Arrange() diff --git a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_Dispose_SessionOpen.cs b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_Dispose_SessionOpen.cs index 35563fcc1..9429579f0 100644 --- a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_Dispose_SessionOpen.cs +++ b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_Dispose_SessionOpen.cs @@ -1,8 +1,11 @@ using System; using System.Globalization; using System.IO; + using Microsoft.VisualStudio.TestTools.UnitTesting; + using Moq; + using Renci.SshNet.Sftp; namespace Renci.SshNet.Tests.Classes.Sftp @@ -31,17 +34,19 @@ protected override void SetupData() protected override void SetupMocks() { - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.RequestOpen(_path, Flags.Write | Flags.Truncate, false)) - .Returns(_handle); - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.CalculateOptimalReadLength(_bufferSize)) - .Returns(_readBufferSize); - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.CalculateOptimalWriteLength(_bufferSize, _handle)) - .Returns(_writeBufferSize); - SftpSessionMock.InSequence(MockSequence).Setup(p => p.IsOpen).Returns(true); - SftpSessionMock.InSequence(MockSequence).Setup(p => p.RequestClose(_handle)); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.RequestOpen(_path, Flags.Write | Flags.Truncate, false)) + .Returns(_handle); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.CalculateOptimalReadLength(_bufferSize)) + .Returns(_readBufferSize); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.CalculateOptimalWriteLength(_bufferSize, _handle)) + .Returns(_writeBufferSize); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.IsOpen).Returns(true); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.RequestClose(_handle)); } protected override void Arrange() diff --git a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_Finalize_SessionOpen.cs b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_Finalize_SessionOpen.cs index 41312f668..7ea748873 100644 --- a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_Finalize_SessionOpen.cs +++ b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_Finalize_SessionOpen.cs @@ -10,7 +10,7 @@ namespace Renci.SshNet.Tests.Classes.Sftp [TestClass] public class SftpFileStreamTest_Finalize_SessionOpen : SftpFileStreamTestBase { - private SftpFileStream _target; + private WeakReference _target; private string _path; private byte[] _handle; private uint _bufferSize; @@ -31,29 +31,27 @@ protected override void SetupData() protected override void SetupMocks() { - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.RequestOpen(_path, Flags.Read | Flags.Write | Flags.CreateNewOrOpen, false)) - .Returns(_handle); - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.CalculateOptimalReadLength(_bufferSize)) - .Returns(_readBufferSize); - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.CalculateOptimalWriteLength(_bufferSize, _handle)) - .Returns(_writeBufferSize); - SftpSessionMock.InSequence(MockSequence).Setup(p => p.IsOpen).Returns(true); - SftpSessionMock.InSequence(MockSequence).Setup(p => p.RequestClose(_handle)); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.RequestOpen(_path, Flags.Read | Flags.Write | Flags.CreateNewOrOpen, false)) + .Returns(_handle); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.CalculateOptimalReadLength(_bufferSize)) + .Returns(_readBufferSize); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.CalculateOptimalWriteLength(_bufferSize, _handle)) + .Returns(_writeBufferSize); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.IsOpen) + .Returns(true); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.RequestClose(_handle)); } protected override void Arrange() { base.Arrange(); - _target = new SftpFileStream(SftpSessionMock.Object, - _path, - FileMode.OpenOrCreate, - FileAccess.ReadWrite, - (int) _bufferSize); - _target = null; + _target = CreateWeakSftpFileStream(); } protected override void Act() @@ -62,6 +60,12 @@ protected override void Act() GC.WaitForPendingFinalizers(); } + [TestMethod] + public void SftpFileStreamShouldHaveBeenFinalized() + { + Assert.IsFalse(_target.TryGetTarget(out _)); + } + [TestMethod] public void IsOpenOnSftpSessionShouldNeverBeInvoked() { @@ -73,5 +77,15 @@ public void RequestCloseOnSftpSessionShouldNeverBeInvoked() { SftpSessionMock.Verify(p => p.RequestClose(_handle), Times.Never); } + + private WeakReference CreateWeakSftpFileStream() + { + var sftpFileStream = new SftpFileStream(SftpSessionMock.Object, + _path, + FileMode.OpenOrCreate, + FileAccess.ReadWrite, + (int) _bufferSize); + return new WeakReference(sftpFileStream); + } } } diff --git a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_Flush_ReadMode_DataInBuffer_NotReadFromBuffer.cs b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_Flush_ReadMode_DataInBuffer_NotReadFromBuffer.cs index ee44c62f7..9795c514a 100644 --- a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_Flush_ReadMode_DataInBuffer_NotReadFromBuffer.cs +++ b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_Flush_ReadMode_DataInBuffer_NotReadFromBuffer.cs @@ -1,10 +1,13 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using System; +using System.IO; + +using Microsoft.VisualStudio.TestTools.UnitTesting; + using Moq; + using Renci.SshNet.Common; using Renci.SshNet.Sftp; using Renci.SshNet.Tests.Common; -using System; -using System.IO; namespace Renci.SshNet.Tests.Classes.Sftp { @@ -36,24 +39,24 @@ protected override void SetupData() protected override void SetupMocks() { - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.RequestOpen(_path, Flags.Read, false)) - .Returns(_handle); - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.CalculateOptimalReadLength(_bufferSize)) - .Returns(_readBufferSize); - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.CalculateOptimalWriteLength(_bufferSize, _handle)) - .Returns(_writeBufferSize); - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.IsOpen) - .Returns(true); - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.RequestRead(_handle, 0UL, _readBufferSize)) - .Returns(_serverBytes); - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.IsOpen) - .Returns(true); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.RequestOpen(_path, Flags.Read, false)) + .Returns(_handle); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.CalculateOptimalReadLength(_bufferSize)) + .Returns(_readBufferSize); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.CalculateOptimalWriteLength(_bufferSize, _handle)) + .Returns(_writeBufferSize); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.IsOpen) + .Returns(true); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.RequestRead(_handle, 0UL, _readBufferSize)) + .Returns(_serverBytes); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.IsOpen) + .Returns(true); } protected override void Arrange() @@ -65,7 +68,7 @@ protected override void Arrange() FileMode.Open, FileAccess.Read, (int)_bufferSize); - _target.Read(_readBytes, 0, _readBytes.Length); + _ = _target.Read(_readBytes, 0, _readBytes.Length); } protected override void Act() @@ -76,9 +79,9 @@ protected override void Act() [TestMethod] public void PositionShouldReturnSameValueAsBeforeFlush() { - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.IsOpen) - .Returns(true); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.IsOpen) + .Returns(true); Assert.AreEqual(_readBytes.Length, _target.Position); @@ -94,12 +97,12 @@ public void ReadShouldReadFromServer() .Add(serverBytes2.Take(0, 3)) .Build(); - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.IsOpen) - .Returns(true); - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.RequestRead(_handle, (ulong)_readBytes.Length, _readBufferSize)) - .Returns(serverBytes2); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.IsOpen) + .Returns(true); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.RequestRead(_handle, (ulong)_readBytes.Length, _readBufferSize)) + .Returns(serverBytes2); var bytesRead = _target.Read(readBytes2, 2, 3); diff --git a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_Flush_ReadMode_DataInBuffer_ReadFromBuffer.cs b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_Flush_ReadMode_DataInBuffer_ReadFromBuffer.cs index f5b25be48..d873f3209 100644 --- a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_Flush_ReadMode_DataInBuffer_ReadFromBuffer.cs +++ b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_Flush_ReadMode_DataInBuffer_ReadFromBuffer.cs @@ -26,6 +26,7 @@ protected override void SetupData() base.SetupData(); var random = new Random(); + _path = random.Next().ToString(); _handle = GenerateRandom(5, random); _bufferSize = (uint)random.Next(1, 1000); @@ -38,27 +39,27 @@ protected override void SetupData() protected override void SetupMocks() { - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.RequestOpen(_path, Flags.Read, false)) - .Returns(_handle); - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.CalculateOptimalReadLength(_bufferSize)) - .Returns(_readBufferSize); - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.CalculateOptimalWriteLength(_bufferSize, _handle)) - .Returns(_writeBufferSize); - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.IsOpen) - .Returns(true); - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.RequestRead(_handle, 0UL, _readBufferSize)) - .Returns(_serverBytes); - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.IsOpen) - .Returns(true); - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.IsOpen) - .Returns(true); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.RequestOpen(_path, Flags.Read, false)) + .Returns(_handle); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.CalculateOptimalReadLength(_bufferSize)) + .Returns(_readBufferSize); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.CalculateOptimalWriteLength(_bufferSize, _handle)) + .Returns(_writeBufferSize); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.IsOpen) + .Returns(true); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.RequestRead(_handle, 0UL, _readBufferSize)) + .Returns(_serverBytes); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.IsOpen) + .Returns(true); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.IsOpen) + .Returns(true); } protected override void Arrange() @@ -70,8 +71,8 @@ protected override void Arrange() FileMode.Open, FileAccess.Read, (int)_bufferSize); - _target.Read(_readBytes1, 0, _readBytes1.Length); - _target.Read(_readBytes2, 0, _readBytes2.Length); + _ = _target.Read(_readBytes1, 0, _readBytes1.Length); + _ = _target.Read(_readBytes2, 0, _readBytes2.Length); } protected override void Act() @@ -82,9 +83,9 @@ protected override void Act() [TestMethod] public void PositionShouldReturnSameValueAsBeforeFlush() { - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.IsOpen) - .Returns(true); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.IsOpen) + .Returns(true); Assert.AreEqual(_readBytes1.Length + _readBytes2.Length, _target.Position); @@ -100,12 +101,12 @@ public void ReadShouldReadFromServer() .Add(serverBytes3.Take(0, 2)) .Build(); - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.IsOpen) - .Returns(true); - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.RequestRead(_handle, (ulong) (_readBytes1.Length + _readBytes2.Length), _readBufferSize)) - .Returns(serverBytes3); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.IsOpen) + .Returns(true); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.RequestRead(_handle, (ulong) (_readBytes1.Length + _readBytes2.Length), _readBufferSize)) + .Returns(serverBytes3); var bytesRead = _target.Read(readBytes3, 1, 2); diff --git a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_Flush_ReadMode_NoDataInBuffer.cs b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_Flush_ReadMode_NoDataInBuffer.cs index 41ba6f439..5388971e6 100644 --- a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_Flush_ReadMode_NoDataInBuffer.cs +++ b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_Flush_ReadMode_NoDataInBuffer.cs @@ -1,10 +1,13 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using System; +using System.IO; + +using Microsoft.VisualStudio.TestTools.UnitTesting; + using Moq; + using Renci.SshNet.Common; using Renci.SshNet.Sftp; using Renci.SshNet.Tests.Common; -using System; -using System.IO; namespace Renci.SshNet.Tests.Classes.Sftp { @@ -36,24 +39,24 @@ protected override void SetupData() protected override void SetupMocks() { - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.RequestOpen(_path, Flags.Read, false)) - .Returns(_handle); - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.CalculateOptimalReadLength(_bufferSize)) - .Returns(_readBufferSize); - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.CalculateOptimalWriteLength(_bufferSize, _handle)) - .Returns(_writeBufferSize); - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.IsOpen) - .Returns(true); - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.RequestRead(_handle, 0UL, _readBufferSize)) - .Returns(_serverBytes); - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.IsOpen) - .Returns(true); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.RequestOpen(_path, Flags.Read, false)) + .Returns(_handle); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.CalculateOptimalReadLength(_bufferSize)) + .Returns(_readBufferSize); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.CalculateOptimalWriteLength(_bufferSize, _handle)) + .Returns(_writeBufferSize); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.IsOpen) + .Returns(true); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.RequestRead(_handle, 0UL, _readBufferSize)) + .Returns(_serverBytes); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.IsOpen) + .Returns(true); } protected override void Arrange() @@ -65,7 +68,7 @@ protected override void Arrange() FileMode.Open, FileAccess.Read, (int) _bufferSize); - _target.Read(_readBytes, 0, _readBytes.Length); + _ = _target.Read(_readBytes, 0, _readBytes.Length); } protected override void Act() @@ -76,9 +79,9 @@ protected override void Act() [TestMethod] public void PositionShouldReturnSameValueAsBeforeFlush() { - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.IsOpen) - .Returns(true); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.IsOpen) + .Returns(true); Assert.AreEqual(_readBytes.Length, _target.Position); @@ -94,12 +97,12 @@ public void ReadShouldReadFromServer() .Add(serverBytes2.Take(0, 3)) .Build(); - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.IsOpen) - .Returns(true); - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.RequestRead(_handle, (ulong) _readBytes.Length, _readBufferSize)) - .Returns(serverBytes2); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.IsOpen) + .Returns(true); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.RequestRead(_handle, (ulong) _readBytes.Length, _readBufferSize)) + .Returns(serverBytes2); var bytesRead = _target.Read(readBytes2, 2, 3); diff --git a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_Flush_WriteMode_DataInBuffer.cs b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_Flush_WriteMode_DataInBuffer.cs index 8dbc7066a..2bf5c2c67 100644 --- a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_Flush_WriteMode_DataInBuffer.cs +++ b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_Flush_WriteMode_DataInBuffer.cs @@ -1,12 +1,15 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using System; +using System.IO; +using System.Threading; + +using Microsoft.VisualStudio.TestTools.UnitTesting; + using Moq; + using Renci.SshNet.Common; using Renci.SshNet.Sftp; using Renci.SshNet.Sftp.Responses; using Renci.SshNet.Tests.Common; -using System; -using System.IO; -using System.Threading; namespace Renci.SshNet.Tests.Classes.Sftp { @@ -29,6 +32,7 @@ protected override void SetupData() base.SetupData(); var random = new Random(); + _path = random.Next().ToString(); _handle = GenerateRandom(5, random); _bufferSize = (uint)random.Next(1, 1000); @@ -42,42 +46,40 @@ protected override void SetupData() protected override void SetupMocks() { - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.RequestOpen(_path, Flags.Read | Flags.Write, false)) - .Returns(_handle); - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.CalculateOptimalReadLength(_bufferSize)) - .Returns(_readBufferSize); - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.CalculateOptimalWriteLength(_bufferSize, _handle)) - .Returns(_writeBufferSize); - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.IsOpen) - .Returns(true); - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.RequestWrite(_handle, 0UL, It.IsAny(), 0, _writeBytes1.Length, It.IsAny(), null)) - .Callback>((handle, serverOffset, data, offset, length, wait, writeCompleted) - => - { - wait.Set(); - }); - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.IsOpen) - .Returns(true); - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.IsOpen) - .Returns(true); - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.IsOpen) - .Returns(true); - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.RequestWrite(_handle, (ulong) _writeBytes1.Length, It.IsAny(), 0, _writeBytes2.Length + _writeBytes3.Length, It.IsAny(), null)) - .Callback>((handle, serverOffset, data, offset, length, wait, writeCompleted) - => - { - _flushedBytes = data.Take(offset, length); - wait.Set(); - }); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.RequestOpen(_path, Flags.Read | Flags.Write, false)) + .Returns(_handle); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.CalculateOptimalReadLength(_bufferSize)) + .Returns(_readBufferSize); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.CalculateOptimalWriteLength(_bufferSize, _handle)) + .Returns(_writeBufferSize); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.IsOpen) + .Returns(true); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.RequestWrite(_handle, 0UL, It.IsAny(), 0, _writeBytes1.Length, It.IsAny(), null)) + .Callback>((handle, serverOffset, data, offset, length, wait, writeCompleted) => + { + _ = wait.Set(); + }); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.IsOpen) + .Returns(true); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.IsOpen) + .Returns(true); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.IsOpen) + .Returns(true); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.RequestWrite(_handle, (ulong) _writeBytes1.Length, It.IsAny(), 0, _writeBytes2.Length + _writeBytes3.Length, It.IsAny(), null)) + .Callback>((handle, serverOffset, data, offset, length, wait, writeCompleted) => + { + _flushedBytes = data.Take(offset, length); + _ = wait.Set(); + }); } protected override void Arrange() @@ -102,9 +104,9 @@ protected override void Act() [TestMethod] public void PositionShouldReturnSameValueAsBeforeFlush() { - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.IsOpen) - .Returns(true); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.IsOpen) + .Returns(true); Assert.AreEqual(_writeBytes1.Length + _writeBytes2.Length + _writeBytes3.Length, _target.Position); @@ -131,12 +133,12 @@ public void ReadShouldReadFromServer() .Add(serverBytes.Take(0, 3)) .Build(); - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.IsOpen) - .Returns(true); - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.RequestRead(_handle, (ulong) (_writeBytes1.Length + _writeBytes2.Length + _writeBytes3.Length), _readBufferSize)) - .Returns(serverBytes); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.IsOpen) + .Returns(true); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.RequestRead(_handle, (ulong) (_writeBytes1.Length + _writeBytes2.Length + _writeBytes3.Length), _readBufferSize)) + .Returns(serverBytes); var bytesRead = _target.Read(readBytes, 2, 3); diff --git a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_OpenAsync_FileModeAppend_FileAccessWrite.cs b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_OpenAsync_FileModeAppend_FileAccessWrite.cs index a95be4233..14cce04e4 100644 --- a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_OpenAsync_FileModeAppend_FileAccessWrite.cs +++ b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_OpenAsync_FileModeAppend_FileAccessWrite.cs @@ -2,8 +2,11 @@ using System.IO; using System.Threading; using System.Threading.Tasks; + using Microsoft.VisualStudio.TestTools.UnitTesting; + using Moq; + using Renci.SshNet.Sftp; using Renci.SshNet.Tests.Common; @@ -48,18 +51,18 @@ protected override void SetupData() protected override void SetupMocks() { - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.RequestOpenAsync(_path, Flags.Write | Flags.Append | Flags.CreateNewOrOpen, _cancellationToken)) - .ReturnsAsync(_handle); - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.RequestFStatAsync(_handle, _cancellationToken)) - .ReturnsAsync(_fileAttributes); - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.CalculateOptimalReadLength((uint)_bufferSize)) - .Returns(_readBufferSize); - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.CalculateOptimalWriteLength((uint)_bufferSize, _handle)) - .Returns(_writeBufferSize); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.RequestOpenAsync(_path, Flags.Write | Flags.Append | Flags.CreateNewOrOpen, _cancellationToken)) + .ReturnsAsync(_handle); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.RequestFStatAsync(_handle, _cancellationToken)) + .ReturnsAsync(_fileAttributes); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.CalculateOptimalReadLength((uint)_bufferSize)) + .Returns(_readBufferSize); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.CalculateOptimalWriteLength((uint)_bufferSize, _handle)) + .Returns(_writeBufferSize); } protected override async Task ActAsync() @@ -95,7 +98,9 @@ public void CanTimeoutShouldReturnTrue() [TestMethod] public void PositionShouldReturnSizeOfFile() { - SftpSessionMock.InSequence(MockSequence).Setup(p => p.IsOpen).Returns(true); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.IsOpen) + .Returns(true); var actual = _target.Position; @@ -109,11 +114,13 @@ public async Task ReadShouldThrowNotSupportedException() { var buffer = new byte[_readBufferSize]; - SftpSessionMock.InSequence(MockSequence).Setup(p => p.IsOpen).Returns(true); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.IsOpen) + .Returns(true); try { - await _target.ReadAsync(buffer, 0, buffer.Length, _cancellationToken); + _ = await _target.ReadAsync(buffer, 0, buffer.Length, _cancellationToken); Assert.Fail(); } catch (NotSupportedException ex) @@ -129,8 +136,12 @@ public async Task WriteShouldStartWritingAtEndOfFile() { var buffer = new byte[_writeBufferSize]; - SftpSessionMock.InSequence(MockSequence).Setup(p => p.IsOpen).Returns(true); - SftpSessionMock.InSequence(MockSequence).Setup(p => p.RequestWriteAsync(_handle, (ulong)_fileAttributes.Size, buffer, 0, buffer.Length, _cancellationToken)).Returns(Task.CompletedTask); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.IsOpen) + .Returns(true); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.RequestWriteAsync(_handle, (ulong)_fileAttributes.Size, buffer, 0, buffer.Length, _cancellationToken)) + .Returns(Task.CompletedTask); await _target.WriteAsync(buffer, 0, buffer.Length, _cancellationToken); diff --git a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_OpenAsync_FileModeCreateNew_FileAccessRead.cs b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_OpenAsync_FileModeCreateNew_FileAccessRead.cs index a697a3c53..1d8b792dd 100644 --- a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_OpenAsync_FileModeCreateNew_FileAccessRead.cs +++ b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_OpenAsync_FileModeCreateNew_FileAccessRead.cs @@ -1,7 +1,9 @@ using System; using System.IO; using System.Threading.Tasks; + using Microsoft.VisualStudio.TestTools.UnitTesting; + using Renci.SshNet.Sftp; namespace Renci.SshNet.Tests.Classes.Sftp @@ -35,7 +37,7 @@ protected override async Task ActAsync() { try { - await SftpFileStream.OpenAsync(SftpSessionMock.Object, _path, _fileMode, _fileAccess, _bufferSize, default); + _ = await SftpFileStream.OpenAsync(SftpSessionMock.Object, _path, _fileMode, _fileAccess, _bufferSize, default); Assert.Fail(); } catch (ArgumentException ex) @@ -49,7 +51,7 @@ public void CtorShouldHaveThrownArgumentException() { Assert.IsNotNull(_actualException); Assert.IsNull(_actualException.InnerException); - Assert.AreEqual(string.Format("Combining {0}: {1} with {2}: {3} is invalid.", typeof(FileMode).Name, _fileMode, typeof(FileAccess).Name, _fileAccess), _actualException.Message); + Assert.AreEqual(string.Format("Combining {0}: {1} with {2}: {3} is invalid.", nameof(FileMode), _fileMode, nameof(FileAccess), _fileAccess), _actualException.Message); Assert.IsNull(_actualException.ParamName); } } diff --git a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_OpenAsync_FileModeCreateNew_FileAccessWrite.cs b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_OpenAsync_FileModeCreateNew_FileAccessWrite.cs index b6c6487df..98ba5c91f 100644 --- a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_OpenAsync_FileModeCreateNew_FileAccessWrite.cs +++ b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_OpenAsync_FileModeCreateNew_FileAccessWrite.cs @@ -2,8 +2,11 @@ using System.IO; using System.Threading; using System.Threading.Tasks; + using Microsoft.VisualStudio.TestTools.UnitTesting; + using Moq; + using Renci.SshNet.Sftp; namespace Renci.SshNet.Tests.Classes.Sftp @@ -39,15 +42,15 @@ protected override void SetupData() protected override void SetupMocks() { - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.RequestOpenAsync(_path, Flags.Write | Flags.CreateNew, _cancellationToken)) - .ReturnsAsync(_handle); - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.CalculateOptimalReadLength((uint) _bufferSize)) - .Returns(_readBufferSize); - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.CalculateOptimalWriteLength((uint) _bufferSize, _handle)) - .Returns(_writeBufferSize); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.RequestOpenAsync(_path, Flags.Write | Flags.CreateNew, _cancellationToken)) + .ReturnsAsync(_handle); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.CalculateOptimalReadLength((uint) _bufferSize)) + .Returns(_readBufferSize); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.CalculateOptimalWriteLength((uint) _bufferSize, _handle)) + .Returns(_writeBufferSize); } protected override async Task ActAsync() @@ -82,7 +85,9 @@ public void CanTimeoutShouldReturnTrue() [TestMethod] public void PositionShouldReturnZero() { - SftpSessionMock.InSequence(MockSequence).Setup(p => p.IsOpen).Returns(true); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.IsOpen) + .Returns(true); var actual = _target.Position; @@ -96,11 +101,13 @@ public async Task ReadShouldThrowNotSupportedException() { var buffer = new byte[_readBufferSize]; - SftpSessionMock.InSequence(MockSequence).Setup(p => p.IsOpen).Returns(true); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.IsOpen) + .Returns(true); try { - await _target.ReadAsync(buffer, 0, buffer.Length); + _ = await _target.ReadAsync(buffer, 0, buffer.Length); Assert.Fail(); } catch (NotSupportedException ex) @@ -116,8 +123,12 @@ public async Task WriteShouldStartWritingAtBeginningOfFile() { var buffer = new byte[_writeBufferSize]; - SftpSessionMock.InSequence(MockSequence).Setup(p => p.IsOpen).Returns(true); - SftpSessionMock.InSequence(MockSequence).Setup(p => p.RequestWriteAsync(_handle, 0UL, buffer, 0, buffer.Length, _cancellationToken)).Returns(Task.CompletedTask); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.IsOpen) + .Returns(true); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.RequestWriteAsync(_handle, 0UL, buffer, 0, buffer.Length, _cancellationToken)) + .Returns(Task.CompletedTask); await _target.WriteAsync(buffer, 0, buffer.Length); diff --git a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_OpenAsync_FileModeCreate_FileAccessRead.cs b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_OpenAsync_FileModeCreate_FileAccessRead.cs index 460081fca..d253c30e4 100644 --- a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_OpenAsync_FileModeCreate_FileAccessRead.cs +++ b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_OpenAsync_FileModeCreate_FileAccessRead.cs @@ -1,7 +1,9 @@ using System; using System.IO; using System.Threading.Tasks; + using Microsoft.VisualStudio.TestTools.UnitTesting; + using Renci.SshNet.Sftp; namespace Renci.SshNet.Tests.Classes.Sftp @@ -35,7 +37,7 @@ protected override async Task ActAsync() { try { - await SftpFileStream.OpenAsync(SftpSessionMock.Object, _path, _fileMode, _fileAccess, _bufferSize, default); + _ = await SftpFileStream.OpenAsync(SftpSessionMock.Object, _path, _fileMode, _fileAccess, _bufferSize, default); Assert.Fail(); } catch (ArgumentException ex) @@ -49,7 +51,7 @@ public void CtorShouldHaveThrownArgumentException() { Assert.IsNotNull(_actualException); Assert.IsNull(_actualException.InnerException); - Assert.AreEqual(string.Format("Combining {0}: {1} with {2}: {3} is invalid.", typeof(FileMode).Name, _fileMode, typeof(FileAccess).Name, _fileAccess), _actualException.Message); + Assert.AreEqual(string.Format("Combining {0}: {1} with {2}: {3} is invalid.", nameof(FileMode), _fileMode, nameof(FileAccess), _fileAccess), _actualException.Message); Assert.IsNull(_actualException.ParamName); } } diff --git a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_OpenAsync_FileModeCreate_FileAccessReadWrite_FileDoesNotExist.cs b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_OpenAsync_FileModeCreate_FileAccessReadWrite_FileDoesNotExist.cs index 9563b9fcd..100f08ac4 100644 --- a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_OpenAsync_FileModeCreate_FileAccessReadWrite_FileDoesNotExist.cs +++ b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_OpenAsync_FileModeCreate_FileAccessReadWrite_FileDoesNotExist.cs @@ -2,8 +2,11 @@ using System.IO; using System.Threading; using System.Threading.Tasks; + using Microsoft.VisualStudio.TestTools.UnitTesting; + using Moq; + using Renci.SshNet.Common; using Renci.SshNet.Sftp; @@ -40,15 +43,15 @@ protected override void SetupData() protected override void SetupMocks() { - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.RequestOpenAsync(_path, Flags.Read | Flags.Write | Flags.CreateNewOrOpen | Flags.Truncate, _cancellationToken)) - .ReturnsAsync(_handle); - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.CalculateOptimalReadLength((uint) _bufferSize)) - .Returns(_readBufferSize); - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.CalculateOptimalWriteLength((uint) _bufferSize, _handle)) - .Returns(_writeBufferSize); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.RequestOpenAsync(_path, Flags.Read | Flags.Write | Flags.CreateNewOrOpen | Flags.Truncate, _cancellationToken)) + .ReturnsAsync(_handle); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.CalculateOptimalReadLength((uint) _bufferSize)) + .Returns(_readBufferSize); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.CalculateOptimalWriteLength((uint) _bufferSize, _handle)) + .Returns(_writeBufferSize); } protected override async Task ActAsync() @@ -83,7 +86,9 @@ public void CanTimeoutShouldReturnTrue() [TestMethod] public void PositionShouldReturnZero() { - SftpSessionMock.InSequence(MockSequence).Setup(p => p.IsOpen).Returns(true); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.IsOpen) + .Returns(true); var actual = _target.Position; @@ -99,8 +104,12 @@ public async Task ReadShouldStartReadingAtBeginningOfFile() var data = new byte[] { 5, 4, 3, 2, 1 }; var expected = new byte[] { 0, 5, 4, 3, 2, 1, 0, 0 }; - SftpSessionMock.InSequence(MockSequence).Setup(p => p.IsOpen).Returns(true); - SftpSessionMock.InSequence(MockSequence).Setup(p => p.RequestReadAsync(_handle, 0UL, _readBufferSize, _cancellationToken)).ReturnsAsync(data); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.IsOpen) + .Returns(true); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.RequestReadAsync(_handle, 0UL, _readBufferSize, _cancellationToken)) + .ReturnsAsync(data); var actual = await _target.ReadAsync(buffer, 1, data.Length); @@ -116,8 +125,12 @@ public async Task WriteShouldStartWritingAtBeginningOfFile() { var buffer = new byte[_writeBufferSize]; - SftpSessionMock.InSequence(MockSequence).Setup(p => p.IsOpen).Returns(true); - SftpSessionMock.InSequence(MockSequence).Setup(p => p.RequestWriteAsync(_handle, 0UL, buffer, 0, buffer.Length, _cancellationToken)).Returns(Task.CompletedTask); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.IsOpen) + .Returns(true); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.RequestWriteAsync(_handle, 0UL, buffer, 0, buffer.Length, _cancellationToken)) + .Returns(Task.CompletedTask); await _target.WriteAsync(buffer, 0, buffer.Length); diff --git a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_OpenAsync_FileModeCreate_FileAccessWrite_FileExists.cs b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_OpenAsync_FileModeCreate_FileAccessWrite_FileExists.cs index ed001ab2a..ceb387637 100644 --- a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_OpenAsync_FileModeCreate_FileAccessWrite_FileExists.cs +++ b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_OpenAsync_FileModeCreate_FileAccessWrite_FileExists.cs @@ -2,8 +2,11 @@ using System.IO; using System.Threading; using System.Threading.Tasks; + using Microsoft.VisualStudio.TestTools.UnitTesting; + using Moq; + using Renci.SshNet.Sftp; namespace Renci.SshNet.Tests.Classes.Sftp @@ -39,15 +42,15 @@ protected override void SetupData() protected override void SetupMocks() { - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.RequestOpenAsync(_path, Flags.Write | Flags.CreateNewOrOpen | Flags.Truncate, _cancellationToken)) - .ReturnsAsync(_handle); - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.CalculateOptimalReadLength((uint) _bufferSize)) - .Returns(_readBufferSize); - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.CalculateOptimalWriteLength((uint) _bufferSize, _handle)) - .Returns(_writeBufferSize); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.RequestOpenAsync(_path, Flags.Write | Flags.CreateNewOrOpen | Flags.Truncate, _cancellationToken)) + .ReturnsAsync(_handle); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.CalculateOptimalReadLength((uint) _bufferSize)) + .Returns(_readBufferSize); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.CalculateOptimalWriteLength((uint) _bufferSize, _handle)) + .Returns(_writeBufferSize); } protected override async Task ActAsync() @@ -82,7 +85,9 @@ public void CanTimeoutShouldReturnTrue() [TestMethod] public void PositionShouldReturnZero() { - SftpSessionMock.InSequence(MockSequence).Setup(p => p.IsOpen).Returns(true); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.IsOpen) + .Returns(true); var actual = _target.Position; @@ -96,11 +101,13 @@ public async Task ReadShouldThrowNotSupportedException() { var buffer = new byte[_readBufferSize]; - SftpSessionMock.InSequence(MockSequence).Setup(p => p.IsOpen).Returns(true); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.IsOpen) + .Returns(true); try { - await _target.ReadAsync(buffer, 0, buffer.Length); + _ = await _target.ReadAsync(buffer, 0, buffer.Length); Assert.Fail(); } catch (NotSupportedException ex) @@ -116,8 +123,12 @@ public async Task WriteShouldStartWritingAtBeginningOfFile() { var buffer = new byte[_writeBufferSize]; - SftpSessionMock.InSequence(MockSequence).Setup(p => p.IsOpen).Returns(true); - SftpSessionMock.InSequence(MockSequence).Setup(p => p.RequestWriteAsync(_handle, 0UL, buffer, 0, buffer.Length, _cancellationToken)).Returns(Task.CompletedTask); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.IsOpen) + .Returns(true); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.RequestWriteAsync(_handle, 0UL, buffer, 0, buffer.Length, _cancellationToken)) + .Returns(Task.CompletedTask); await _target.WriteAsync(buffer, 0, buffer.Length); @@ -131,4 +142,4 @@ public void RequestOpenOnSftpSessionShouldBeInvokedOnce() SftpSessionMock.Verify(p => p.RequestOpenAsync(_path, Flags.Write | Flags.CreateNewOrOpen | Flags.Truncate, _cancellationToken), Times.Once); } } -} \ No newline at end of file +} diff --git a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_OpenAsync_FileModeOpenOrCreate_FileAccessReadWrite.cs b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_OpenAsync_FileModeOpenOrCreate_FileAccessReadWrite.cs index c7cd5d4a4..5803444e4 100644 --- a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_OpenAsync_FileModeOpenOrCreate_FileAccessReadWrite.cs +++ b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_OpenAsync_FileModeOpenOrCreate_FileAccessReadWrite.cs @@ -2,8 +2,11 @@ using System.IO; using System.Threading; using System.Threading.Tasks; + using Microsoft.VisualStudio.TestTools.UnitTesting; + using Moq; + using Renci.SshNet.Common; using Renci.SshNet.Sftp; @@ -40,15 +43,15 @@ protected override void SetupData() protected override void SetupMocks() { - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.RequestOpenAsync(_path, Flags.Read | Flags.Write | Flags.CreateNewOrOpen, _cancellationToken)) - .ReturnsAsync(_handle); - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.CalculateOptimalReadLength((uint) _bufferSize)) - .Returns(_readBufferSize); - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.CalculateOptimalWriteLength((uint) _bufferSize, _handle)) - .Returns(_writeBufferSize); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.RequestOpenAsync(_path, Flags.Read | Flags.Write | Flags.CreateNewOrOpen, _cancellationToken)) + .ReturnsAsync(_handle); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.CalculateOptimalReadLength((uint) _bufferSize)) + .Returns(_readBufferSize); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.CalculateOptimalWriteLength((uint) _bufferSize, _handle)) + .Returns(_writeBufferSize); } protected override async Task ActAsync() @@ -83,7 +86,9 @@ public void CanTimeoutShouldReturnTrue() [TestMethod] public void PositionShouldReturnZero() { - SftpSessionMock.InSequence(MockSequence).Setup(p => p.IsOpen).Returns(true); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.IsOpen) + .Returns(true); var actual = _target.Position; @@ -99,8 +104,12 @@ public async Task ReadShouldStartReadingAtBeginningOfFile() var data = new byte[] { 5, 4, 3, 2, 1 }; var expected = new byte[] { 0, 5, 4, 3, 2, 1, 0, 0 }; - SftpSessionMock.InSequence(MockSequence).Setup(p => p.IsOpen).Returns(true); - SftpSessionMock.InSequence(MockSequence).Setup(p => p.RequestReadAsync(_handle, 0UL, _readBufferSize, _cancellationToken)).ReturnsAsync(data); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.IsOpen) + .Returns(true); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.RequestReadAsync(_handle, 0UL, _readBufferSize, _cancellationToken)) + .ReturnsAsync(data); var actual = await _target.ReadAsync(buffer, 1, data.Length); @@ -116,8 +125,12 @@ public async Task WriteShouldStartWritingAtBeginningOfFile() { var buffer = new byte[_writeBufferSize]; - SftpSessionMock.InSequence(MockSequence).Setup(p => p.IsOpen).Returns(true); - SftpSessionMock.InSequence(MockSequence).Setup(p => p.RequestWriteAsync(_handle, 0UL, buffer, 0, buffer.Length, _cancellationToken)).Returns(Task.CompletedTask); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.IsOpen) + .Returns(true); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.RequestWriteAsync(_handle, 0UL, buffer, 0, buffer.Length, _cancellationToken)) + .Returns(Task.CompletedTask); await _target.WriteAsync(buffer, 0, buffer.Length); diff --git a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_OpenAsync_FileModeOpen_FileAccessReadWrite.cs b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_OpenAsync_FileModeOpen_FileAccessReadWrite.cs index 56589f668..7a653cb29 100644 --- a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_OpenAsync_FileModeOpen_FileAccessReadWrite.cs +++ b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_OpenAsync_FileModeOpen_FileAccessReadWrite.cs @@ -2,8 +2,11 @@ using System.IO; using System.Threading; using System.Threading.Tasks; + using Microsoft.VisualStudio.TestTools.UnitTesting; + using Moq; + using Renci.SshNet.Common; using Renci.SshNet.Sftp; @@ -40,15 +43,15 @@ protected override void SetupData() protected override void SetupMocks() { - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.RequestOpenAsync(_path, Flags.Read | Flags.Write, _cancellationToken)) - .ReturnsAsync(_handle); - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.CalculateOptimalReadLength((uint) _bufferSize)) - .Returns(_readBufferSize); - SftpSessionMock.InSequence(MockSequence) - .Setup(p => p.CalculateOptimalWriteLength((uint) _bufferSize, _handle)) - .Returns(_writeBufferSize); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.RequestOpenAsync(_path, Flags.Read | Flags.Write, _cancellationToken)) + .ReturnsAsync(_handle); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.CalculateOptimalReadLength((uint) _bufferSize)) + .Returns(_readBufferSize); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.CalculateOptimalWriteLength((uint) _bufferSize, _handle)) + .Returns(_writeBufferSize); } protected override async Task ActAsync() @@ -83,7 +86,9 @@ public void CanTimeoutShouldReturnTrue() [TestMethod] public void PositionShouldReturnZero() { - SftpSessionMock.InSequence(MockSequence).Setup(p => p.IsOpen).Returns(true); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.IsOpen) + .Returns(true); var actual = _target.Position; @@ -99,8 +104,12 @@ public async Task ReadShouldStartReadingAtBeginningOfFile() var data = new byte[] { 5, 4, 3, 2, 1 }; var expected = new byte[] { 0, 5, 4, 3, 2, 1, 0, 0 }; - SftpSessionMock.InSequence(MockSequence).Setup(p => p.IsOpen).Returns(true); - SftpSessionMock.InSequence(MockSequence).Setup(p => p.RequestReadAsync(_handle, 0UL, _readBufferSize, _cancellationToken)).ReturnsAsync(data); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.IsOpen) + .Returns(true); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.RequestReadAsync(_handle, 0UL, _readBufferSize, _cancellationToken)) + .ReturnsAsync(data); var actual = await _target.ReadAsync(buffer, 1, data.Length); @@ -116,8 +125,12 @@ public async Task WriteShouldStartWritingAtBeginningOfFile() { var buffer = new byte[_writeBufferSize]; - SftpSessionMock.InSequence(MockSequence).Setup(p => p.IsOpen).Returns(true); - SftpSessionMock.InSequence(MockSequence).Setup(p => p.RequestWriteAsync(_handle, 0UL, buffer, 0, buffer.Length, _cancellationToken)).Returns(Task.CompletedTask); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.IsOpen) + .Returns(true); + _ = SftpSessionMock.InSequence(MockSequence) + .Setup(p => p.RequestWriteAsync(_handle, 0UL, buffer, 0, buffer.Length, _cancellationToken)) + .Returns(Task.CompletedTask); await _target.WriteAsync(buffer, 0, buffer.Length); diff --git a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_OpenAsync_FileModeTruncate_FileAccessRead.cs b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_OpenAsync_FileModeTruncate_FileAccessRead.cs index 9247274e8..660bd1a1f 100644 --- a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_OpenAsync_FileModeTruncate_FileAccessRead.cs +++ b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_OpenAsync_FileModeTruncate_FileAccessRead.cs @@ -1,8 +1,9 @@ using System; using System.IO; -using System.Threading; using System.Threading.Tasks; + using Microsoft.VisualStudio.TestTools.UnitTesting; + using Renci.SshNet.Sftp; namespace Renci.SshNet.Tests.Classes.Sftp @@ -36,7 +37,7 @@ protected override async Task ActAsync() { try { - await SftpFileStream.OpenAsync(SftpSessionMock.Object, _path, _fileMode, _fileAccess, _bufferSize, default); + _ = await SftpFileStream.OpenAsync(SftpSessionMock.Object, _path, _fileMode, _fileAccess, _bufferSize, default); Assert.Fail(); } catch (ArgumentException ex) @@ -50,7 +51,7 @@ public void CtorShouldHaveThrownArgumentException() { Assert.IsNotNull(_actualException); Assert.IsNull(_actualException.InnerException); - Assert.AreEqual(string.Format("Combining {0}: {1} with {2}: {3} is invalid.", typeof(FileMode).Name, _fileMode, typeof(FileAccess).Name, _fileAccess), _actualException.Message); + Assert.AreEqual(string.Format("Combining {0}: {1} with {2}: {3} is invalid.", nameof(FileMode), _fileMode, nameof(FileAccess), _fileAccess), _actualException.Message); Assert.IsNull(_actualException.ParamName); } } diff --git a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_WriteAsync_SessionOpen_CountGreatherThanTwoTimesTheWriteBufferSize.cs b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_WriteAsync_SessionOpen_CountGreatherThanTwoTimesTheWriteBufferSize.cs index a9f4587b0..8fb74b436 100644 --- a/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_WriteAsync_SessionOpen_CountGreatherThanTwoTimesTheWriteBufferSize.cs +++ b/src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_WriteAsync_SessionOpen_CountGreatherThanTwoTimesTheWriteBufferSize.cs @@ -3,11 +3,13 @@ using System.IO; using System.Threading; using System.Threading.Tasks; + using Microsoft.VisualStudio.TestTools.UnitTesting; + using Moq; + using Renci.SshNet.Common; using Renci.SshNet.Sftp; -using Renci.SshNet.Sftp.Responses; namespace Renci.SshNet.Tests.Classes.Sftp { diff --git a/src/Renci.SshNet.Tests/Classes/Sftp/SftpHandleResponseBuilder.cs b/src/Renci.SshNet.Tests/Classes/Sftp/SftpHandleResponseBuilder.cs index 4477e2fb0..d9f67f61d 100644 --- a/src/Renci.SshNet.Tests/Classes/Sftp/SftpHandleResponseBuilder.cs +++ b/src/Renci.SshNet.Tests/Classes/Sftp/SftpHandleResponseBuilder.cs @@ -1,7 +1,4 @@ -using Renci.SshNet.Sftp; -using Renci.SshNet.Sftp.Responses; -using System.Collections.Generic; -using System.Text; +using Renci.SshNet.Sftp.Responses; namespace Renci.SshNet.Tests.Classes.Sftp { @@ -32,10 +29,10 @@ public SftpHandleResponseBuilder WithHandle(byte[] handle) public SftpHandleResponse Build() { var sftpHandleResponse = new SftpHandleResponse(_protocolVersion) - { - ResponseId = _responseId, - Handle = _handle - }; + { + ResponseId = _responseId, + Handle = _handle + }; return sftpHandleResponse; } } diff --git a/src/Renci.SshNet.Tests/Classes/Sftp/SftpNameResponseBuilder.cs b/src/Renci.SshNet.Tests/Classes/Sftp/SftpNameResponseBuilder.cs index e0dc9ae5d..268f1c5c5 100644 --- a/src/Renci.SshNet.Tests/Classes/Sftp/SftpNameResponseBuilder.cs +++ b/src/Renci.SshNet.Tests/Classes/Sftp/SftpNameResponseBuilder.cs @@ -10,7 +10,7 @@ internal class SftpNameResponseBuilder private uint _responseId; private uint _protocolVersion; private Encoding _encoding; - private List> _files; + private readonly List> _files; public SftpNameResponseBuilder() { @@ -32,7 +32,10 @@ public SftpNameResponseBuilder WithResponseId(uint responseId) public SftpNameResponseBuilder WithFiles(params KeyValuePair[] files) { for (var i = 0; i < files.Length; i++) + { _files.Add(files[i]); + } + return this; } diff --git a/src/Renci.SshNet.Tests/Classes/Sftp/SftpOpenRequestBuilder.cs b/src/Renci.SshNet.Tests/Classes/Sftp/SftpOpenRequestBuilder.cs index 00c0efa36..49f785d0d 100644 --- a/src/Renci.SshNet.Tests/Classes/Sftp/SftpOpenRequestBuilder.cs +++ b/src/Renci.SshNet.Tests/Classes/Sftp/SftpOpenRequestBuilder.cs @@ -1,10 +1,9 @@ -using Renci.SshNet.Sftp; +using System; +using System.Text; + +using Renci.SshNet.Sftp; using Renci.SshNet.Sftp.Requests; using Renci.SshNet.Sftp.Responses; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; namespace Renci.SshNet.Tests.Classes.Sftp { diff --git a/src/Renci.SshNet.Tests/Classes/Sftp/SftpStatVfsRequestBuilder.cs b/src/Renci.SshNet.Tests/Classes/Sftp/SftpStatVfsRequestBuilder.cs index 71e37bd12..d52b208a4 100644 --- a/src/Renci.SshNet.Tests/Classes/Sftp/SftpStatVfsRequestBuilder.cs +++ b/src/Renci.SshNet.Tests/Classes/Sftp/SftpStatVfsRequestBuilder.cs @@ -1,5 +1,6 @@ using Renci.SshNet.Sftp.Requests; using Renci.SshNet.Sftp.Responses; + using System; using System.Text; diff --git a/src/Renci.SshNet.Tests/Classes/Sftp/SftpStatVfsResponseBuilder.cs b/src/Renci.SshNet.Tests/Classes/Sftp/SftpStatVfsResponseBuilder.cs index 6dc110f74..b3735b91d 100644 --- a/src/Renci.SshNet.Tests/Classes/Sftp/SftpStatVfsResponseBuilder.cs +++ b/src/Renci.SshNet.Tests/Classes/Sftp/SftpStatVfsResponseBuilder.cs @@ -88,9 +88,13 @@ public SftpStatVfsResponseBuilder WithSid(ulong sid) public SftpStatVfsResponseBuilder WithIsReadOnly(bool isReadOnly) { if (isReadOnly) + { _flag &= SftpFileSytemInformation.SSH_FXE_STATVFS_ST_RDONLY; + } else + { _flag |= SftpFileSytemInformation.SSH_FXE_STATVFS_ST_RDONLY; + } return this; } @@ -98,9 +102,13 @@ public SftpStatVfsResponseBuilder WithIsReadOnly(bool isReadOnly) public SftpStatVfsResponseBuilder WithSupportsSetUid(bool supportsSetUid) { if (supportsSetUid) + { _flag |= SftpFileSytemInformation.SSH_FXE_STATVFS_ST_NOSUID; + } else + { _flag &= SftpFileSytemInformation.SSH_FXE_STATVFS_ST_NOSUID; + } return this; } diff --git a/src/Renci.SshNet.Tests/Classes/Sftp/SftpVersionResponseBuilder.cs b/src/Renci.SshNet.Tests/Classes/Sftp/SftpVersionResponseBuilder.cs index 85f33cc1d..1e4d55efd 100644 --- a/src/Renci.SshNet.Tests/Classes/Sftp/SftpVersionResponseBuilder.cs +++ b/src/Renci.SshNet.Tests/Classes/Sftp/SftpVersionResponseBuilder.cs @@ -6,7 +6,7 @@ namespace Renci.SshNet.Tests.Classes.Sftp internal class SftpVersionResponseBuilder { private uint _version; - private IDictionary _extensions; + private readonly IDictionary _extensions; public SftpVersionResponseBuilder() { diff --git a/src/Renci.SshNet.Tests/Classes/SftpClientTest.CreateDirectory.cs b/src/Renci.SshNet.Tests/Classes/SftpClientTest.CreateDirectory.cs index 2c6284a6a..73e5f3c83 100644 --- a/src/Renci.SshNet.Tests/Classes/SftpClientTest.CreateDirectory.cs +++ b/src/Renci.SshNet.Tests/Classes/SftpClientTest.CreateDirectory.cs @@ -43,7 +43,9 @@ public void Test_Sftp_CreateDirectory_In_Current_Location() public void Test_Sftp_CreateDirectory_In_Forbidden_Directory() { if (Resources.USERNAME == "root") + { Assert.Fail("Must not run this test as root!"); + } using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD)) { @@ -101,4 +103,4 @@ public void Test_Sftp_CreateDirectory_Null() } } } -} \ No newline at end of file +} diff --git a/src/Renci.SshNet.Tests/Classes/SftpClientTest.DeleteDirectory.cs b/src/Renci.SshNet.Tests/Classes/SftpClientTest.DeleteDirectory.cs index 5e981afc0..0964d4690 100644 --- a/src/Renci.SshNet.Tests/Classes/SftpClientTest.DeleteDirectory.cs +++ b/src/Renci.SshNet.Tests/Classes/SftpClientTest.DeleteDirectory.cs @@ -44,7 +44,9 @@ public void Test_Sftp_DeleteDirectory_Which_Doesnt_Exists() public void Test_Sftp_DeleteDirectory_Which_No_Permissions() { if (Resources.USERNAME == "root") + { Assert.Fail("Must not run this test as root!"); + } using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD)) { @@ -89,4 +91,4 @@ public void Test_Sftp_DeleteDirectory_Null() } } } -} \ No newline at end of file +} diff --git a/src/Renci.SshNet.Tests/Classes/SftpClientTest.Download.cs b/src/Renci.SshNet.Tests/Classes/SftpClientTest.Download.cs index 85a2d7ecd..41dbdf33f 100644 --- a/src/Renci.SshNet.Tests/Classes/SftpClientTest.Download.cs +++ b/src/Renci.SshNet.Tests/Classes/SftpClientTest.Download.cs @@ -18,7 +18,9 @@ public partial class SftpClientTest public void Test_Sftp_Download_Forbidden() { if (Resources.USERNAME == "root") + { Assert.Fail("Must not run this test as root!"); + } using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD)) { @@ -118,4 +120,4 @@ public void Test_Sftp_EndDownloadFile_Invalid_Async_Handle() } } } -} \ No newline at end of file +} diff --git a/src/Renci.SshNet.Tests/Classes/SftpClientTest.Upload.cs b/src/Renci.SshNet.Tests/Classes/SftpClientTest.Upload.cs index aa70e232d..2018c9f0d 100644 --- a/src/Renci.SshNet.Tests/Classes/SftpClientTest.Upload.cs +++ b/src/Renci.SshNet.Tests/Classes/SftpClientTest.Upload.cs @@ -1,12 +1,14 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Renci.SshNet.Common; -using Renci.SshNet.Sftp; -using Renci.SshNet.Tests.Properties; -using System; +using System; using System.Collections.Generic; using System.IO; using System.Threading; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +using Renci.SshNet.Common; +using Renci.SshNet.Sftp; +using Renci.SshNet.Tests.Properties; + namespace Renci.SshNet.Tests.Classes { /// @@ -25,10 +27,10 @@ public void Test_Sftp_Upload_And_Download_1MB_File() { sftp.Connect(); - string uploadedFileName = Path.GetTempFileName(); - string remoteFileName = Path.GetRandomFileName(); + var uploadedFileName = Path.GetTempFileName(); + var remoteFileName = Path.GetRandomFileName(); - this.CreateTestFile(uploadedFileName, 1); + CreateTestFile(uploadedFileName, 1); // Calculate has value var uploadedHash = CalculateMD5(uploadedFileName); @@ -38,7 +40,7 @@ public void Test_Sftp_Upload_And_Download_1MB_File() sftp.UploadFile(file, remoteFileName); } - string downloadedFileName = Path.GetTempFileName(); + var downloadedFileName = Path.GetTempFileName(); using (var file = File.OpenWrite(downloadedFileName)) { @@ -68,10 +70,10 @@ public void Test_Sftp_Upload_Forbidden() { sftp.Connect(); - string uploadedFileName = Path.GetTempFileName(); - string remoteFileName = "/root/1"; + var uploadedFileName = Path.GetTempFileName(); + var remoteFileName = "/root/1"; - this.CreateTestFile(uploadedFileName, 1); + CreateTestFile(uploadedFileName, 1); using (var file = File.OpenRead(uploadedFileName)) { @@ -98,14 +100,16 @@ public void Test_Sftp_Multiple_Async_Upload_And_Download_10Files_5MB_Each() var testInfoList = new Dictionary(); - for (int i = 0; i < maxFiles; i++) + for (var i = 0; i < maxFiles; i++) { - var testInfo = new TestInfo(); - testInfo.UploadedFileName = Path.GetTempFileName(); - testInfo.DownloadedFileName = Path.GetTempFileName(); - testInfo.RemoteFileName = Path.GetRandomFileName(); + var testInfo = new TestInfo + { + UploadedFileName = Path.GetTempFileName(), + DownloadedFileName = Path.GetTempFileName(), + RemoteFileName = Path.GetRandomFileName() + }; - this.CreateTestFile(testInfo.UploadedFileName, maxSize); + CreateTestFile(testInfo.UploadedFileName, maxSize); // Calculate hash value testInfo.UploadedHash = CalculateMD5(testInfo.UploadedFileName); @@ -130,7 +134,7 @@ public void Test_Sftp_Multiple_Async_Upload_And_Download_10Files_5MB_Each() } // Wait for upload to finish - bool uploadCompleted = false; + var uploadCompleted = false; while (!uploadCompleted) { // Assume upload completed @@ -174,7 +178,7 @@ public void Test_Sftp_Multiple_Async_Upload_And_Download_10Files_5MB_Each() } // Wait for download to finish - bool downloadCompleted = false; + var downloadCompleted = false; while (!downloadCompleted) { // Assume download completed @@ -248,11 +252,11 @@ public void Test_Sftp_Ensure_Async_Delegates_Called_For_BeginFileUpload_BeginFil { sftp.Connect(); - string remoteFileName = Path.GetRandomFileName(); - string localFileName = Path.GetRandomFileName(); - bool uploadDelegateCalled = false; - bool downloadDelegateCalled = false; - bool listDirectoryDelegateCalled = false; + var remoteFileName = Path.GetRandomFileName(); + var localFileName = Path.GetRandomFileName(); + var uploadDelegateCalled = false; + var downloadDelegateCalled = false; + var listDirectoryDelegateCalled = false; IAsyncResult asyncResult; // Test for BeginUploadFile. @@ -261,11 +265,14 @@ public void Test_Sftp_Ensure_Async_Delegates_Called_For_BeginFileUpload_BeginFil using (var fileStream = File.OpenRead(localFileName)) { - asyncResult = sftp.BeginUploadFile(fileStream, remoteFileName, delegate(IAsyncResult ar) - { - sftp.EndUploadFile(ar); - uploadDelegateCalled = true; - }, null); + asyncResult = sftp.BeginUploadFile(fileStream, + remoteFileName, + delegate(IAsyncResult ar) + { + sftp.EndUploadFile(ar); + uploadDelegateCalled = true; + }, + null); while (!asyncResult.IsCompleted) { @@ -282,11 +289,14 @@ public void Test_Sftp_Ensure_Async_Delegates_Called_For_BeginFileUpload_BeginFil asyncResult = null; using (var fileStream = File.OpenWrite(localFileName)) { - asyncResult = sftp.BeginDownloadFile(remoteFileName, fileStream, delegate(IAsyncResult ar) - { - sftp.EndDownloadFile(ar); - downloadDelegateCalled = true; - }, null); + asyncResult = sftp.BeginDownloadFile(remoteFileName, + fileStream, + delegate(IAsyncResult ar) + { + sftp.EndDownloadFile(ar); + downloadDelegateCalled = true; + }, + null); while (!asyncResult.IsCompleted) { @@ -301,11 +311,13 @@ public void Test_Sftp_Ensure_Async_Delegates_Called_For_BeginFileUpload_BeginFil // Test for BeginListDirectory. asyncResult = null; - asyncResult = sftp.BeginListDirectory(sftp.WorkingDirectory, delegate(IAsyncResult ar) - { - sftp.EndListDirectory(ar); - listDirectoryDelegateCalled = true; - }, null); + asyncResult = sftp.BeginListDirectory(sftp.WorkingDirectory, + delegate(IAsyncResult ar) + { + _ = sftp.EndListDirectory(ar); + listDirectoryDelegateCalled = true; + }, + null); while (!asyncResult.IsCompleted) { @@ -326,7 +338,7 @@ public void Test_Sftp_BeginUploadFile_StreamIsNull() using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD)) { sftp.Connect(); - sftp.BeginUploadFile(null, "aaaaa", null, null); + _ = sftp.BeginUploadFile(null, "aaaaa", null, null); sftp.Disconnect(); } } @@ -341,7 +353,7 @@ public void Test_Sftp_BeginUploadFile_FileNameIsWhiteSpace() using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD)) { sftp.Connect(); - sftp.BeginUploadFile(new MemoryStream(), " ", null, null); + _ = sftp.BeginUploadFile(new MemoryStream(), " ", null, null); sftp.Disconnect(); } } @@ -356,7 +368,7 @@ public void Test_Sftp_BeginUploadFile_FileNameIsNull() using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD)) { sftp.Connect(); - sftp.BeginUploadFile(new MemoryStream(), null, null, null); + _ = sftp.BeginUploadFile(new MemoryStream(), null, null, null); sftp.Disconnect(); } } @@ -372,10 +384,10 @@ public void Test_Sftp_EndUploadFile_Invalid_Async_Handle() sftp.Connect(); var async1 = sftp.BeginListDirectory("/", null, null); var filename = Path.GetTempFileName(); - this.CreateTestFile(filename, 100); + CreateTestFile(filename, 100); var async2 = sftp.BeginUploadFile(File.OpenRead(filename), "test", null, null); sftp.EndUploadFile(async1); } } } -} \ No newline at end of file +} diff --git a/src/Renci.SshNet.Tests/Classes/SftpClientTest.cs b/src/Renci.SshNet.Tests/Classes/SftpClientTest.cs index a66e49312..200abae89 100644 --- a/src/Renci.SshNet.Tests/Classes/SftpClientTest.cs +++ b/src/Renci.SshNet.Tests/Classes/SftpClientTest.cs @@ -1360,14 +1360,23 @@ protected static string CalculateMD5(string fileName) { using (FileStream file = new FileStream(fileName, FileMode.Open)) { +#if NET7_0_OR_GREATER + var hash = MD5.HashData(file); +#else +#if NET6_0 + var md5 = MD5.Create(); +#else MD5 md5 = new MD5CryptoServiceProvider(); - byte[] retVal = md5.ComputeHash(file); +#endif // NET6_0 + var hash = md5.ComputeHash(file); +#endif // NET7_0_OR_GREATER + file.Close(); StringBuilder sb = new StringBuilder(); - for (int i = 0; i < retVal.Length; i++) + for (var i = 0; i < hash.Length; i++) { - sb.Append(retVal[i].ToString("x2")); + sb.Append(hash[i].ToString("x2")); } return sb.ToString(); } diff --git a/src/Renci.SshNet.Tests/Classes/SftpClientTestBase.cs b/src/Renci.SshNet.Tests/Classes/SftpClientTestBase.cs index 11657962c..e0ca2c91c 100644 --- a/src/Renci.SshNet.Tests/Classes/SftpClientTestBase.cs +++ b/src/Renci.SshNet.Tests/Classes/SftpClientTestBase.cs @@ -5,15 +5,15 @@ namespace Renci.SshNet.Tests.Classes { public abstract class SftpClientTestBase : BaseClientTestBase { - internal Mock _sftpResponseFactoryMock { get; private set; } - internal Mock _sftpSessionMock { get; private set; } + internal Mock SftpResponseFactoryMock { get; private set; } + internal Mock SftpSessionMock { get; private set; } protected override void CreateMocks() { base.CreateMocks(); - _sftpResponseFactoryMock = new Mock(MockBehavior.Strict); - _sftpSessionMock = new Mock(MockBehavior.Strict); + SftpResponseFactoryMock = new Mock(MockBehavior.Strict); + SftpSessionMock = new Mock(MockBehavior.Strict); } } } diff --git a/src/Renci.SshNet.Tests/Classes/SftpClientTest_Connect_SftpSessionConnectFailure.cs b/src/Renci.SshNet.Tests/Classes/SftpClientTest_Connect_SftpSessionConnectFailure.cs index b3bcb8e81..6f9650487 100644 --- a/src/Renci.SshNet.Tests/Classes/SftpClientTest_Connect_SftpSessionConnectFailure.cs +++ b/src/Renci.SshNet.Tests/Classes/SftpClientTest_Connect_SftpSessionConnectFailure.cs @@ -1,12 +1,13 @@ using System; using System.Reflection; using System.Threading; + using Microsoft.VisualStudio.TestTools.UnitTesting; + using Moq; + using Renci.SshNet.Common; -using Renci.SshNet.Connection; using Renci.SshNet.Security; -using Renci.SshNet.Sftp; namespace Renci.SshNet.Tests.Classes { @@ -28,34 +29,34 @@ protected override void SetupMocks() { var sequence = new MockSequence(); - _serviceFactoryMock.InSequence(sequence) - .Setup(p => p.CreateSocketFactory()) - .Returns(_socketFactoryMock.Object); - _serviceFactoryMock.InSequence(sequence) - .Setup(p => p.CreateSession(_connectionInfo, _socketFactoryMock.Object)) - .Returns(_sessionMock.Object); - _sessionMock.InSequence(sequence) - .Setup(p => p.Connect()); - _serviceFactoryMock.InSequence(sequence) - .Setup(p => p.CreateSftpResponseFactory()) - .Returns(_sftpResponseFactoryMock.Object); - _serviceFactoryMock.InSequence(sequence) - .Setup(p => p.CreateSftpSession(_sessionMock.Object, -1, _connectionInfo.Encoding, _sftpResponseFactoryMock.Object)) - .Returns(_sftpSessionMock.Object); - _sftpSessionMock.InSequence(sequence) - .Setup(p => p.Connect()) - .Throws(_sftpSessionConnectionException); - _sftpSessionMock.InSequence(sequence) + _ = ServiceFactoryMock.InSequence(sequence) + .Setup(p => p.CreateSocketFactory()) + .Returns(SocketFactoryMock.Object); + _ = ServiceFactoryMock.InSequence(sequence) + .Setup(p => p.CreateSession(_connectionInfo, SocketFactoryMock.Object)) + .Returns(SessionMock.Object); + _ = SessionMock.InSequence(sequence) + .Setup(p => p.Connect()); + _ = ServiceFactoryMock.InSequence(sequence) + .Setup(p => p.CreateSftpResponseFactory()) + .Returns(SftpResponseFactoryMock.Object); + _ = ServiceFactoryMock.InSequence(sequence) + .Setup(p => p.CreateSftpSession(SessionMock.Object, -1, _connectionInfo.Encoding, SftpResponseFactoryMock.Object)) + .Returns(SftpSessionMock.Object); + _ = SftpSessionMock.InSequence(sequence) + .Setup(p => p.Connect()) + .Throws(_sftpSessionConnectionException); + _ = SftpSessionMock.InSequence(sequence) + .Setup(p => p.Dispose()); + _ = SessionMock.InSequence(sequence) .Setup(p => p.Dispose()); - _sessionMock.InSequence(sequence) - .Setup(p => p.Dispose()); } protected override void Arrange() { base.Arrange(); - _sftpClient = new SftpClient(_connectionInfo, false, _serviceFactoryMock.Object); + _sftpClient = new SftpClient(_connectionInfo, false, ServiceFactoryMock.Object); } protected override void Act() @@ -97,7 +98,7 @@ public void ErrorOccuredOnSessionShouldNoLongerBeSignaledViaErrorOccurredOnSftpC _sftpClient.ErrorOccurred += (sender, args) => Interlocked.Increment(ref errorOccurredSignalCount); - _sessionMock.Raise(p => p.ErrorOccured += null, new ExceptionEventArgs(new Exception())); + SessionMock.Raise(p => p.ErrorOccured += null, new ExceptionEventArgs(new Exception())); Assert.AreEqual(0, errorOccurredSignalCount); } @@ -109,7 +110,7 @@ public void HostKeyReceivedOnSessionShouldNoLongerBeSignaledViaHostKeyReceivedOn _sftpClient.HostKeyReceived += (sender, args) => Interlocked.Increment(ref hostKeyReceivedSignalCount); - _sessionMock.Raise(p => p.HostKeyReceived += null, new HostKeyEventArgs(GetKeyHostAlgorithm())); + SessionMock.Raise(p => p.HostKeyReceived += null, new HostKeyEventArgs(GetKeyHostAlgorithm())); Assert.AreEqual(0, hostKeyReceivedSignalCount); } diff --git a/src/Renci.SshNet.Tests/Classes/SftpClientTest_Dispose_Connected.cs b/src/Renci.SshNet.Tests/Classes/SftpClientTest_Dispose_Connected.cs index 239c84931..fe8ef9f63 100644 --- a/src/Renci.SshNet.Tests/Classes/SftpClientTest_Dispose_Connected.cs +++ b/src/Renci.SshNet.Tests/Classes/SftpClientTest_Dispose_Connected.cs @@ -1,7 +1,8 @@ using System; + using Microsoft.VisualStudio.TestTools.UnitTesting; + using Moq; -using Renci.SshNet.Sftp; namespace Renci.SshNet.Tests.Classes { @@ -16,31 +17,38 @@ protected override void SetupData() { _connectionInfo = new ConnectionInfo("host", "user", new NoneAuthenticationMethod("userauth")); _operationTimeout = new Random().Next(1000, 10000); - _sftpClient = new SftpClient(_connectionInfo, false, _serviceFactoryMock.Object); - _sftpClient.OperationTimeout = TimeSpan.FromMilliseconds(_operationTimeout); + _sftpClient = new SftpClient(_connectionInfo, false, ServiceFactoryMock.Object) + { + OperationTimeout = TimeSpan.FromMilliseconds(_operationTimeout) + }; } protected override void SetupMocks() { var sequence = new MockSequence(); - _serviceFactoryMock.InSequence(sequence) - .Setup(p => p.CreateSocketFactory()) - .Returns(_socketFactoryMock.Object); - _serviceFactoryMock.InSequence(sequence) - .Setup(p => p.CreateSession(_connectionInfo, _socketFactoryMock.Object)) - .Returns(_sessionMock.Object); - _sessionMock.InSequence(sequence).Setup(p => p.Connect()); - _serviceFactoryMock.InSequence(sequence) - .Setup(p => p.CreateSftpResponseFactory()) - .Returns(_sftpResponseFactoryMock.Object); - _serviceFactoryMock.InSequence(sequence) - .Setup(p => p.CreateSftpSession(_sessionMock.Object, _operationTimeout, _connectionInfo.Encoding, _sftpResponseFactoryMock.Object)) - .Returns(_sftpSessionMock.Object); - _sftpSessionMock.InSequence(sequence).Setup(p => p.Connect()); - _sessionMock.InSequence(sequence).Setup(p => p.OnDisconnecting()); - _sftpSessionMock.InSequence(sequence).Setup(p => p.Dispose()); - _sessionMock.InSequence(sequence).Setup(p => p.Dispose()); + _ = ServiceFactoryMock.InSequence(sequence) + .Setup(p => p.CreateSocketFactory()) + .Returns(SocketFactoryMock.Object); + _ = ServiceFactoryMock.InSequence(sequence) + .Setup(p => p.CreateSession(_connectionInfo, SocketFactoryMock.Object)) + .Returns(SessionMock.Object); + _ = SessionMock.InSequence(sequence) + .Setup(p => p.Connect()); + _ = ServiceFactoryMock.InSequence(sequence) + .Setup(p => p.CreateSftpResponseFactory()) + .Returns(SftpResponseFactoryMock.Object); + _ = ServiceFactoryMock.InSequence(sequence) + .Setup(p => p.CreateSftpSession(SessionMock.Object, _operationTimeout, _connectionInfo.Encoding, SftpResponseFactoryMock.Object)) + .Returns(SftpSessionMock.Object); + _ = SftpSessionMock.InSequence(sequence) + .Setup(p => p.Connect()); + _ = SessionMock.InSequence(sequence) + .Setup(p => p.OnDisconnecting()); + _ = SftpSessionMock.InSequence(sequence) + .Setup(p => p.Dispose()); + _ = SessionMock.InSequence(sequence) + .Setup(p => p.Dispose()); } protected override void Arrange() @@ -58,58 +66,58 @@ protected override void Act() [TestMethod] public void CreateSftpMessageFactoryOnServiceFactoryShouldBeInvokedOnce() { - _serviceFactoryMock.Verify(p => p.CreateSftpResponseFactory(), Times.Once); + ServiceFactoryMock.Verify(p => p.CreateSftpResponseFactory(), Times.Once); } [TestMethod] public void CreateSftpSessionOnServiceFactoryShouldBeInvokedOnce() { - _serviceFactoryMock.Verify( - p => p.CreateSftpSession(_sessionMock.Object, _operationTimeout, _connectionInfo.Encoding, _sftpResponseFactoryMock.Object), + ServiceFactoryMock.Verify( + p => p.CreateSftpSession(SessionMock.Object, _operationTimeout, _connectionInfo.Encoding, SftpResponseFactoryMock.Object), Times.Once); } [TestMethod] public void CreateSocketFactoryOnServiceFactoryShouldBeInvokedOnce() { - _serviceFactoryMock.Verify(p => p.CreateSocketFactory(), Times.Once); + ServiceFactoryMock.Verify(p => p.CreateSocketFactory(), Times.Once); } [TestMethod] public void CreateSessionOnServiceFactoryShouldBeInvokedOnce() { - _serviceFactoryMock.Verify(p => p.CreateSession(_connectionInfo, _socketFactoryMock.Object), + ServiceFactoryMock.Verify(p => p.CreateSession(_connectionInfo, SocketFactoryMock.Object), Times.Once); } [TestMethod] public void DisconnectOnNetConfSessionShouldNeverBeInvoked() { - _sftpSessionMock.Verify(p => p.Disconnect(), Times.Never); + SftpSessionMock.Verify(p => p.Disconnect(), Times.Never); } [TestMethod] public void DisconnectOnSessionShouldNeverBeInvoked() { - _sessionMock.Verify(p => p.Disconnect(), Times.Never); + SessionMock.Verify(p => p.Disconnect(), Times.Never); } [TestMethod] public void DisposeOnNetConfSessionShouldBeInvokedOnce() { - _sftpSessionMock.Verify(p => p.Dispose(), Times.Once); + SftpSessionMock.Verify(p => p.Dispose(), Times.Once); } [TestMethod] public void DisposeOnSessionShouldBeInvokedOnce() { - _sessionMock.Verify(p => p.Dispose(), Times.Once); + SessionMock.Verify(p => p.Dispose(), Times.Once); } [TestMethod] public void OnDisconnectingOnSessionShouldBeInvokedOnce() { - _sessionMock.Verify(p => p.OnDisconnecting(), Times.Once); + SessionMock.Verify(p => p.OnDisconnecting(), Times.Once); } } } diff --git a/src/Renci.SshNet.Tests/Classes/SftpClientTest_Dispose_Disconnected.cs b/src/Renci.SshNet.Tests/Classes/SftpClientTest_Dispose_Disconnected.cs index 192c5e957..0f8d0a469 100644 --- a/src/Renci.SshNet.Tests/Classes/SftpClientTest_Dispose_Disconnected.cs +++ b/src/Renci.SshNet.Tests/Classes/SftpClientTest_Dispose_Disconnected.cs @@ -1,7 +1,8 @@ using System; + using Microsoft.VisualStudio.TestTools.UnitTesting; + using Moq; -using Renci.SshNet.Sftp; namespace Renci.SshNet.Tests.Classes { @@ -17,31 +18,38 @@ protected override void SetupData() { _connectionInfo = new ConnectionInfo("host", "user", new NoneAuthenticationMethod("userauth")); _operationTimeout = new Random().Next(1000, 10000); - _sftpClient = new SftpClient(_connectionInfo, false, _serviceFactoryMock.Object); - _sftpClient.OperationTimeout = TimeSpan.FromMilliseconds(_operationTimeout); + _sftpClient = new SftpClient(_connectionInfo, false, ServiceFactoryMock.Object) + { + OperationTimeout = TimeSpan.FromMilliseconds(_operationTimeout) + }; } protected override void SetupMocks() { var sequence = new MockSequence(); - _serviceFactoryMock.InSequence(sequence) - .Setup(p => p.CreateSocketFactory()) - .Returns(_socketFactoryMock.Object); - _serviceFactoryMock.InSequence(sequence) - .Setup(p => p.CreateSession(_connectionInfo, _socketFactoryMock.Object)) - .Returns(_sessionMock.Object); - _sessionMock.InSequence(sequence).Setup(p => p.Connect()); - _serviceFactoryMock.InSequence(sequence) - .Setup(p => p.CreateSftpResponseFactory()) - .Returns(_sftpResponseFactoryMock.Object); - _serviceFactoryMock.InSequence(sequence) - .Setup(p => p.CreateSftpSession(_sessionMock.Object, _operationTimeout, _connectionInfo.Encoding, _sftpResponseFactoryMock.Object)) - .Returns(_sftpSessionMock.Object); - _sftpSessionMock.InSequence(sequence).Setup(p => p.Connect()); - _sessionMock.InSequence(sequence).Setup(p => p.OnDisconnecting()); - _sftpSessionMock.InSequence(sequence).Setup(p => p.Dispose()); - _sessionMock.InSequence(sequence).Setup(p => p.Dispose()); + _ = ServiceFactoryMock.InSequence(sequence) + .Setup(p => p.CreateSocketFactory()) + .Returns(SocketFactoryMock.Object); + _ = ServiceFactoryMock.InSequence(sequence) + .Setup(p => p.CreateSession(_connectionInfo, SocketFactoryMock.Object)) + .Returns(SessionMock.Object); + _ = SessionMock.InSequence(sequence) + .Setup(p => p.Connect()); + _ = ServiceFactoryMock.InSequence(sequence) + .Setup(p => p.CreateSftpResponseFactory()) + .Returns(SftpResponseFactoryMock.Object); + _ = ServiceFactoryMock.InSequence(sequence) + .Setup(p => p.CreateSftpSession(SessionMock.Object, _operationTimeout, _connectionInfo.Encoding, SftpResponseFactoryMock.Object)) + .Returns(SftpSessionMock.Object); + _ = SftpSessionMock.InSequence(sequence) + .Setup(p => p.Connect()); + _ = SessionMock.InSequence(sequence) + .Setup(p => p.OnDisconnecting()); + _ = SftpSessionMock.InSequence(sequence) + .Setup(p => p.Dispose()); + _ = SessionMock.InSequence(sequence) + .Setup(p => p.Dispose()); } protected override void Arrange() @@ -60,58 +68,58 @@ protected override void Act() [TestMethod] public void CreateSftpMessageFactoryOnServiceFactoryShouldBeInvokedOnce() { - _serviceFactoryMock.Verify(p => p.CreateSftpResponseFactory(), Times.Once); + ServiceFactoryMock.Verify(p => p.CreateSftpResponseFactory(), Times.Once); } [TestMethod] public void CreateSftpSessionOnServiceFactoryShouldBeInvokedOnce() { - _serviceFactoryMock.Verify( - p => p.CreateSftpSession(_sessionMock.Object, _operationTimeout, _connectionInfo.Encoding, _sftpResponseFactoryMock.Object), + ServiceFactoryMock.Verify( + p => p.CreateSftpSession(SessionMock.Object, _operationTimeout, _connectionInfo.Encoding, SftpResponseFactoryMock.Object), Times.Once); } [TestMethod] public void CreateSocketFactoryOnServiceFactoryShouldBeInvokedOnce() { - _serviceFactoryMock.Verify(p => p.CreateSocketFactory(), Times.Once); + ServiceFactoryMock.Verify(p => p.CreateSocketFactory(), Times.Once); } [TestMethod] public void CreateSessionOnServiceFactoryShouldBeInvokedOnce() { - _serviceFactoryMock.Verify(p => p.CreateSession(_connectionInfo, _socketFactoryMock.Object), + ServiceFactoryMock.Verify(p => p.CreateSession(_connectionInfo, SocketFactoryMock.Object), Times.Once); } [TestMethod] public void DisconnectOnNetConfSessionShouldNeverBeInvoked() { - _sftpSessionMock.Verify(p => p.Disconnect(), Times.Never); + SftpSessionMock.Verify(p => p.Disconnect(), Times.Never); } [TestMethod] public void DisconnectOnSessionShouldNeverBeInvoked() { - _sessionMock.Verify(p => p.Disconnect(), Times.Never); + SessionMock.Verify(p => p.Disconnect(), Times.Never); } [TestMethod] public void DisposeOnNetConfSessionShouldBeInvokedOnce() { - _sftpSessionMock.Verify(p => p.Dispose(), Times.Once); + SftpSessionMock.Verify(p => p.Dispose(), Times.Once); } [TestMethod] public void DisposeOnSessionShouldBeInvokedOnce() { - _sessionMock.Verify(p => p.Dispose(), Times.Once); + SessionMock.Verify(p => p.Dispose(), Times.Once); } [TestMethod] public void OnDisconnectingOnSessionShouldBeInvokedOnce() { - _sessionMock.Verify(p => p.OnDisconnecting(), Times.Once); + SessionMock.Verify(p => p.OnDisconnecting(), Times.Once); } } } diff --git a/src/Renci.SshNet.Tests/Classes/SftpClientTest_Dispose_Disposed.cs b/src/Renci.SshNet.Tests/Classes/SftpClientTest_Dispose_Disposed.cs index 11e00ad03..09208b8bc 100644 --- a/src/Renci.SshNet.Tests/Classes/SftpClientTest_Dispose_Disposed.cs +++ b/src/Renci.SshNet.Tests/Classes/SftpClientTest_Dispose_Disposed.cs @@ -1,7 +1,8 @@ using System; + using Microsoft.VisualStudio.TestTools.UnitTesting; + using Moq; -using Renci.SshNet.Sftp; namespace Renci.SshNet.Tests.Classes { @@ -16,31 +17,38 @@ protected override void SetupData() { _connectionInfo = new ConnectionInfo("host", "user", new NoneAuthenticationMethod("userauth")); _operationTimeout = new Random().Next(1000, 10000); - _sftpClient = new SftpClient(_connectionInfo, false, _serviceFactoryMock.Object); - _sftpClient.OperationTimeout = TimeSpan.FromMilliseconds(_operationTimeout); + _sftpClient = new SftpClient(_connectionInfo, false, ServiceFactoryMock.Object) + { + OperationTimeout = TimeSpan.FromMilliseconds(_operationTimeout) + }; } protected override void SetupMocks() { var sequence = new MockSequence(); - _serviceFactoryMock.InSequence(sequence) - .Setup(p => p.CreateSocketFactory()) - .Returns(_socketFactoryMock.Object); - _serviceFactoryMock.InSequence(sequence) - .Setup(p => p.CreateSession(_connectionInfo, _socketFactoryMock.Object)) - .Returns(_sessionMock.Object); - _sessionMock.InSequence(sequence).Setup(p => p.Connect()); - _serviceFactoryMock.InSequence(sequence) - .Setup(p => p.CreateSftpResponseFactory()) - .Returns(_sftpResponseFactoryMock.Object); - _serviceFactoryMock.InSequence(sequence) - .Setup(p => p.CreateSftpSession(_sessionMock.Object, _operationTimeout, _connectionInfo.Encoding, _sftpResponseFactoryMock.Object)) - .Returns(_sftpSessionMock.Object); - _sftpSessionMock.InSequence(sequence).Setup(p => p.Connect()); - _sessionMock.InSequence(sequence).Setup(p => p.OnDisconnecting()); - _sftpSessionMock.InSequence(sequence).Setup(p => p.Dispose()); - _sessionMock.InSequence(sequence).Setup(p => p.Dispose()); + _ = ServiceFactoryMock.InSequence(sequence) + .Setup(p => p.CreateSocketFactory()) + .Returns(SocketFactoryMock.Object); + _ = ServiceFactoryMock.InSequence(sequence) + .Setup(p => p.CreateSession(_connectionInfo, SocketFactoryMock.Object)) + .Returns(SessionMock.Object); + _ = SessionMock.InSequence(sequence) + .Setup(p => p.Connect()); + _ = ServiceFactoryMock.InSequence(sequence) + .Setup(p => p.CreateSftpResponseFactory()) + .Returns(SftpResponseFactoryMock.Object); + _ = ServiceFactoryMock.InSequence(sequence) + .Setup(p => p.CreateSftpSession(SessionMock.Object, _operationTimeout, _connectionInfo.Encoding, SftpResponseFactoryMock.Object)) + .Returns(SftpSessionMock.Object); + _ = SftpSessionMock.InSequence(sequence) + .Setup(p => p.Connect()); + _ = SessionMock.InSequence(sequence) + .Setup(p => p.OnDisconnecting()); + _ = SftpSessionMock.InSequence(sequence) + .Setup(p => p.Dispose()); + _ = SessionMock.InSequence(sequence) + .Setup(p => p.Dispose()); } protected override void Arrange() @@ -59,58 +67,58 @@ protected override void Act() [TestMethod] public void CreateSftpMessageFactoryOnServiceFactoryShouldBeInvokedOnce() { - _serviceFactoryMock.Verify(p => p.CreateSftpResponseFactory(), Times.Once); + ServiceFactoryMock.Verify(p => p.CreateSftpResponseFactory(), Times.Once); } [TestMethod] public void CreateSftpSessionOnServiceFactoryShouldBeInvokedOnce() { - _serviceFactoryMock.Verify( - p => p.CreateSftpSession(_sessionMock.Object, _operationTimeout, _connectionInfo.Encoding, _sftpResponseFactoryMock.Object), + ServiceFactoryMock.Verify( + p => p.CreateSftpSession(SessionMock.Object, _operationTimeout, _connectionInfo.Encoding, SftpResponseFactoryMock.Object), Times.Once); } [TestMethod] public void CreateSocketFactoryOnServiceFactoryShouldBeInvokedOnce() { - _serviceFactoryMock.Verify(p => p.CreateSocketFactory(), Times.Once); + ServiceFactoryMock.Verify(p => p.CreateSocketFactory(), Times.Once); } [TestMethod] public void CreateSessionOnServiceFactoryShouldBeInvokedOnce() { - _serviceFactoryMock.Verify(p => p.CreateSession(_connectionInfo, _socketFactoryMock.Object), + ServiceFactoryMock.Verify(p => p.CreateSession(_connectionInfo, SocketFactoryMock.Object), Times.Once); } [TestMethod] public void DisconnectOnNetConfSessionShouldNeverBeInvoked() { - _sftpSessionMock.Verify(p => p.Disconnect(), Times.Never); + SftpSessionMock.Verify(p => p.Disconnect(), Times.Never); } [TestMethod] public void DisconnectOnSessionShouldNeverBeInvoked() { - _sessionMock.Verify(p => p.Disconnect(), Times.Never); + SessionMock.Verify(p => p.Disconnect(), Times.Never); } [TestMethod] public void DisposeOnNetConfSessionShouldBeInvokedOnce() { - _sftpSessionMock.Verify(p => p.Dispose(), Times.Once); + SftpSessionMock.Verify(p => p.Dispose(), Times.Once); } [TestMethod] public void DisposeOnSessionShouldBeInvokedOnce() { - _sessionMock.Verify(p => p.Dispose(), Times.Once); + SessionMock.Verify(p => p.Dispose(), Times.Once); } [TestMethod] public void OnDisconnectingOnSessionShouldBeInvokedOnce() { - _sessionMock.Verify(p => p.OnDisconnecting(), Times.Once); + SessionMock.Verify(p => p.OnDisconnecting(), Times.Once); } } } diff --git a/src/Renci.SshNet.Tests/Classes/SftpClientTest_Finalize_Connected.cs b/src/Renci.SshNet.Tests/Classes/SftpClientTest_Finalize_Connected.cs index 033f0ea07..f98f6dad2 100644 --- a/src/Renci.SshNet.Tests/Classes/SftpClientTest_Finalize_Connected.cs +++ b/src/Renci.SshNet.Tests/Classes/SftpClientTest_Finalize_Connected.cs @@ -1,7 +1,8 @@ using System; + using Microsoft.VisualStudio.TestTools.UnitTesting; + using Moq; -using Renci.SshNet.Sftp; namespace Renci.SshNet.Tests.Classes { @@ -17,23 +18,25 @@ protected override void SetupData() { _connectionInfo = new ConnectionInfo("host", "user", new NoneAuthenticationMethod("userauth")); _operationTimeout = new Random().Next(1000, 10000); - _sftpClient = new SftpClient(_connectionInfo, false, _serviceFactoryMock.Object); - _sftpClient.OperationTimeout = TimeSpan.FromMilliseconds(_operationTimeout); + _sftpClient = new SftpClient(_connectionInfo, false, ServiceFactoryMock.Object) + { + OperationTimeout = TimeSpan.FromMilliseconds(_operationTimeout) + }; _sftpClientWeakRefence = new WeakReference(_sftpClient); } protected override void SetupMocks() { - _serviceFactoryMock.Setup(p => p.CreateSocketFactory()) - .Returns(_socketFactoryMock.Object); - _serviceFactoryMock.Setup(p => p.CreateSession(_connectionInfo, _socketFactoryMock.Object)) - .Returns(_sessionMock.Object); - _sessionMock.Setup(p => p.Connect()); - _serviceFactoryMock.Setup(p => p.CreateSftpResponseFactory()) - .Returns(_sftpResponseFactoryMock.Object); - _serviceFactoryMock.Setup(p => p.CreateSftpSession(_sessionMock.Object, _operationTimeout, _connectionInfo.Encoding, _sftpResponseFactoryMock.Object)) - .Returns(_sftpSessionMock.Object); - _sftpSessionMock.Setup(p => p.Connect()); + _ = ServiceFactoryMock.Setup(p => p.CreateSocketFactory()) + .Returns(SocketFactoryMock.Object); + _ = ServiceFactoryMock.Setup(p => p.CreateSession(_connectionInfo, SocketFactoryMock.Object)) + .Returns(SessionMock.Object); + _ = SessionMock.Setup(p => p.Connect()); + _ = ServiceFactoryMock.Setup(p => p.CreateSftpResponseFactory()) + .Returns(SftpResponseFactoryMock.Object); + _ = ServiceFactoryMock.Setup(p => p.CreateSftpSession(SessionMock.Object, _operationTimeout, _connectionInfo.Encoding, SftpResponseFactoryMock.Object)) + .Returns(SftpSessionMock.Object); + _ = SftpSessionMock.Setup(p => p.Connect()); } protected override void Arrange() @@ -60,7 +63,7 @@ public void DisconnectOnSftpSessionShouldNeverBeInvoked() // Since we recreated the mocks, this test has no value // We'll leaving ths test just in case we have a solution that does not require us // to recreate the mocks - _sftpSessionMock.Verify(p => p.Disconnect(), Times.Never); + SftpSessionMock.Verify(p => p.Disconnect(), Times.Never); } [TestMethod] @@ -69,7 +72,7 @@ public void DisposeOnSftpSessionShouldNeverBeInvoked() // Since we recreated the mocks, this test has no value // We'll leaving ths test just in case we have a solution that does not require us // to recreate the mocks - _sftpSessionMock.Verify(p => p.Dispose(), Times.Never); + SftpSessionMock.Verify(p => p.Dispose(), Times.Never); } [TestMethod] diff --git a/src/Renci.SshNet.Tests/Classes/ShellStreamTest_Write_WriteBufferEmptyAndWriteMoreBytesThanBufferSize.cs b/src/Renci.SshNet.Tests/Classes/ShellStreamTest_Write_WriteBufferEmptyAndWriteMoreBytesThanBufferSize.cs index 4f1fa8692..941c3f7bb 100644 --- a/src/Renci.SshNet.Tests/Classes/ShellStreamTest_Write_WriteBufferEmptyAndWriteMoreBytesThanBufferSize.cs +++ b/src/Renci.SshNet.Tests/Classes/ShellStreamTest_Write_WriteBufferEmptyAndWriteMoreBytesThanBufferSize.cs @@ -51,7 +51,7 @@ private void SetupData() _terminalModes = new Dictionary(); _bufferSize = random.Next(100, 1000); - _data = CryptoAbstraction.GenerateRandom(_bufferSize * 2 + 10); + _data = CryptoAbstraction.GenerateRandom((_bufferSize * 2) + 10); _offset = 0; _count = _data.Length; @@ -70,32 +70,32 @@ private void SetupMocks() { _mockSequence = new MockSequence(); - _sessionMock.InSequence(_mockSequence) - .Setup(p => p.ConnectionInfo) - .Returns(_connectionInfoMock.Object); - _connectionInfoMock.InSequence(_mockSequence) - .Setup(p => p.Encoding) - .Returns(new UTF8Encoding()); - _sessionMock.InSequence(_mockSequence) - .Setup(p => p.CreateChannelSession()) - .Returns(_channelSessionMock.Object); - _channelSessionMock.InSequence(_mockSequence) - .Setup(p => p.Open()); - _channelSessionMock.InSequence(_mockSequence) - .Setup(p => p.SendPseudoTerminalRequest(_terminalName, - _widthColumns, - _heightRows, - _widthPixels, - _heightPixels, - _terminalModes)) - .Returns(true); - _channelSessionMock.InSequence(_mockSequence) - .Setup(p => p.SendShellRequest()) - .Returns(true); - _channelSessionMock.InSequence(_mockSequence) - .Setup(p => p.SendData(_expectedBytesSent1)); - _channelSessionMock.InSequence(_mockSequence) - .Setup(p => p.SendData(_expectedBytesSent2)); + _ = _sessionMock.InSequence(_mockSequence) + .Setup(p => p.ConnectionInfo) + .Returns(_connectionInfoMock.Object); + _ = _connectionInfoMock.InSequence(_mockSequence) + .Setup(p => p.Encoding) + .Returns(new UTF8Encoding()); + _ = _sessionMock.InSequence(_mockSequence) + .Setup(p => p.CreateChannelSession()) + .Returns(_channelSessionMock.Object); + _ = _channelSessionMock.InSequence(_mockSequence) + .Setup(p => p.Open()); + _ = _channelSessionMock.InSequence(_mockSequence) + .Setup(p => p.SendPseudoTerminalRequest(_terminalName, + _widthColumns, + _heightRows, + _widthPixels, + _heightPixels, + _terminalModes)) + .Returns(true); + _ = _channelSessionMock.InSequence(_mockSequence) + .Setup(p => p.SendShellRequest()) + .Returns(true); + _ = _channelSessionMock.InSequence(_mockSequence) + .Setup(p => p.SendData(_expectedBytesSent1)); + _ = _channelSessionMock.InSequence(_mockSequence) + .Setup(p => p.SendData(_expectedBytesSent2)); } private void Arrange() @@ -129,14 +129,14 @@ public void BufferShouldHaveBeenFlushedTwice() [TestMethod] public void FlushShouldSendRemaningBytesToServer() { - var expectedBytesSent = _data.Take(_bufferSize * 2, _data.Length - _bufferSize * 2); + var expectedBytesSent = _data.Take(_bufferSize * 2, _data.Length - (_bufferSize * 2)); - _channelSessionMock.InSequence(_mockSequence) - .Setup(p => p.SendData(expectedBytesSent)); + _ = _channelSessionMock.InSequence(_mockSequence) + .Setup(p => p.SendData(expectedBytesSent)); _shellStream.Flush(); _channelSessionMock.Verify(p => p.SendData(expectedBytesSent), Times.Once); } } -} \ No newline at end of file +} diff --git a/src/Renci.SshNet.Tests/Classes/ShellStreamTest_Write_WriteBufferEmptyAndWriteZeroBytes.cs b/src/Renci.SshNet.Tests/Classes/ShellStreamTest_Write_WriteBufferEmptyAndWriteZeroBytes.cs index 05e63a19f..94d55ca87 100644 --- a/src/Renci.SshNet.Tests/Classes/ShellStreamTest_Write_WriteBufferEmptyAndWriteZeroBytes.cs +++ b/src/Renci.SshNet.Tests/Classes/ShellStreamTest_Write_WriteBufferEmptyAndWriteZeroBytes.cs @@ -1,9 +1,11 @@ using System; using System.Collections.Generic; using System.Text; + using Microsoft.VisualStudio.TestTools.UnitTesting; + using Moq; -using Renci.SshNet.Abstractions; + using Renci.SshNet.Channels; using Renci.SshNet.Common; @@ -64,28 +66,28 @@ private void SetupMocks() { _mockSequence = new MockSequence(); - _sessionMock.InSequence(_mockSequence) - .Setup(p => p.ConnectionInfo) - .Returns(_connectionInfoMock.Object); - _connectionInfoMock.InSequence(_mockSequence) - .Setup(p => p.Encoding) - .Returns(new UTF8Encoding()); - _sessionMock.InSequence(_mockSequence) - .Setup(p => p.CreateChannelSession()) - .Returns(_channelSessionMock.Object); - _channelSessionMock.InSequence(_mockSequence) - .Setup(p => p.Open()); - _channelSessionMock.InSequence(_mockSequence) - .Setup(p => p.SendPseudoTerminalRequest(_terminalName, - _widthColumns, - _heightRows, - _widthPixels, - _heightPixels, - _terminalModes)) - .Returns(true); - _channelSessionMock.InSequence(_mockSequence) - .Setup(p => p.SendShellRequest()) - .Returns(true); + _ = _sessionMock.InSequence(_mockSequence) + .Setup(p => p.ConnectionInfo) + .Returns(_connectionInfoMock.Object); + _ = _connectionInfoMock.InSequence(_mockSequence) + .Setup(p => p.Encoding) + .Returns(new UTF8Encoding()); + _ = _sessionMock.InSequence(_mockSequence) + .Setup(p => p.CreateChannelSession()) + .Returns(_channelSessionMock.Object); + _ = _channelSessionMock.InSequence(_mockSequence) + .Setup(p => p.Open()); + _ = _channelSessionMock.InSequence(_mockSequence) + .Setup(p => p.SendPseudoTerminalRequest(_terminalName, + _widthColumns, + _heightRows, + _widthPixels, + _heightPixels, + _terminalModes)) + .Returns(true); + _ = _channelSessionMock.InSequence(_mockSequence) + .Setup(p => p.SendShellRequest()) + .Returns(true); } private void Arrange() @@ -123,4 +125,4 @@ public void FlushShouldSendNoBytesToServer() _channelSessionMock.Verify(p => p.SendData(It.IsAny()), Times.Never); } } -} \ No newline at end of file +} diff --git a/src/Renci.SshNet.Tests/Classes/SshClientTest.cs b/src/Renci.SshNet.Tests/Classes/SshClientTest.cs index 78f1db6c4..1eabcae20 100644 --- a/src/Renci.SshNet.Tests/Classes/SshClientTest.cs +++ b/src/Renci.SshNet.Tests/Classes/SshClientTest.cs @@ -80,9 +80,11 @@ public void Test_Connect_Timeout() var password = Resources.PASSWORD; #region Example SshClient Connect Timeout - var connectionInfo = new PasswordConnectionInfo(host, username, password); - connectionInfo.Timeout = TimeSpan.FromSeconds(30); + var connectionInfo = new PasswordConnectionInfo(host, username, password) + { + Timeout = TimeSpan.FromSeconds(30) + }; using (var client = new SshClient(connectionInfo)) { @@ -942,4 +944,4 @@ public void ForwardedPortsTest() } } -} \ No newline at end of file +} diff --git a/src/Renci.SshNet.Tests/Classes/SshClientTest_CreateShellStream_TerminalNameAndColumnsAndRowsAndWidthAndHeightAndBufferSizeAndTerminalModes_Connected.cs b/src/Renci.SshNet.Tests/Classes/SshClientTest_CreateShellStream_TerminalNameAndColumnsAndRowsAndWidthAndHeightAndBufferSizeAndTerminalModes_Connected.cs index df1ea835f..4dc5a2063 100644 --- a/src/Renci.SshNet.Tests/Classes/SshClientTest_CreateShellStream_TerminalNameAndColumnsAndRowsAndWidthAndHeightAndBufferSizeAndTerminalModes_Connected.cs +++ b/src/Renci.SshNet.Tests/Classes/SshClientTest_CreateShellStream_TerminalNameAndColumnsAndRowsAndWidthAndHeightAndBufferSizeAndTerminalModes_Connected.cs @@ -43,16 +43,16 @@ protected override void SetupMocks() { var sequence = new MockSequence(); - _serviceFactoryMock.InSequence(sequence) + ServiceFactoryMock.InSequence(sequence) .Setup(p => p.CreateSocketFactory()) - .Returns(_socketFactoryMock.Object); - _serviceFactoryMock.InSequence(sequence) - .Setup(p => p.CreateSession(_connectionInfo, _socketFactoryMock.Object)) - .Returns(_sessionMock.Object); - _sessionMock.InSequence(sequence) + .Returns(SocketFactoryMock.Object); + ServiceFactoryMock.InSequence(sequence) + .Setup(p => p.CreateSession(_connectionInfo, SocketFactoryMock.Object)) + .Returns(SessionMock.Object); + SessionMock.InSequence(sequence) .Setup(p => p.Connect()); - _serviceFactoryMock.InSequence(sequence) - .Setup(p => p.CreateShellStream(_sessionMock.Object, + ServiceFactoryMock.InSequence(sequence) + .Setup(p => p.CreateShellStream(SessionMock.Object, _terminalName, _widthColumns, _heightRows, @@ -67,7 +67,7 @@ protected override void Arrange() { base.Arrange(); - _sshClient = new SshClient(_connectionInfo, false, _serviceFactoryMock.Object); + _sshClient = new SshClient(_connectionInfo, false, ServiceFactoryMock.Object); _sshClient.Connect(); } @@ -85,7 +85,7 @@ protected override void Act() [TestMethod] public void CreateShellStreamOnServiceFactoryShouldBeInvokedOnce() { - _serviceFactoryMock.Verify(p => p.CreateShellStream(_sessionMock.Object, + ServiceFactoryMock.Verify(p => p.CreateShellStream(SessionMock.Object, _terminalName, _widthColumns, _heightRows, diff --git a/src/Renci.SshNet.Tests/Classes/SshClientTest_CreateShellStream_TerminalNameAndColumnsAndRowsAndWidthAndHeightAndBufferSize_Connected.cs b/src/Renci.SshNet.Tests/Classes/SshClientTest_CreateShellStream_TerminalNameAndColumnsAndRowsAndWidthAndHeightAndBufferSize_Connected.cs index 337f9bce3..861c8c725 100644 --- a/src/Renci.SshNet.Tests/Classes/SshClientTest_CreateShellStream_TerminalNameAndColumnsAndRowsAndWidthAndHeightAndBufferSize_Connected.cs +++ b/src/Renci.SshNet.Tests/Classes/SshClientTest_CreateShellStream_TerminalNameAndColumnsAndRowsAndWidthAndHeightAndBufferSize_Connected.cs @@ -1,9 +1,10 @@ using System; -using System.Collections.Generic; + using Microsoft.VisualStudio.TestTools.UnitTesting; + using Moq; + using Renci.SshNet.Channels; -using Renci.SshNet.Common; namespace Renci.SshNet.Tests.Classes { @@ -41,31 +42,31 @@ protected override void SetupMocks() { var sequence = new MockSequence(); - _serviceFactoryMock.InSequence(sequence) - .Setup(p => p.CreateSocketFactory()) - .Returns(_socketFactoryMock.Object); - _serviceFactoryMock.InSequence(sequence) - .Setup(p => p.CreateSession(_connectionInfo, _socketFactoryMock.Object)) - .Returns(_sessionMock.Object); - _sessionMock.InSequence(sequence) - .Setup(p => p.Connect()); - _serviceFactoryMock.InSequence(sequence) - .Setup(p => p.CreateShellStream(_sessionMock.Object, - _terminalName, - _widthColumns, - _heightRows, - _widthPixels, - _heightPixels, - null, - _bufferSize)) - .Returns(_expected); + _ = ServiceFactoryMock.InSequence(sequence) + .Setup(p => p.CreateSocketFactory()) + .Returns(SocketFactoryMock.Object); + _ = ServiceFactoryMock.InSequence(sequence) + .Setup(p => p.CreateSession(_connectionInfo, SocketFactoryMock.Object)) + .Returns(SessionMock.Object); + _ = SessionMock.InSequence(sequence) + .Setup(p => p.Connect()); + _ = ServiceFactoryMock.InSequence(sequence) + .Setup(p => p.CreateShellStream(SessionMock.Object, + _terminalName, + _widthColumns, + _heightRows, + _widthPixels, + _heightPixels, + null, + _bufferSize)) + .Returns(_expected); } protected override void Arrange() { base.Arrange(); - _sshClient = new SshClient(_connectionInfo, false, _serviceFactoryMock.Object); + _sshClient = new SshClient(_connectionInfo, false, ServiceFactoryMock.Object); _sshClient.Connect(); } @@ -82,7 +83,7 @@ protected override void Act() [TestMethod] public void CreateShellStreamOnServiceFactoryShouldBeInvokedOnce() { - _serviceFactoryMock.Verify(p => p.CreateShellStream(_sessionMock.Object, + ServiceFactoryMock.Verify(p => p.CreateShellStream(SessionMock.Object, _terminalName, _widthColumns, _heightRows, @@ -105,20 +106,20 @@ private ShellStream CreateShellStream() var sessionMock = new Mock(MockBehavior.Loose); var channelSessionMock = new Mock(MockBehavior.Strict); - sessionMock.Setup(p => p.ConnectionInfo) - .Returns(new ConnectionInfo("A", "B", new PasswordAuthenticationMethod("A", "B"))); - sessionMock.Setup(p => p.CreateChannelSession()) - .Returns(channelSessionMock.Object); - channelSessionMock.Setup(p => p.Open()); - channelSessionMock.Setup(p => p.SendPseudoTerminalRequest(_terminalName, + _ = sessionMock.Setup(p => p.ConnectionInfo) + .Returns(new ConnectionInfo("A", "B", new PasswordAuthenticationMethod("A", "B"))); + _ = sessionMock.Setup(p => p.CreateChannelSession()) + .Returns(channelSessionMock.Object); + _ = channelSessionMock.Setup(p => p.Open()); + _ = channelSessionMock.Setup(p => p.SendPseudoTerminalRequest(_terminalName, _widthColumns, _heightRows, _widthPixels, _heightPixels, null)) - .Returns(true); - channelSessionMock.Setup(p => p.SendShellRequest()) - .Returns(true); + .Returns(true); + _ = channelSessionMock.Setup(p => p.SendShellRequest()) + .Returns(true); return new ShellStream(sessionMock.Object, _terminalName, diff --git a/src/Renci.SshNet.Tests/Classes/SshClientTest_Disconnect_ForwardedPortStarted.cs b/src/Renci.SshNet.Tests/Classes/SshClientTest_Disconnect_ForwardedPortStarted.cs index 6b1259f0c..234512645 100644 --- a/src/Renci.SshNet.Tests/Classes/SshClientTest_Disconnect_ForwardedPortStarted.cs +++ b/src/Renci.SshNet.Tests/Classes/SshClientTest_Disconnect_ForwardedPortStarted.cs @@ -27,24 +27,24 @@ protected override void SetupMocks() { var sequence = new MockSequence(); - _serviceFactoryMock.InSequence(sequence) + ServiceFactoryMock.InSequence(sequence) .Setup(p => p.CreateSocketFactory()) - .Returns(_socketFactoryMock.Object); - _serviceFactoryMock.InSequence(sequence) - .Setup(p => p.CreateSession(_connectionInfo, _socketFactoryMock.Object)) - .Returns(_sessionMock.Object); - _sessionMock.InSequence(sequence).Setup(p => p.Connect()); + .Returns(SocketFactoryMock.Object); + ServiceFactoryMock.InSequence(sequence) + .Setup(p => p.CreateSession(_connectionInfo, SocketFactoryMock.Object)) + .Returns(SessionMock.Object); + SessionMock.InSequence(sequence).Setup(p => p.Connect()); _forwardedPortMock.InSequence(sequence).Setup(p => p.Start()); - _sessionMock.InSequence(sequence).Setup(p => p.OnDisconnecting()); + SessionMock.InSequence(sequence).Setup(p => p.OnDisconnecting()); _forwardedPortMock.InSequence(sequence).Setup(p => p.Stop()); - _sessionMock.InSequence(sequence).Setup(p => p.Dispose()); + SessionMock.InSequence(sequence).Setup(p => p.Dispose()); } protected override void Arrange() { base.Arrange(); - _sshClient = new SshClient(_connectionInfo, false, _serviceFactoryMock.Object); + _sshClient = new SshClient(_connectionInfo, false, ServiceFactoryMock.Object); _sshClient.Connect(); _sshClient.AddForwardedPort(_forwardedPortMock.Object); @@ -71,13 +71,13 @@ public void ForwardedPortShouldBeRemovedFromSshClient() [TestMethod] public void DisconnectOnSessionShouldNeverBeInvoked() { - _sessionMock.Verify(p => p.Disconnect(), Times.Never); + SessionMock.Verify(p => p.Disconnect(), Times.Never); } [TestMethod] public void DisposeOnSessionShouldBeInvokedOnce() { - _sessionMock.Verify(p => p.Dispose(), Times.Once); + SessionMock.Verify(p => p.Dispose(), Times.Once); } } } diff --git a/src/Renci.SshNet.Tests/Classes/SshClientTest_Dispose_Connected.cs b/src/Renci.SshNet.Tests/Classes/SshClientTest_Dispose_Connected.cs index 55108df62..fd10b8937 100644 --- a/src/Renci.SshNet.Tests/Classes/SshClientTest_Dispose_Connected.cs +++ b/src/Renci.SshNet.Tests/Classes/SshClientTest_Dispose_Connected.cs @@ -18,22 +18,22 @@ protected override void SetupMocks() { var sequence = new MockSequence(); - _serviceFactoryMock.InSequence(sequence) + ServiceFactoryMock.InSequence(sequence) .Setup(p => p.CreateSocketFactory()) - .Returns(_socketFactoryMock.Object); - _serviceFactoryMock.InSequence(sequence) - .Setup(p => p.CreateSession(_connectionInfo, _socketFactoryMock.Object)) - .Returns(_sessionMock.Object); - _sessionMock.InSequence(sequence).Setup(p => p.Connect()); - _sessionMock.InSequence(sequence).Setup(p => p.OnDisconnecting()); - _sessionMock.InSequence(sequence).Setup(p => p.Dispose()); + .Returns(SocketFactoryMock.Object); + ServiceFactoryMock.InSequence(sequence) + .Setup(p => p.CreateSession(_connectionInfo, SocketFactoryMock.Object)) + .Returns(SessionMock.Object); + SessionMock.InSequence(sequence).Setup(p => p.Connect()); + SessionMock.InSequence(sequence).Setup(p => p.OnDisconnecting()); + SessionMock.InSequence(sequence).Setup(p => p.Dispose()); } protected override void Arrange() { base.Arrange(); - _sshClient = new SshClient(_connectionInfo, false, _serviceFactoryMock.Object); + _sshClient = new SshClient(_connectionInfo, false, ServiceFactoryMock.Object); _sshClient.Connect(); } @@ -45,32 +45,32 @@ protected override void Act() [TestMethod] public void CreateSocketFactoryOnServiceFactoryShouldBeInvokedOnce() { - _serviceFactoryMock.Verify(p => p.CreateSocketFactory(), Times.Once); + ServiceFactoryMock.Verify(p => p.CreateSocketFactory(), Times.Once); } [TestMethod] public void CreateSessionOnServiceFactoryShouldBeInvokedOnce() { - _serviceFactoryMock.Verify(p => p.CreateSession(_connectionInfo, _socketFactoryMock.Object), + ServiceFactoryMock.Verify(p => p.CreateSession(_connectionInfo, SocketFactoryMock.Object), Times.Once); } [TestMethod] public void DisconnectOnSessionShouldNeverBeInvoked() { - _sessionMock.Verify(p => p.Disconnect(), Times.Never); + SessionMock.Verify(p => p.Disconnect(), Times.Never); } [TestMethod] public void DisposeOnSessionShouldBeInvokedOnce() { - _sessionMock.Verify(p => p.Dispose(), Times.Once); + SessionMock.Verify(p => p.Dispose(), Times.Once); } [TestMethod] public void OnDisconnectingOnSessionShouldBeInvokedOnce() { - _sessionMock.Verify(p => p.OnDisconnecting(), Times.Once); + SessionMock.Verify(p => p.OnDisconnecting(), Times.Once); } } } diff --git a/src/Renci.SshNet.Tests/Classes/SshClientTest_Dispose_Disconnected.cs b/src/Renci.SshNet.Tests/Classes/SshClientTest_Dispose_Disconnected.cs index 1d78561be..bae18feb5 100644 --- a/src/Renci.SshNet.Tests/Classes/SshClientTest_Dispose_Disconnected.cs +++ b/src/Renci.SshNet.Tests/Classes/SshClientTest_Dispose_Disconnected.cs @@ -18,22 +18,22 @@ protected override void SetupMocks() { var sequence = new MockSequence(); - _serviceFactoryMock.InSequence(sequence) + ServiceFactoryMock.InSequence(sequence) .Setup(p => p.CreateSocketFactory()) - .Returns(_socketFactoryMock.Object); - _serviceFactoryMock.InSequence(sequence) - .Setup(p => p.CreateSession(_connectionInfo, _socketFactoryMock.Object)) - .Returns(_sessionMock.Object); - _sessionMock.InSequence(sequence).Setup(p => p.Connect()); - _sessionMock.InSequence(sequence).Setup(p => p.OnDisconnecting()); - _sessionMock.InSequence(sequence).Setup(p => p.Dispose()); + .Returns(SocketFactoryMock.Object); + ServiceFactoryMock.InSequence(sequence) + .Setup(p => p.CreateSession(_connectionInfo, SocketFactoryMock.Object)) + .Returns(SessionMock.Object); + SessionMock.InSequence(sequence).Setup(p => p.Connect()); + SessionMock.InSequence(sequence).Setup(p => p.OnDisconnecting()); + SessionMock.InSequence(sequence).Setup(p => p.Dispose()); } protected override void Arrange() { base.Arrange(); - _sshClient = new SshClient(_connectionInfo, false, _serviceFactoryMock.Object); + _sshClient = new SshClient(_connectionInfo, false, ServiceFactoryMock.Object); _sshClient.Connect(); _sshClient.Disconnect(); } @@ -46,32 +46,32 @@ protected override void Act() [TestMethod] public void CreateSocketFactoryOnServiceFactoryShouldBeInvokedOnce() { - _serviceFactoryMock.Verify(p => p.CreateSocketFactory(), Times.Once); + ServiceFactoryMock.Verify(p => p.CreateSocketFactory(), Times.Once); } [TestMethod] public void CreateSessionOnServiceFactoryShouldBeInvokedOnce() { - _serviceFactoryMock.Verify(p => p.CreateSession(_connectionInfo, _socketFactoryMock.Object), + ServiceFactoryMock.Verify(p => p.CreateSession(_connectionInfo, SocketFactoryMock.Object), Times.Once); } [TestMethod] public void DisconnectOnSessionShouldNeverBeInvoked() { - _sessionMock.Verify(p => p.Disconnect(), Times.Never); + SessionMock.Verify(p => p.Disconnect(), Times.Never); } [TestMethod] public void DisposeOnSessionShouldBeInvokedOnce() { - _sessionMock.Verify(p => p.Dispose(), Times.Once); + SessionMock.Verify(p => p.Dispose(), Times.Once); } [TestMethod] public void OnDisconnectingOnSessionShouldBeInvokedOnce() { - _sessionMock.Verify(p => p.OnDisconnecting(), Times.Once); + SessionMock.Verify(p => p.OnDisconnecting(), Times.Once); } } } diff --git a/src/Renci.SshNet.Tests/Classes/SshClientTest_Dispose_Disposed.cs b/src/Renci.SshNet.Tests/Classes/SshClientTest_Dispose_Disposed.cs index 54e07be9e..c4dcf868a 100644 --- a/src/Renci.SshNet.Tests/Classes/SshClientTest_Dispose_Disposed.cs +++ b/src/Renci.SshNet.Tests/Classes/SshClientTest_Dispose_Disposed.cs @@ -18,22 +18,22 @@ protected override void SetupMocks() { var sequence = new MockSequence(); - _serviceFactoryMock.InSequence(sequence) + ServiceFactoryMock.InSequence(sequence) .Setup(p => p.CreateSocketFactory()) - .Returns(_socketFactoryMock.Object); - _serviceFactoryMock.InSequence(sequence) - .Setup(p => p.CreateSession(_connectionInfo, _socketFactoryMock.Object)) - .Returns(_sessionMock.Object); - _sessionMock.InSequence(sequence).Setup(p => p.Connect()); - _sessionMock.InSequence(sequence).Setup(p => p.OnDisconnecting()); - _sessionMock.InSequence(sequence).Setup(p => p.Dispose()); + .Returns(SocketFactoryMock.Object); + ServiceFactoryMock.InSequence(sequence) + .Setup(p => p.CreateSession(_connectionInfo, SocketFactoryMock.Object)) + .Returns(SessionMock.Object); + SessionMock.InSequence(sequence).Setup(p => p.Connect()); + SessionMock.InSequence(sequence).Setup(p => p.OnDisconnecting()); + SessionMock.InSequence(sequence).Setup(p => p.Dispose()); } protected override void Arrange() { base.Arrange(); - _sshClient = new SshClient(_connectionInfo, false, _serviceFactoryMock.Object); + _sshClient = new SshClient(_connectionInfo, false, ServiceFactoryMock.Object); _sshClient.Connect(); _sshClient.Dispose(); } @@ -46,32 +46,32 @@ protected override void Act() [TestMethod] public void CreateSocketFactoryOnServiceFactoryShouldBeInvokedOnce() { - _serviceFactoryMock.Verify(p => p.CreateSocketFactory(), Times.Once); + ServiceFactoryMock.Verify(p => p.CreateSocketFactory(), Times.Once); } [TestMethod] public void CreateSessionOnServiceFactoryShouldBeInvokedOnce() { - _serviceFactoryMock.Verify(p => p.CreateSession(_connectionInfo, _socketFactoryMock.Object), + ServiceFactoryMock.Verify(p => p.CreateSession(_connectionInfo, SocketFactoryMock.Object), Times.Once); } [TestMethod] public void DisconnectOnSessionShouldNeverBeInvoked() { - _sessionMock.Verify(p => p.Disconnect(), Times.Never); + SessionMock.Verify(p => p.Disconnect(), Times.Never); } [TestMethod] public void DisposeOnSessionShouldBeInvokedOnce() { - _sessionMock.Verify(p => p.Dispose(), Times.Once); + SessionMock.Verify(p => p.Dispose(), Times.Once); } [TestMethod] public void OnDisconnectingOnSessionShouldBeInvokedOnce() { - _sessionMock.Verify(p => p.OnDisconnecting(), Times.Once); + SessionMock.Verify(p => p.OnDisconnecting(), Times.Once); } } } diff --git a/src/Renci.SshNet.Tests/Classes/SshClientTest_Dispose_ForwardedPortStarted.cs b/src/Renci.SshNet.Tests/Classes/SshClientTest_Dispose_ForwardedPortStarted.cs index 0b6da3cd3..213e11ef3 100644 --- a/src/Renci.SshNet.Tests/Classes/SshClientTest_Dispose_ForwardedPortStarted.cs +++ b/src/Renci.SshNet.Tests/Classes/SshClientTest_Dispose_ForwardedPortStarted.cs @@ -28,24 +28,24 @@ protected override void SetupMocks() { var sequence = new MockSequence(); - _serviceFactoryMock.InSequence(sequence) + ServiceFactoryMock.InSequence(sequence) .Setup(p => p.CreateSocketFactory()) - .Returns(_socketFactoryMock.Object); - _serviceFactoryMock.InSequence(sequence) - .Setup(p => p.CreateSession(_connectionInfo, _socketFactoryMock.Object)) - .Returns(_sessionMock.Object); - _sessionMock.InSequence(sequence).Setup(p => p.Connect()); + .Returns(SocketFactoryMock.Object); + ServiceFactoryMock.InSequence(sequence) + .Setup(p => p.CreateSession(_connectionInfo, SocketFactoryMock.Object)) + .Returns(SessionMock.Object); + SessionMock.InSequence(sequence).Setup(p => p.Connect()); _forwardedPortMock.InSequence(sequence).Setup(p => p.Start()); - _sessionMock.InSequence(sequence).Setup(p => p.OnDisconnecting()); + SessionMock.InSequence(sequence).Setup(p => p.OnDisconnecting()); _forwardedPortMock.InSequence(sequence).Setup(p => p.Stop()); - _sessionMock.InSequence(sequence).Setup(p => p.Dispose()); + SessionMock.InSequence(sequence).Setup(p => p.Dispose()); } protected override void Arrange() { base.Arrange(); - _sshClient = new SshClient(_connectionInfo, false, _serviceFactoryMock.Object); + _sshClient = new SshClient(_connectionInfo, false, ServiceFactoryMock.Object); _sshClient.Connect(); _sshClient.AddForwardedPort(_forwardedPortMock.Object); @@ -86,13 +86,13 @@ public void IsConnectedShouldThrowObjectDisposedException() [TestMethod] public void DisconnectOnSessionShouldNeverBeInvoked() { - _sessionMock.Verify(p => p.Disconnect(), Times.Never); + SessionMock.Verify(p => p.Disconnect(), Times.Never); } [TestMethod] public void DisposeOnSessionShouldBeInvokedOnce() { - _sessionMock.Verify(p => p.Dispose(), Times.Once); + SessionMock.Verify(p => p.Dispose(), Times.Once); } } } diff --git a/src/Renci.SshNet.Tests/Classes/SshCommandTest.cs b/src/Renci.SshNet.Tests/Classes/SshCommandTest.cs index cfd68b078..d43a11e5e 100644 --- a/src/Renci.SshNet.Tests/Classes/SshCommandTest.cs +++ b/src/Renci.SshNet.Tests/Classes/SshCommandTest.cs @@ -104,10 +104,14 @@ public void Test_Execute_OutputStream() { var result = reader.ReadToEnd(); if (string.IsNullOrEmpty(result)) + { continue; + } + Console.Write(result); } - cmd.EndExecute(asynch); + + _ = cmd.EndExecute(asynch); client.Disconnect(); #endregion @@ -730,4 +734,4 @@ private static bool ExecuteTestCommand(SshClient s) return result.Equals(testValue); } } -} \ No newline at end of file +} diff --git a/src/Renci.SshNet.Tests/Classes/SshCommandTest_EndExecute_AsyncResultFromOtherInstance.cs b/src/Renci.SshNet.Tests/Classes/SshCommandTest_EndExecute_AsyncResultFromOtherInstance.cs index b312a2058..5584786c5 100644 --- a/src/Renci.SshNet.Tests/Classes/SshCommandTest_EndExecute_AsyncResultFromOtherInstance.cs +++ b/src/Renci.SshNet.Tests/Classes/SshCommandTest_EndExecute_AsyncResultFromOtherInstance.cs @@ -1,8 +1,11 @@ using System; using System.Globalization; using System.Text; + using Microsoft.VisualStudio.TestTools.UnitTesting; + using Moq; + using Renci.SshNet.Channels; using Renci.SshNet.Tests.Common; @@ -39,15 +42,26 @@ private void Arrange() _asyncResultB = null; var seq = new MockSequence(); - _sessionMock.InSequence(seq).Setup(p => p.CreateChannelSession()).Returns(_channelSessionAMock.Object); - _channelSessionAMock.InSequence(seq).Setup(p => p.Open()); - _channelSessionAMock.InSequence(seq).Setup(p => p.SendExecRequest(_commandText)).Returns(true); - _sessionMock.InSequence(seq).Setup(p => p.CreateChannelSession()).Returns(_channelSessionBMock.Object); - _channelSessionBMock.InSequence(seq).Setup(p => p.Open()); - _channelSessionBMock.InSequence(seq).Setup(p => p.SendExecRequest(_commandText)).Returns(true); + + _ = _sessionMock.InSequence(seq) + .Setup(p => p.CreateChannelSession()) + .Returns(_channelSessionAMock.Object); + _ = _channelSessionAMock.InSequence(seq) + .Setup(p => p.Open()); + _ = _channelSessionAMock.InSequence(seq) + .Setup(p => p.SendExecRequest(_commandText)) + .Returns(true); + _ = _sessionMock.InSequence(seq) + .Setup(p => p.CreateChannelSession()) + .Returns(_channelSessionBMock.Object); + _ = _channelSessionBMock.InSequence(seq) + .Setup(p => p.Open()); + _ = _channelSessionBMock.InSequence(seq) + .Setup(p => p.SendExecRequest(_commandText)) + .Returns(true); _sshCommandA = new SshCommand(_sessionMock.Object, _commandText, _encoding); - _sshCommandA.BeginExecute(); + _ = _sshCommandA.BeginExecute(); _sshCommandB = new SshCommand(_sessionMock.Object, _commandText, _encoding); _asyncResultB = _sshCommandB.BeginExecute(); @@ -57,7 +71,7 @@ private void Act() { try { - _sshCommandA.EndExecute(_asyncResultB); + _ = _sshCommandA.EndExecute(_asyncResultB); Assert.Fail(); } catch (ArgumentException ex) @@ -71,7 +85,7 @@ public void EndExecuteShouldHaveThrownArgumentException() { Assert.IsNotNull(_actualException); Assert.IsNull(_actualException.InnerException); - Assert.AreEqual(string.Format("The {0} object was not returned from the corresponding asynchronous method on this class.", typeof(IAsyncResult).Name), _actualException.Message); + Assert.AreEqual(string.Format("The {0} object was not returned from the corresponding asynchronous method on this class.", nameof(IAsyncResult)), _actualException.Message); Assert.IsNull(_actualException.ParamName); } } diff --git a/src/Renci.SshNet.Tests/Classes/SubsystemSessionStub.cs b/src/Renci.SshNet.Tests/Classes/SubsystemSessionStub.cs index 241b49104..e7fab595a 100644 --- a/src/Renci.SshNet.Tests/Classes/SubsystemSessionStub.cs +++ b/src/Renci.SshNet.Tests/Classes/SubsystemSessionStub.cs @@ -1,7 +1,7 @@ using System; using System.Collections.Generic; -using System.Text; using System.Threading; + using Renci.SshNet.Common; namespace Renci.SshNet.Tests.Classes @@ -29,10 +29,12 @@ public int OnChannelOpenInvocationCount protected override void OnChannelOpen() { - Interlocked.Increment(ref _onChannelOpenInvocationCount); + _ = Interlocked.Increment(ref _onChannelOpenInvocationCount); if (OnChannelOpenException != null) + { throw OnChannelOpenException; + } } protected override void OnDataReceived(byte[] data) @@ -40,7 +42,9 @@ protected override void OnDataReceived(byte[] data) OnDataReceivedInvocations.Add(new ChannelDataEventArgs(0, data)); if (OnDataReceivedException != null) + { throw OnDataReceivedException; + } } } } diff --git a/src/Renci.SshNet.Tests/Classes/SubsystemSession_Connect_Disconnected.cs b/src/Renci.SshNet.Tests/Classes/SubsystemSession_Connect_Disconnected.cs index 1d15dd6e5..273ceef45 100644 --- a/src/Renci.SshNet.Tests/Classes/SubsystemSession_Connect_Disconnected.cs +++ b/src/Renci.SshNet.Tests/Classes/SubsystemSession_Connect_Disconnected.cs @@ -1,9 +1,11 @@ using System; using System.Collections.Generic; using System.Globalization; -using System.Text; + using Microsoft.VisualStudio.TestTools.UnitTesting; + using Moq; + using Renci.SshNet.Channels; using Renci.SshNet.Common; @@ -42,18 +44,29 @@ protected void Arrange() _channelAfterDisconnectMock = new Mock(MockBehavior.Strict); _sequence = new MockSequence(); - _sessionMock.InSequence(_sequence).Setup(p => p.CreateChannelSession()).Returns(_channelBeforeDisconnectMock.Object); - _channelBeforeDisconnectMock.InSequence(_sequence).Setup(p => p.Open()); - _channelBeforeDisconnectMock.InSequence(_sequence).Setup(p => p.SendSubsystemRequest(_subsystemName)).Returns(true); - _channelBeforeDisconnectMock.InSequence(_sequence).Setup(p => p.Dispose()); - _sessionMock.InSequence(_sequence).Setup(p => p.CreateChannelSession()).Returns(_channelAfterDisconnectMock.Object); - _channelAfterDisconnectMock.InSequence(_sequence).Setup(p => p.Open()); - _channelAfterDisconnectMock.InSequence(_sequence).Setup(p => p.SendSubsystemRequest(_subsystemName)).Returns(true); - - _subsystemSession = new SubsystemSessionStub( - _sessionMock.Object, - _subsystemName, - _operationTimeout); + + _ = _sessionMock.InSequence(_sequence) + .Setup(p => p.CreateChannelSession()) + .Returns(_channelBeforeDisconnectMock.Object); + _ = _channelBeforeDisconnectMock.InSequence(_sequence) + .Setup(p => p.Open()); + _ = _channelBeforeDisconnectMock.InSequence(_sequence) + .Setup(p => p.SendSubsystemRequest(_subsystemName)) + .Returns(true); + _ = _channelBeforeDisconnectMock.InSequence(_sequence) + .Setup(p => p.Dispose()); + _ = _sessionMock.InSequence(_sequence) + .Setup(p => p.CreateChannelSession()) + .Returns(_channelAfterDisconnectMock.Object); + _ = _channelAfterDisconnectMock.InSequence(_sequence) + .Setup(p => p.Open()); + _ = _channelAfterDisconnectMock.InSequence(_sequence) + .Setup(p => p.SendSubsystemRequest(_subsystemName)) + .Returns(true); + + _subsystemSession = new SubsystemSessionStub(_sessionMock.Object, + _subsystemName, + _operationTimeout); _subsystemSession.Disconnected += (sender, args) => _disconnectedRegister.Add(args); _subsystemSession.ErrorOccurred += (sender, args) => _errorOccurredRegister.Add(args); _subsystemSession.Connect(); @@ -80,7 +93,9 @@ public void ErrorOccurredHasNeverFired() [TestMethod] public void IsOpenShouldReturnTrueWhenChannelIsOpen() { - _channelAfterDisconnectMock.InSequence(_sequence).Setup(p => p.IsOpen).Returns(true); + _ = _channelAfterDisconnectMock.InSequence(_sequence) + .Setup(p => p.IsOpen) + .Returns(true); Assert.IsTrue(_subsystemSession.IsOpen); @@ -90,7 +105,9 @@ public void IsOpenShouldReturnTrueWhenChannelIsOpen() [TestMethod] public void IsOpenShouldReturnFalseWhenChannelIsNotOpen() { - _channelAfterDisconnectMock.InSequence(_sequence).Setup(p => p.IsOpen).Returns(false); + _ = _channelAfterDisconnectMock.InSequence(_sequence) + .Setup(p => p.IsOpen) + .Returns(false); Assert.IsFalse(_subsystemSession.IsOpen); diff --git a/src/Renci.SshNet.Tests/Classes/SubsystemSession_Connect_Disposed.cs b/src/Renci.SshNet.Tests/Classes/SubsystemSession_Connect_Disposed.cs index 11e6b0c63..2d90ce740 100644 --- a/src/Renci.SshNet.Tests/Classes/SubsystemSession_Connect_Disposed.cs +++ b/src/Renci.SshNet.Tests/Classes/SubsystemSession_Connect_Disposed.cs @@ -1,9 +1,11 @@ using System; using System.Collections.Generic; using System.Globalization; -using System.Text; + using Microsoft.VisualStudio.TestTools.UnitTesting; + using Moq; + using Renci.SshNet.Channels; using Renci.SshNet.Common; @@ -40,14 +42,19 @@ protected void Arrange() _channelMock = new Mock(MockBehavior.Strict); var sequence = new MockSequence(); - _sessionMock.InSequence(sequence).Setup(p => p.CreateChannelSession()).Returns(_channelMock.Object); - _channelMock.InSequence(sequence).Setup(p => p.Open()); - _channelMock.InSequence(sequence).Setup(p => p.SendSubsystemRequest(_subsystemName)).Returns(true); - _subsystemSession = new SubsystemSessionStub( - _sessionMock.Object, - _subsystemName, - _operationTimeout); + _ = _sessionMock.InSequence(sequence) + .Setup(p => p.CreateChannelSession()) + .Returns(_channelMock.Object); + _ = _channelMock.InSequence(sequence) + .Setup(p => p.Open()); + _ = _channelMock.InSequence(sequence) + .Setup(p => p.SendSubsystemRequest(_subsystemName)) + .Returns(true); + + _subsystemSession = new SubsystemSessionStub(_sessionMock.Object, + _subsystemName, + _operationTimeout); _subsystemSession.Disconnected += (sender, args) => _disconnectedRegister.Add(args); _subsystemSession.ErrorOccurred += (sender, args) => _errorOccurredRegister.Add(args); _subsystemSession.Dispose(); @@ -58,6 +65,7 @@ protected void Act() try { _subsystemSession.Connect(); + Assert.Fail(); } catch (ObjectDisposedException ex) { diff --git a/src/Renci.SshNet.Tests/Classes/SubsystemSession_Connect_NeverConnected.cs b/src/Renci.SshNet.Tests/Classes/SubsystemSession_Connect_NeverConnected.cs index d784c7aed..23bd273ed 100644 --- a/src/Renci.SshNet.Tests/Classes/SubsystemSession_Connect_NeverConnected.cs +++ b/src/Renci.SshNet.Tests/Classes/SubsystemSession_Connect_NeverConnected.cs @@ -1,9 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace Renci.SshNet.Tests.Classes +namespace Renci.SshNet.Tests.Classes { class SubsystemSession_Connect_NeverConnected { diff --git a/src/Renci.SshNet.Tests/Classes/SubsystemSession_Disconnect_Connected.cs b/src/Renci.SshNet.Tests/Classes/SubsystemSession_Disconnect_Connected.cs index f5d078135..bf1b3b789 100644 --- a/src/Renci.SshNet.Tests/Classes/SubsystemSession_Disconnect_Connected.cs +++ b/src/Renci.SshNet.Tests/Classes/SubsystemSession_Disconnect_Connected.cs @@ -1,9 +1,11 @@ using System; using System.Collections.Generic; using System.Globalization; -using System.Text; + using Microsoft.VisualStudio.TestTools.UnitTesting; + using Moq; + using Renci.SshNet.Channels; using Renci.SshNet.Common; @@ -40,10 +42,17 @@ protected void Arrange() _channelMock = new Mock(MockBehavior.Strict); _sequence = new MockSequence(); - _sessionMock.InSequence(_sequence).Setup(p => p.CreateChannelSession()).Returns(_channelMock.Object); - _channelMock.InSequence(_sequence).Setup(p => p.Open()); - _channelMock.InSequence(_sequence).Setup(p => p.SendSubsystemRequest(_subsystemName)).Returns(true); - _channelMock.InSequence(_sequence).Setup(p => p.Dispose()); + + _ = _sessionMock.InSequence(_sequence) + .Setup(p => p.CreateChannelSession()) + .Returns(_channelMock.Object); + _ = _channelMock.InSequence(_sequence) + .Setup(p => p.Open()); + _ = _channelMock.InSequence(_sequence) + .Setup(p => p.SendSubsystemRequest(_subsystemName)) + .Returns(true); + _ = _channelMock.InSequence(_sequence) + .Setup(p => p.Dispose()); _subsystemSession = new SubsystemSessionStub( _sessionMock.Object, diff --git a/src/Renci.SshNet.Tests/Classes/SubsystemSession_Disconnect_Disposed.cs b/src/Renci.SshNet.Tests/Classes/SubsystemSession_Disconnect_Disposed.cs index 21116a78e..4ee558c3b 100644 --- a/src/Renci.SshNet.Tests/Classes/SubsystemSession_Disconnect_Disposed.cs +++ b/src/Renci.SshNet.Tests/Classes/SubsystemSession_Disconnect_Disposed.cs @@ -1,9 +1,11 @@ using System; using System.Collections.Generic; using System.Globalization; -using System.Text; + using Microsoft.VisualStudio.TestTools.UnitTesting; + using Moq; + using Renci.SshNet.Channels; using Renci.SshNet.Common; @@ -39,15 +41,21 @@ protected void Arrange() _channelMock = new Mock(MockBehavior.Strict); var sequence = new MockSequence(); - _sessionMock.InSequence(sequence).Setup(p => p.CreateChannelSession()).Returns(_channelMock.Object); - _channelMock.InSequence(sequence).Setup(p => p.Open()); - _channelMock.InSequence(sequence).Setup(p => p.SendSubsystemRequest(_subsystemName)).Returns(true); - _channelMock.InSequence(sequence).Setup(p => p.Dispose()); - _subsystemSession = new SubsystemSessionStub( - _sessionMock.Object, - _subsystemName, - _operationTimeout); + _ = _sessionMock.InSequence(sequence) + .Setup(p => p.CreateChannelSession()) + .Returns(_channelMock.Object); + _ = _channelMock.InSequence(sequence) + .Setup(p => p.Open()); + _ = _channelMock.InSequence(sequence) + .Setup(p => p.SendSubsystemRequest(_subsystemName)) + .Returns(true); + _ = _channelMock.InSequence(sequence) + .Setup(p => p.Dispose()); + + _subsystemSession = new SubsystemSessionStub(_sessionMock.Object, + _subsystemName, + _operationTimeout); _subsystemSession.Disconnected += (sender, args) => _disconnectedRegister.Add(args); _subsystemSession.ErrorOccurred += (sender, args) => _errorOccurredRegister.Add(args); _subsystemSession.Connect(); diff --git a/src/Renci.SshNet.Tests/Classes/SubsystemSession_Disconnect_NeverConnected.cs b/src/Renci.SshNet.Tests/Classes/SubsystemSession_Disconnect_NeverConnected.cs index 71b161a56..a7edaf9f6 100644 --- a/src/Renci.SshNet.Tests/Classes/SubsystemSession_Disconnect_NeverConnected.cs +++ b/src/Renci.SshNet.Tests/Classes/SubsystemSession_Disconnect_NeverConnected.cs @@ -1,9 +1,11 @@ using System; using System.Collections.Generic; using System.Globalization; -using System.Text; + using Microsoft.VisualStudio.TestTools.UnitTesting; + using Moq; + using Renci.SshNet.Common; namespace Renci.SshNet.Tests.Classes @@ -35,10 +37,9 @@ protected void Arrange() _sessionMock = new Mock(MockBehavior.Strict); - _subsystemSession = new SubsystemSessionStub( - _sessionMock.Object, - _subsystemName, - _operationTimeout); + _subsystemSession = new SubsystemSessionStub(_sessionMock.Object, + _subsystemName, + _operationTimeout); _subsystemSession.Disconnected += (sender, args) => _disconnectedRegister.Add(args); _subsystemSession.ErrorOccurred += (sender, args) => _errorOccurredRegister.Add(args); } diff --git a/src/Renci.SshNet.Tests/Classes/SubsystemSession_Dispose_Connected.cs b/src/Renci.SshNet.Tests/Classes/SubsystemSession_Dispose_Connected.cs index f89da65ce..3de5b14a7 100644 --- a/src/Renci.SshNet.Tests/Classes/SubsystemSession_Dispose_Connected.cs +++ b/src/Renci.SshNet.Tests/Classes/SubsystemSession_Dispose_Connected.cs @@ -1,9 +1,11 @@ using System; using System.Collections.Generic; using System.Globalization; -using System.Text; + using Microsoft.VisualStudio.TestTools.UnitTesting; + using Moq; + using Renci.SshNet.Channels; using Renci.SshNet.Common; @@ -39,15 +41,13 @@ protected void Arrange() _channelMock = new Mock(MockBehavior.Strict); var sequence = new MockSequence(); - _sessionMock.InSequence(sequence).Setup(p => p.CreateChannelSession()).Returns(_channelMock.Object); - _channelMock.InSequence(sequence).Setup(p => p.Open()); - _channelMock.InSequence(sequence).Setup(p => p.SendSubsystemRequest(_subsystemName)).Returns(true); - _channelMock.InSequence(sequence).Setup(p => p.Dispose()); - _subsystemSession = new SubsystemSessionStub( - _sessionMock.Object, - _subsystemName, - _operationTimeout); + _ = _sessionMock.InSequence(sequence).Setup(p => p.CreateChannelSession()).Returns(_channelMock.Object); + _ = _channelMock.InSequence(sequence).Setup(p => p.Open()); + _ = _channelMock.InSequence(sequence).Setup(p => p.SendSubsystemRequest(_subsystemName)).Returns(true); + _ = _channelMock.InSequence(sequence).Setup(p => p.Dispose()); + + _subsystemSession = new SubsystemSessionStub(_sessionMock.Object, _subsystemName, _operationTimeout); _subsystemSession.Disconnected += (sender, args) => _disconnectedRegister.Add(args); _subsystemSession.ErrorOccurred += (sender, args) => _errorOccurredRegister.Add(args); _subsystemSession.Connect(); diff --git a/src/Renci.SshNet.Tests/Classes/SubsystemSession_Dispose_Disconnected.cs b/src/Renci.SshNet.Tests/Classes/SubsystemSession_Dispose_Disconnected.cs index c304ed43a..eaae69dc0 100644 --- a/src/Renci.SshNet.Tests/Classes/SubsystemSession_Dispose_Disconnected.cs +++ b/src/Renci.SshNet.Tests/Classes/SubsystemSession_Dispose_Disconnected.cs @@ -1,9 +1,11 @@ using System; using System.Collections.Generic; using System.Globalization; -using System.Text; + using Microsoft.VisualStudio.TestTools.UnitTesting; + using Moq; + using Renci.SshNet.Channels; using Renci.SshNet.Common; @@ -39,10 +41,17 @@ protected void Arrange() _channelMock = new Mock(MockBehavior.Strict); var sequence = new MockSequence(); - _sessionMock.InSequence(sequence).Setup(p => p.CreateChannelSession()).Returns(_channelMock.Object); - _channelMock.InSequence(sequence).Setup(p => p.Open()); - _channelMock.InSequence(sequence).Setup(p => p.SendSubsystemRequest(_subsystemName)).Returns(true); - _channelMock.InSequence(sequence).Setup(p => p.Dispose()); + + _ = _sessionMock.InSequence(sequence) + .Setup(p => p.CreateChannelSession()) + .Returns(_channelMock.Object); + _ = _channelMock.InSequence(sequence) + .Setup(p => p.Open()); + _ = _channelMock.InSequence(sequence) + .Setup(p => p.SendSubsystemRequest(_subsystemName)) + .Returns(true); + _ = _channelMock.InSequence(sequence) + .Setup(p => p.Dispose()); _subsystemSession = new SubsystemSessionStub( _sessionMock.Object, diff --git a/src/Renci.SshNet.Tests/Classes/SubsystemSession_Dispose_Disposed.cs b/src/Renci.SshNet.Tests/Classes/SubsystemSession_Dispose_Disposed.cs index d2f93decf..e0da36780 100644 --- a/src/Renci.SshNet.Tests/Classes/SubsystemSession_Dispose_Disposed.cs +++ b/src/Renci.SshNet.Tests/Classes/SubsystemSession_Dispose_Disposed.cs @@ -1,9 +1,11 @@ using System; using System.Collections.Generic; using System.Globalization; -using System.Text; + using Microsoft.VisualStudio.TestTools.UnitTesting; + using Moq; + using Renci.SshNet.Channels; using Renci.SshNet.Common; @@ -39,10 +41,17 @@ protected void Arrange() _channelMock = new Mock(MockBehavior.Strict); var sequence = new MockSequence(); - _sessionMock.InSequence(sequence).Setup(p => p.CreateChannelSession()).Returns(_channelMock.Object); - _channelMock.InSequence(sequence).Setup(p => p.Open()); - _channelMock.InSequence(sequence).Setup(p => p.SendSubsystemRequest(_subsystemName)).Returns(true); - _channelMock.InSequence(sequence).Setup(p => p.Dispose()); + + _ = _sessionMock.InSequence(sequence) + .Setup(p => p.CreateChannelSession()) + .Returns(_channelMock.Object); + _ = _channelMock.InSequence(sequence) + .Setup(p => p.Open()); + _ = _channelMock.InSequence(sequence) + .Setup(p => p.SendSubsystemRequest(_subsystemName)) + .Returns(true); + _ = _channelMock.InSequence(sequence) + .Setup(p => p.Dispose()); _subsystemSession = new SubsystemSessionStub( _sessionMock.Object, diff --git a/src/Renci.SshNet.Tests/Classes/SubsystemSession_Dispose_NeverConnected.cs b/src/Renci.SshNet.Tests/Classes/SubsystemSession_Dispose_NeverConnected.cs index 83fab8995..96e768c9e 100644 --- a/src/Renci.SshNet.Tests/Classes/SubsystemSession_Dispose_NeverConnected.cs +++ b/src/Renci.SshNet.Tests/Classes/SubsystemSession_Dispose_NeverConnected.cs @@ -1,10 +1,11 @@ using System; using System.Collections.Generic; using System.Globalization; -using System.Text; + using Microsoft.VisualStudio.TestTools.UnitTesting; + using Moq; -using Renci.SshNet.Channels; + using Renci.SshNet.Common; namespace Renci.SshNet.Tests.Classes @@ -29,6 +30,7 @@ public void Setup() protected void Arrange() { var random = new Random(); + _subsystemName = random.Next().ToString(CultureInfo.InvariantCulture); _operationTimeout = 30000; _disconnectedRegister = new List(); @@ -36,10 +38,9 @@ protected void Arrange() _sessionMock = new Mock(MockBehavior.Strict); - _subsystemSession = new SubsystemSessionStub( - _sessionMock.Object, - _subsystemName, - _operationTimeout); + _subsystemSession = new SubsystemSessionStub(_sessionMock.Object, + _subsystemName, + _operationTimeout); _subsystemSession.Disconnected += (sender, args) => _disconnectedRegister.Add(args); _subsystemSession.ErrorOccurred += (sender, args) => _errorOccurredRegister.Add(args); } diff --git a/src/Renci.SshNet.Tests/Classes/SubsystemSession_OnChannelException_Disposed.cs b/src/Renci.SshNet.Tests/Classes/SubsystemSession_OnChannelException_Disposed.cs index d9b3a162b..9f6f054ec 100644 --- a/src/Renci.SshNet.Tests/Classes/SubsystemSession_OnChannelException_Disposed.cs +++ b/src/Renci.SshNet.Tests/Classes/SubsystemSession_OnChannelException_Disposed.cs @@ -1,9 +1,11 @@ using System; using System.Collections.Generic; using System.Globalization; -using System.Text; + using Microsoft.VisualStudio.TestTools.UnitTesting; + using Moq; + using Renci.SshNet.Channels; using Renci.SshNet.Common; @@ -41,10 +43,17 @@ protected void Arrange() _channelMock = new Mock(MockBehavior.Strict); var sequence = new MockSequence(); - _sessionMock.InSequence(sequence).Setup(p => p.CreateChannelSession()).Returns(_channelMock.Object); - _channelMock.InSequence(sequence).Setup(p => p.Open()); - _channelMock.InSequence(sequence).Setup(p => p.SendSubsystemRequest(_subsystemName)).Returns(true); - _channelMock.InSequence(sequence).Setup(p => p.Dispose()); + + _ = _sessionMock.InSequence(sequence) + .Setup(p => p.CreateChannelSession()) + .Returns(_channelMock.Object); + _ = _channelMock.InSequence(sequence) + .Setup(p => p.Open()); + _ = _channelMock.InSequence(sequence) + .Setup(p => p.SendSubsystemRequest(_subsystemName)) + .Returns(true); + _ = _channelMock.InSequence(sequence) + .Setup(p => p.Dispose()); _subsystemSession = new SubsystemSessionStub( _sessionMock.Object, diff --git a/src/Renci.SshNet.Tests/Classes/SubsystemSession_OnSessionDisconnected_Connected.cs b/src/Renci.SshNet.Tests/Classes/SubsystemSession_OnSessionDisconnected_Connected.cs index b6851cfcf..f689d8017 100644 --- a/src/Renci.SshNet.Tests/Classes/SubsystemSession_OnSessionDisconnected_Connected.cs +++ b/src/Renci.SshNet.Tests/Classes/SubsystemSession_OnSessionDisconnected_Connected.cs @@ -1,9 +1,11 @@ using System; using System.Collections.Generic; using System.Globalization; -using System.Text; + using Microsoft.VisualStudio.TestTools.UnitTesting; + using Moq; + using Renci.SshNet.Channels; using Renci.SshNet.Common; @@ -40,14 +42,19 @@ protected void Arrange() _channelMock = new Mock(MockBehavior.Strict); _sequence = new MockSequence(); - _sessionMock.InSequence(_sequence).Setup(p => p.CreateChannelSession()).Returns(_channelMock.Object); - _channelMock.InSequence(_sequence).Setup(p => p.Open()); - _channelMock.InSequence(_sequence).Setup(p => p.SendSubsystemRequest(_subsystemName)).Returns(true); - - _subsystemSession = new SubsystemSessionStub( - _sessionMock.Object, - _subsystemName, - _operationTimeout); + + _ = _sessionMock.InSequence(_sequence) + .Setup(p => p.CreateChannelSession()) + .Returns(_channelMock.Object); + _ = _channelMock.InSequence(_sequence) + .Setup(p => p.Open()); + _ = _channelMock.InSequence(_sequence) + .Setup(p => p.SendSubsystemRequest(_subsystemName)) + .Returns(true); + + _subsystemSession = new SubsystemSessionStub(_sessionMock.Object, + _subsystemName, + _operationTimeout); _subsystemSession.Disconnected += (sender, args) => _disconnectedRegister.Add(args); _subsystemSession.ErrorOccurred += (sender, args) => _errorOccurredRegister.Add(args); _subsystemSession.Connect(); @@ -73,7 +80,9 @@ public void ErrorOccurredHasNeverFired() [TestMethod] public void IsOpenShouldReturnTrueWhenChannelIsOpen() { - _channelMock.InSequence(_sequence).Setup(p => p.IsOpen).Returns(true); + _ = _channelMock.InSequence(_sequence) + .Setup(p => p.IsOpen) + .Returns(true); Assert.IsTrue(_subsystemSession.IsOpen); @@ -83,7 +92,9 @@ public void IsOpenShouldReturnTrueWhenChannelIsOpen() [TestMethod] public void IsOpenShouldReturnFalseWhenChannelIsNotOpen() { - _channelMock.InSequence(_sequence).Setup(p => p.IsOpen).Returns(false); + _ = _channelMock.InSequence(_sequence) + .Setup(p => p.IsOpen) + .Returns(false); Assert.IsFalse(_subsystemSession.IsOpen); diff --git a/src/Renci.SshNet.Tests/Classes/SubsystemSession_OnSessionDisconnected_Disposed.cs b/src/Renci.SshNet.Tests/Classes/SubsystemSession_OnSessionDisconnected_Disposed.cs index 7a90eba4c..177bbff33 100644 --- a/src/Renci.SshNet.Tests/Classes/SubsystemSession_OnSessionDisconnected_Disposed.cs +++ b/src/Renci.SshNet.Tests/Classes/SubsystemSession_OnSessionDisconnected_Disposed.cs @@ -1,9 +1,11 @@ using System; using System.Collections.Generic; using System.Globalization; -using System.Text; + using Microsoft.VisualStudio.TestTools.UnitTesting; + using Moq; + using Renci.SshNet.Channels; using Renci.SshNet.Common; @@ -39,15 +41,21 @@ protected void Arrange() _channelMock = new Mock(MockBehavior.Strict); var sequence = new MockSequence(); - _sessionMock.InSequence(sequence).Setup(p => p.CreateChannelSession()).Returns(_channelMock.Object); - _channelMock.InSequence(sequence).Setup(p => p.Open()); - _channelMock.InSequence(sequence).Setup(p => p.SendSubsystemRequest(_subsystemName)).Returns(true); - _channelMock.InSequence(sequence).Setup(p => p.Dispose()); - _subsystemSession = new SubsystemSessionStub( - _sessionMock.Object, - _subsystemName, - _operationTimeout); + _ = _sessionMock.InSequence(sequence) + .Setup(p => p.CreateChannelSession()) + .Returns(_channelMock.Object); + _ = _channelMock.InSequence(sequence) + .Setup(p => p.Open()); + _ = _channelMock.InSequence(sequence) + .Setup(p => p.SendSubsystemRequest(_subsystemName)) + .Returns(true); + _ = _channelMock.InSequence(sequence) + .Setup(p => p.Dispose()); + + _subsystemSession = new SubsystemSessionStub(_sessionMock.Object, + _subsystemName, + _operationTimeout); _subsystemSession.Disconnected += (sender, args) => _disconnectedRegister.Add(args); _subsystemSession.ErrorOccurred += (sender, args) => _errorOccurredRegister.Add(args); _subsystemSession.Connect(); diff --git a/src/Renci.SshNet.Tests/Classes/SubsystemSession_SendData_Disconnected.cs b/src/Renci.SshNet.Tests/Classes/SubsystemSession_SendData_Disconnected.cs index 6d60a61b2..92754621d 100644 --- a/src/Renci.SshNet.Tests/Classes/SubsystemSession_SendData_Disconnected.cs +++ b/src/Renci.SshNet.Tests/Classes/SubsystemSession_SendData_Disconnected.cs @@ -1,9 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace Renci.SshNet.Tests.Classes +namespace Renci.SshNet.Tests.Classes { class SubsystemSession_SendData_Disconnected { diff --git a/src/Renci.SshNet.Tests/Common/ArrayBuilder.cs b/src/Renci.SshNet.Tests/Common/ArrayBuilder.cs index cff2e4c32..9f9f7d659 100644 --- a/src/Renci.SshNet.Tests/Common/ArrayBuilder.cs +++ b/src/Renci.SshNet.Tests/Common/ArrayBuilder.cs @@ -4,7 +4,7 @@ namespace Renci.SshNet.Tests.Common { public class ArrayBuilder { - private List _buffer; + private readonly List _buffer; public ArrayBuilder() { @@ -19,7 +19,10 @@ public ArrayBuilder Add(T[] array) public ArrayBuilder Add(T[] array, int index, int length) { for (var i = 0; i < length; i++) + { _buffer.Add(array[index + i]); + } + return this; } diff --git a/src/Renci.SshNet.Tests/Common/AsyncSocketListener.cs b/src/Renci.SshNet.Tests/Common/AsyncSocketListener.cs index 6815d1609..0f7dac81f 100644 --- a/src/Renci.SshNet.Tests/Common/AsyncSocketListener.cs +++ b/src/Renci.SshNet.Tests/Common/AsyncSocketListener.cs @@ -10,11 +10,11 @@ public class AsyncSocketListener : IDisposable { private readonly IPEndPoint _endPoint; private readonly ManualResetEvent _acceptCallbackDone; - private List _connectedClients; + private readonly List _connectedClients; + private readonly object _syncLock; private Socket _listener; private Thread _receiveThread; private bool _started; - private object _syncLock; private string _stackTrace; public delegate void BytesReceivedHandler(byte[] bytesReceived, Socket socket); @@ -84,10 +84,7 @@ public void Stop() _connectedClients.Clear(); } - if (_listener != null) - { - _listener.Dispose(); - } + _listener?.Dispose(); if (_receiveThread != null) { @@ -109,9 +106,9 @@ private void StartListener(object state) var listener = (Socket)state; while (_started) { - _acceptCallbackDone.Reset(); - listener.BeginAccept(AcceptCallback, listener); - _acceptCallbackDone.WaitOne(); + _ = _acceptCallbackDone.Reset(); + _ = listener.BeginAccept(AcceptCallback, listener); + _ = _acceptCallbackDone.WaitOne(); } } catch (Exception ex) @@ -128,7 +125,7 @@ private void StartListener(object state) private void AcceptCallback(IAsyncResult ar) { // Signal the main thread to continue - _acceptCallbackDone.Set(); + _ = _acceptCallbackDone.Set(); // Get the socket that listens for inbound connections var listener = (Socket)ar.AsyncState; @@ -188,7 +185,7 @@ private void AcceptCallback(IAsyncResult ar) try { - handler.BeginReceive(state.Buffer, 0, state.Buffer.Length, 0, ReadCallback, state); + _ =handler.BeginReceive(state.Buffer, 0, state.Buffer.Length, 0, ReadCallback, state); } catch (SocketException ex) { @@ -308,7 +305,7 @@ void ConnectionDisconnected() throw new Exception("Exception in ReadCallback: " + _stackTrace, ex); } - _connectedClients.Remove(handler); + _ = _connectedClients.Remove(handler); } } } @@ -321,7 +318,7 @@ void ConnectionDisconnected() try { - handler.BeginReceive(state.Buffer, 0, state.Buffer.Length, 0, ReadCallback, state); + _ = handler.BeginReceive(state.Buffer, 0, state.Buffer.Length, 0, ReadCallback, state); } catch (ObjectDisposedException) { @@ -347,23 +344,17 @@ void ConnectionDisconnected() private void SignalBytesReceived(byte[] bytesReceived, Socket client) { - var subscribers = BytesReceived; - if (subscribers != null) - subscribers(bytesReceived, client); + BytesReceived?.Invoke(bytesReceived, client); } private void SignalConnected(Socket client) { - var subscribers = Connected; - if (subscribers != null) - subscribers(client); + Connected?.Invoke(client); } private void SignalDisconnected(Socket client) { - var subscribers = Disconnected; - if (subscribers != null) - subscribers(client); + Disconnected?.Invoke(client); } private static void DrainSocket(Socket socket) diff --git a/src/Renci.SshNet.Tests/Common/DictionaryAssert.cs b/src/Renci.SshNet.Tests/Common/DictionaryAssert.cs index 0df1c5049..ec45fb61a 100644 --- a/src/Renci.SshNet.Tests/Common/DictionaryAssert.cs +++ b/src/Renci.SshNet.Tests/Common/DictionaryAssert.cs @@ -8,22 +8,29 @@ public static class DictionaryAssert public static void AreEqual(IDictionary expected, IDictionary actual) { if (ReferenceEquals(expected, actual)) + { return; + } if (expected == null) + { throw new AssertFailedException("Expected dictionary to be null, but was not null."); + } if (actual == null) + { throw new AssertFailedException("Expected dictionary not to be null, but was null."); + } if (expected.Count != actual.Count) + { throw new AssertFailedException(string.Format("Expected dictionary to contain {0} entries, but was {1}.", expected.Count, actual.Count)); + } foreach (var expectedEntry in expected) { - TValue actualValue; - if (!actual.TryGetValue(expectedEntry.Key, out actualValue)) + if (!actual.TryGetValue(expectedEntry.Key, out var actualValue)) { throw new AssertFailedException(string.Format("Dictionary contains no entry with key '{0}'.", expectedEntry.Key)); } diff --git a/src/Renci.SshNet.Tests/Common/Extensions.cs b/src/Renci.SshNet.Tests/Common/Extensions.cs index 4e88a7900..2c2e04bef 100644 --- a/src/Renci.SshNet.Tests/Common/Extensions.cs +++ b/src/Renci.SshNet.Tests/Common/Extensions.cs @@ -10,11 +10,15 @@ internal static class Extensions public static string AsString(this IList exceptionEvents) { if (exceptionEvents.Count == 0) + { return string.Empty; + } - string reportedExceptions = string.Empty; + var reportedExceptions = string.Empty; foreach (var exceptionEvent in exceptionEvents) + { reportedExceptions += exceptionEvent.Exception.ToString(); + } return reportedExceptions; } diff --git a/src/Renci.SshNet.Tests/Common/HttpProxyStub.cs b/src/Renci.SshNet.Tests/Common/HttpProxyStub.cs index d7bdba506..7cc8c4715 100644 --- a/src/Renci.SshNet.Tests/Common/HttpProxyStub.cs +++ b/src/Renci.SshNet.Tests/Common/HttpProxyStub.cs @@ -24,7 +24,10 @@ public HttpRequest HttpRequest get { if (_httpRequestParser == null) + { throw new InvalidOperationException("The proxy is not started."); + } + return _httpRequestParser.HttpRequest; } } @@ -45,8 +48,7 @@ public void Start() public void Stop() { - if (_listener != null) - _listener.Stop(); + _listener?.Stop(); } public void Dispose() @@ -62,7 +64,10 @@ private void OnBytesReceived(byte[] bytesReceived, Socket socket) if (_httpRequestParser.CurrentState == HttpRequestParser.State.Content) { foreach (var response in Responses) - socket.Send(response); + { + _ = socket.Send(response); + } + socket.Shutdown(SocketShutdown.Send); } } @@ -150,11 +155,16 @@ private string ReadLine(byte[] data, ref int position) { var buffer = _buffer.ToArray(); var bytesInLine = buffer.Length; + // when the previous byte was a CR, then do not include it in line if (buffer.Length > 0 && buffer[buffer.Length - 1] == '\r') + { bytesInLine -= 1; + } + // clear the buffer _buffer.Clear(); + // move position up one position as we've processed the current byte position++; return Encoding.ASCII.GetString(buffer, 0, bytesInLine); @@ -166,4 +176,4 @@ private string ReadLine(byte[] data, ref int position) } } } -} \ No newline at end of file +} diff --git a/src/Renci.SshNet.Tests/Common/SftpFileAttributesBuilder.cs b/src/Renci.SshNet.Tests/Common/SftpFileAttributesBuilder.cs index 2cf1b11a8..92521316e 100644 --- a/src/Renci.SshNet.Tests/Common/SftpFileAttributesBuilder.cs +++ b/src/Renci.SshNet.Tests/Common/SftpFileAttributesBuilder.cs @@ -64,23 +64,27 @@ public SftpFileAttributesBuilder WithExtension(string name, string value) public SftpFileAttributes Build() { if (_lastAccessTime == null) + { _lastAccessTime = DateTime.SpecifyKind(DateTime.MinValue, DateTimeKind.Utc); + } else if (_lastAccessTime.Value.Kind != DateTimeKind.Utc) + { _lastAccessTime = _lastAccessTime.Value.ToUniversalTime(); + } if (_lastWriteTime == null) + { _lastWriteTime = DateTime.SpecifyKind(DateTime.MinValue, DateTimeKind.Utc); + } else if (_lastWriteTime.Value.Kind != DateTimeKind.Utc) + { _lastWriteTime = _lastWriteTime.Value.ToUniversalTime(); + } - if (_size == null) - _size = 0; - if (_userId == null) - _userId = 0; - if (_groupId == null) - _groupId = 0; - if (_permissions == null) - _permissions = 0; + _size ??= 0; + _userId ??= 0; + _groupId ??= 0; + _permissions ??= 0; return new SftpFileAttributes(_lastAccessTime.Value, _lastWriteTime.Value, diff --git a/src/Renci.SshNet.Tests/Renci.SshNet.Tests.csproj b/src/Renci.SshNet.Tests/Renci.SshNet.Tests.csproj index 89a270445..f4c0b6f33 100644 --- a/src/Renci.SshNet.Tests/Renci.SshNet.Tests.csproj +++ b/src/Renci.SshNet.Tests/Renci.SshNet.Tests.csproj @@ -13,10 +13,6 @@ $(NoWarn);CS1591 - - FEATURE_TPL - - diff --git a/src/Renci.SshNet/.editorconfig b/src/Renci.SshNet/.editorconfig index 7c507c75c..c0430021e 100644 --- a/src/Renci.SshNet/.editorconfig +++ b/src/Renci.SshNet/.editorconfig @@ -1,5 +1,12 @@ [*.cs] +#### SYSLIB diagnostics #### + +# SYSLIB1045: Use 'GeneratedRegexAttribute' to generate the regular expression implementation at compile-time +# +# TODO: Remove this when https://github.com/sshnet/SSH.NET/issues/1131 is implemented. +dotnet_diagnostic.SYSLIB1045.severity = none + ### StyleCop Analyzers rules ### # SA1202: Elements must be ordered by access diff --git a/src/Renci.SshNet/Abstractions/SocketAbstraction.cs b/src/Renci.SshNet/Abstractions/SocketAbstraction.cs index 3c6fb90a3..5784879fa 100644 --- a/src/Renci.SshNet/Abstractions/SocketAbstraction.cs +++ b/src/Renci.SshNet/Abstractions/SocketAbstraction.cs @@ -186,6 +186,7 @@ public static void ReadContinuous(Socket socket, byte[] buffer, int offset, int continue; } +#pragma warning disable IDE0010 // Add missing cases switch (ex.SocketErrorCode) { case SocketError.ConnectionAborted: @@ -199,6 +200,7 @@ public static void ReadContinuous(Socket socket, byte[] buffer, int offset, int default: throw; // throw any other error } +#pragma warning restore IDE0010 // Add missing cases } } } @@ -369,6 +371,7 @@ public static void Send(Socket socket, byte[] data, int offset, int size) public static bool IsErrorResumable(SocketError socketError) { +#pragma warning disable IDE0010 // Add missing cases switch (socketError) { case SocketError.WouldBlock: @@ -378,6 +381,7 @@ public static bool IsErrorResumable(SocketError socketError) default: return false; } +#pragma warning restore IDE0010 // Add missing cases } #if FEATURE_SOCKET_EAP diff --git a/src/Renci.SshNet/Abstractions/SocketExtensions.cs b/src/Renci.SshNet/Abstractions/SocketExtensions.cs index 84c2f03df..8e6c0133b 100644 --- a/src/Renci.SshNet/Abstractions/SocketExtensions.cs +++ b/src/Renci.SshNet/Abstractions/SocketExtensions.cs @@ -36,7 +36,7 @@ public void SetCompleted() IsCompleted = true; var continuation = _continuationAction ?? Interlocked.CompareExchange(ref _continuationAction, SENTINEL, null); - if (continuation != null) + if (continuation is not null) { continuation(); } diff --git a/src/Renci.SshNet/Abstractions/ThreadAbstraction.cs b/src/Renci.SshNet/Abstractions/ThreadAbstraction.cs index b506a64c8..0c9e3b64f 100644 --- a/src/Renci.SshNet/Abstractions/ThreadAbstraction.cs +++ b/src/Renci.SshNet/Abstractions/ThreadAbstraction.cs @@ -15,7 +15,7 @@ public static void Sleep(int millisecondsTimeout) public static void ExecuteThreadLongRunning(Action action) { - if (action == null) + if (action is null) { throw new ArgumentNullException(nameof(action)); } @@ -30,7 +30,7 @@ public static void ExecuteThreadLongRunning(Action action) /// The action to execute. public static void ExecuteThread(Action action) { - if (action == null) + if (action is null) { throw new ArgumentNullException(nameof(action)); } diff --git a/src/Renci.SshNet/BaseClient.cs b/src/Renci.SshNet/BaseClient.cs index 6596ceedb..ed0db2bba 100644 --- a/src/Renci.SshNet/BaseClient.cs +++ b/src/Renci.SshNet/BaseClient.cs @@ -182,12 +182,12 @@ protected BaseClient(ConnectionInfo connectionInfo, bool ownsConnectionInfo) /// internal BaseClient(ConnectionInfo connectionInfo, bool ownsConnectionInfo, IServiceFactory serviceFactory) { - if (connectionInfo == null) + if (connectionInfo is null) { throw new ArgumentNullException(nameof(connectionInfo)); } - if (serviceFactory == null) + if (serviceFactory is null) { throw new ArgumentNullException(nameof(serviceFactory)); } @@ -453,7 +453,7 @@ protected void CheckDisposed() /// private void StopKeepAliveTimer() { - if (_keepAliveTimer == null) + if (_keepAliveTimer is null) { return; } @@ -467,7 +467,7 @@ private void SendKeepAliveMessage() var session = Session; // do nothing if we have disposed or disconnected - if (session == null) + if (session is null) { return; } diff --git a/src/Renci.SshNet/Channels/ChannelDirectTcpip.cs b/src/Renci.SshNet/Channels/ChannelDirectTcpip.cs index 374272b29..11eea894c 100644 --- a/src/Renci.SshNet/Channels/ChannelDirectTcpip.cs +++ b/src/Renci.SshNet/Channels/ChannelDirectTcpip.cs @@ -113,14 +113,14 @@ public void Bind() /// private void CloseSocket() { - if (_socket == null) + if (_socket is null) { return; } lock (_socketLock) { - if (_socket == null) + if (_socket is null) { return; } @@ -138,7 +138,7 @@ private void CloseSocket() /// One of the values that specifies the operation that will no longer be allowed. private void ShutdownSocket(SocketShutdown how) { - if (_socket == null) + if (_socket is null) { return; } diff --git a/src/Renci.SshNet/Channels/ChannelForwardedTcpip.cs b/src/Renci.SshNet/Channels/ChannelForwardedTcpip.cs index 321a00d02..465c8f181 100644 --- a/src/Renci.SshNet/Channels/ChannelForwardedTcpip.cs +++ b/src/Renci.SshNet/Channels/ChannelForwardedTcpip.cs @@ -119,7 +119,7 @@ private void ForwardedPort_Closing(object sender, EventArgs eventArgs) /// One of the values that specifies the operation that will no longer be allowed. private void ShutdownSocket(SocketShutdown how) { - if (_socket == null) + if (_socket is null) { return; } @@ -149,7 +149,7 @@ private void ShutdownSocket(SocketShutdown how) /// private void CloseSocket() { - if (_socket == null) + if (_socket is null) { return; } diff --git a/src/Renci.SshNet/Channels/ClientChannel.cs b/src/Renci.SshNet/Channels/ClientChannel.cs index 1ec03c6bc..f1b332afb 100644 --- a/src/Renci.SshNet/Channels/ClientChannel.cs +++ b/src/Renci.SshNet/Channels/ClientChannel.cs @@ -117,7 +117,7 @@ protected override void Dispose(bool disposing) /// private void UnsubscribeFromSessionEvents(ISession session) { - if (session == null) + if (session is null) { return; } diff --git a/src/Renci.SshNet/ClientAuthentication.cs b/src/Renci.SshNet/ClientAuthentication.cs index a8a6745e2..6d91455af 100644 --- a/src/Renci.SshNet/ClientAuthentication.cs +++ b/src/Renci.SshNet/ClientAuthentication.cs @@ -44,12 +44,12 @@ internal int PartialSuccessLimit /// The for which to perform authentication. public void Authenticate(IConnectionInfoInternal connectionInfo, ISession session) { - if (connectionInfo == null) + if (connectionInfo is null) { throw new ArgumentNullException(nameof(connectionInfo)); } - if (session == null) + if (session is null) { throw new ArgumentNullException(nameof(session)); } @@ -138,6 +138,8 @@ private bool TryAuthenticate(ISession session, case AuthenticationResult.Success: authenticationException = null; break; + default: + break; } if (authenticationResult == AuthenticationResult.Success) diff --git a/src/Renci.SshNet/Common/AsyncResult.cs b/src/Renci.SshNet/Common/AsyncResult.cs index ec103552e..acc1da119 100644 --- a/src/Renci.SshNet/Common/AsyncResult.cs +++ b/src/Renci.SshNet/Common/AsyncResult.cs @@ -121,7 +121,7 @@ public WaitHandle AsyncWaitHandle { get { - if (_asyncWaitHandle == null) + if (_asyncWaitHandle is null) { var done = IsCompleted; var mre = new ManualResetEvent(done); diff --git a/src/Renci.SshNet/Common/BigInteger.cs b/src/Renci.SshNet/Common/BigInteger.cs index 8e8f7b514..47c0aa4a4 100644 --- a/src/Renci.SshNet/Common/BigInteger.cs +++ b/src/Renci.SshNet/Common/BigInteger.cs @@ -288,13 +288,15 @@ public BigInteger(ulong value) else { _sign = 1; - var low = (uint)value; - var high = (uint)(value >> 32); + var low = (uint) value; + var high = (uint) (value >> 32); _data = new uint[high != 0 ? 2 : 1]; _data[0] = low; if (high != 0) + { _data[1] = high; + } } } @@ -377,7 +379,10 @@ public BigInteger(decimal value) var bits = decimal.GetBits(decimal.Truncate(value)); var size = 3; - while (size > 0 && bits[size - 1] == 0) size--; + while (size > 0 && bits[size - 1] == 0) + { + size--; + } if (size == 0) { @@ -409,7 +414,7 @@ public BigInteger(decimal value) [CLSCompliant(false)] public BigInteger(byte[] value) { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -765,7 +770,7 @@ public static BigInteger Zero /// public static explicit operator int(BigInteger value) { - if (value._data == null) + if (value._data is null) { return 0; } @@ -810,7 +815,7 @@ public static explicit operator int(BigInteger value) [CLSCompliant(false)] public static explicit operator uint(BigInteger value) { - if (value._data == null) + if (value._data is null) { return 0; } @@ -906,7 +911,7 @@ public static explicit operator sbyte(BigInteger value) /// public static explicit operator long(BigInteger value) { - if (value._data == null) + if (value._data is null) { return 0; } @@ -970,7 +975,7 @@ long.MinValue works fine since it's bigint encoding looks like a negative [CLSCompliant(false)] public static explicit operator ulong(BigInteger value) { - if (value._data == null) + if (value._data is null) { return 0; } @@ -999,7 +1004,7 @@ public static explicit operator ulong(BigInteger value) /// public static explicit operator double(BigInteger value) { - if (value._data == null) + if (value._data is null) { return 0.0; } @@ -1050,7 +1055,7 @@ public static explicit operator float(BigInteger value) /// public static explicit operator decimal(BigInteger value) { - if (value._data == null) + if (value._data is null) { return decimal.Zero; } @@ -1360,7 +1365,10 @@ public static explicit operator BigInteger(decimal value) } int m; - for (m = res.Length - 1; m >= 0 && res[m] == 0; --m) ; + for (m = res.Length - 1; m >= 0 && res[m] == 0; --m) + { + // Intentionally empty block + } if (m < res.Length - 1) { @@ -1394,7 +1402,10 @@ public static explicit operator BigInteger(decimal value) DivModUnsigned(dividend._data, divisor._data, out var quotient, out _); int i; - for (i = quotient.Length - 1; i >= 0 && quotient[i] == 0; --i) ; + for (i = quotient.Length - 1; i >= 0 && quotient[i] == 0; --i) + { + // Intentionally empty block + } if (i == -1) { @@ -1432,7 +1443,10 @@ public static explicit operator BigInteger(decimal value) DivModUnsigned(dividend._data, divisor._data, out _, out var remainderValue); int i; - for (i = remainderValue.Length - 1; i >= 0 && remainderValue[i] == 0; --i) ; + for (i = remainderValue.Length - 1; i >= 0 && remainderValue[i] == 0; --i) + { + // Intentionally empty block + } if (i == -1) { @@ -1456,7 +1470,7 @@ public static explicit operator BigInteger(decimal value) /// public static BigInteger operator -(BigInteger value) { - if (value._data == null) + if (value._data is null) { return value; } @@ -1488,7 +1502,7 @@ public static explicit operator BigInteger(decimal value) /// public static BigInteger operator ++(BigInteger value) { - if (value._data == null) + if (value._data is null) { return One; } @@ -1522,7 +1536,7 @@ public static explicit operator BigInteger(decimal value) /// public static BigInteger operator --(BigInteger value) { - if (value._data == null) + if (value._data is null) { return MinusOne; } @@ -1619,7 +1633,10 @@ public static explicit operator BigInteger(decimal value) result[i] = word; } - for (i = result.Length - 1; i >= 0 && result[i] == 0; --i) ; + for (i = result.Length - 1; i >= 0 && result[i] == 0; --i) + { + // Intentionally empty block + } if (i == -1) { @@ -1706,7 +1723,10 @@ public static explicit operator BigInteger(decimal value) result[i] = word; } - for (i = result.Length - 1; i >= 0 && result[i] == 0; --i) ; + for (i = result.Length - 1; i >= 0 && result[i] == 0; --i) + { + // Intentionally empty block + } if (i == -1) { @@ -1793,7 +1813,10 @@ public static explicit operator BigInteger(decimal value) result[i] = word; } - for (i = result.Length - 1; i >= 0 && result[i] == 0; --i) ; + for (i = result.Length - 1; i >= 0 && result[i] == 0; --i) + { + // Intentionally empty block + } if (i == -1) { @@ -1817,7 +1840,7 @@ public static explicit operator BigInteger(decimal value) /// public static BigInteger operator ~(BigInteger value) { - if (value._data == null) + if (value._data is null) { return MinusOne; } @@ -1854,7 +1877,10 @@ public static explicit operator BigInteger(decimal value) result[i] = word; } - for (i = result.Length - 1; i >= 0 && result[i] == 0; --i) ; + for (i = result.Length - 1; i >= 0 && result[i] == 0; --i) + { + // Intentionally empty block + } if (i == -1) { @@ -1895,7 +1921,7 @@ static int BitScanBackward(uint word) /// public static BigInteger operator <<(BigInteger value, int shift) { - if (shift == 0 || value._data == null) + if (shift == 0 || value._data is null) { return value; } @@ -2876,7 +2902,7 @@ private static bool Parse(string value, NumberStyles style, IFormatProvider fp, result = Zero; exc = null; - if (value == null) + if (value is null) { if (!tryParse) { @@ -3420,7 +3446,7 @@ private static bool Parse(string value, bool tryParse, out BigInteger result, ou result = Zero; exc = null; - if (value == null) + if (value is null) { if (!tryParse) { @@ -3630,7 +3656,10 @@ public static BigInteger DivRem(BigInteger dividend, BigInteger divisor, out Big DivModUnsigned(dividend._data, divisor._data, out var quotient, out var remainderValue); int i; - for (i = remainderValue.Length - 1; i >= 0 && remainderValue[i] == 0; --i) ; + for (i = remainderValue.Length - 1; i >= 0 && remainderValue[i] == 0; --i) + { + // Intentionally empty block + } if (i == -1) { @@ -3646,7 +3675,10 @@ public static BigInteger DivRem(BigInteger dividend, BigInteger divisor, out Big remainder = new BigInteger(dividend._sign, remainderValue); } - for (i = quotient.Length - 1; i >= 0 && quotient[i] == 0; --i) ; + for (i = quotient.Length - 1; i >= 0 && quotient[i] == 0; --i) + { + // Intentionally empty block + } if (i == -1) { @@ -3870,7 +3902,7 @@ public static double Log(BigInteger value, double baseValue) return value.IsOne ? 0 : double.NaN; } - if (value._data == null) + if (value._data is null) { return double.NegativeInfinity; } @@ -4079,7 +4111,7 @@ public static BigInteger Negate(BigInteger value) /// is not a . public readonly int CompareTo(object obj) { - if (obj == null) + if (obj is null) { return 1; } @@ -4539,7 +4571,11 @@ private static uint[] CoreSub(uint[] a, uint[] b) } // remove extra zeroes - for (i = bl - 1; i >= 0 && res[i] == 0; --i) ; + for (i = bl - 1; i >= 0 && res[i] == 0; --i) + { + // Intentionally empty block + } + if (i < bl - 1) { Array.Resize(ref res, i + 1); @@ -4586,7 +4622,11 @@ private static uint[] CoreSub(uint[] a, uint b) } // Remove extra zeroes - for (i = len - 1; i >= 0 && res[i] == 0; --i) ; + for (i = len - 1; i >= 0 && res[i] == 0; --i) + { + // Intentionally empty block + } + if (i < len - 1) { Array.Resize(ref res, i + 1); @@ -4658,7 +4698,9 @@ private static int GetNormalizeShift(uint value) if ((value & 0x80000000) == 0) { +#pragma warning disable IDE0059 // Unnecessary assignment of a value value <<= 1; +#pragma warning restore IDE0059 // Unnecessary assignment of a value shift += 1; } @@ -4746,7 +4788,7 @@ private static void DivModUnsigned(uint[] u, uint[] v, out uint[] q, out uint[] q[j] = (uint)div; } - r[0] = (uint)rem; + r[0] = (uint) rem; } else if (m >= n) { @@ -4759,7 +4801,6 @@ private static void DivModUnsigned(uint[] u, uint[] v, out uint[] q, out uint[] Normalize(v, n, vn, shift); q = new uint[m - n + 1]; - r = null; // Main division loop for (var j = m - n; j >= 0; j--) @@ -4789,7 +4830,7 @@ private static void DivModUnsigned(uint[] u, uint[] v, out uint[] q, out uint[] // Multiply and subtract long b = 0; - long t = 0; + long t; for (i = 0; i < n; i++) { var p = vn[i] * qq; diff --git a/src/Renci.SshNet/Common/Extensions.cs b/src/Renci.SshNet/Common/Extensions.cs index 1e6bb6def..8fed310c1 100644 --- a/src/Renci.SshNet/Common/Extensions.cs +++ b/src/Renci.SshNet/Common/Extensions.cs @@ -126,7 +126,7 @@ internal static void DebugPrint(this IEnumerable bytes) internal static T CreateInstance(this Type type) where T : class { - if (type == null) + if (type is null) { return null; } @@ -173,7 +173,7 @@ internal static void ValidatePort(this int value, string argument) /// public static byte[] Take(this byte[] value, int offset, int count) { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -208,7 +208,7 @@ public static byte[] Take(this byte[] value, int offset, int count) /// public static byte[] Take(this byte[] value, int count) { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -230,12 +230,12 @@ public static byte[] Take(this byte[] value, int count) public static bool IsEqualTo(this byte[] left, byte[] right) { - if (left == null) + if (left is null) { throw new ArgumentNullException(nameof(left)); } - if (right == null) + if (right is null) { throw new ArgumentNullException(nameof(right)); } @@ -270,7 +270,7 @@ public static bool IsEqualTo(this byte[] left, byte[] right) /// public static byte[] TrimLeadingZeros(this byte[] value) { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -317,12 +317,12 @@ public static byte[] Pad(this byte[] data, int length) public static byte[] Concat(this byte[] first, byte[] second) { - if (first == null || first.Length == 0) + if (first is null || first.Length == 0) { return second; } - if (second == null || second.Length == 0) + if (second is null || second.Length == 0) { return first; } @@ -345,7 +345,7 @@ internal static bool CanWrite(this Socket socket) internal static bool IsConnected(this Socket socket) { - if (socket == null) + if (socket is null) { return false; } diff --git a/src/Renci.SshNet/Common/ObjectIdentifier.cs b/src/Renci.SshNet/Common/ObjectIdentifier.cs index ab491cce6..f1b2d88df 100644 --- a/src/Renci.SshNet/Common/ObjectIdentifier.cs +++ b/src/Renci.SshNet/Common/ObjectIdentifier.cs @@ -20,7 +20,7 @@ public struct ObjectIdentifier /// has less than two elements. public ObjectIdentifier(params ulong[] identifiers) { - if (identifiers == null) + if (identifiers is null) { throw new ArgumentNullException(nameof(identifiers)); } diff --git a/src/Renci.SshNet/Common/PacketDump.cs b/src/Renci.SshNet/Common/PacketDump.cs index c9357a3af..47329f6d0 100644 --- a/src/Renci.SshNet/Common/PacketDump.cs +++ b/src/Renci.SshNet/Common/PacketDump.cs @@ -14,7 +14,7 @@ public static string Create(List data, int indentLevel) public static string Create(byte[] data, int indentLevel) { - if (data == null) + if (data is null) { throw new ArgumentNullException(nameof(data)); } diff --git a/src/Renci.SshNet/Common/PipeStream.cs b/src/Renci.SshNet/Common/PipeStream.cs index 71a82e1d8..d2fe8d369 100644 --- a/src/Renci.SshNet/Common/PipeStream.cs +++ b/src/Renci.SshNet/Common/PipeStream.cs @@ -185,7 +185,7 @@ public override int Read(byte[] buffer, int offset, int count) throw new NotSupportedException("Offsets with value of non-zero are not supported"); } - if (buffer == null) + if (buffer is null) { throw new ArgumentNullException(nameof(buffer)); } @@ -269,7 +269,7 @@ private bool ReadAvailable(int count) /// offset or count is negative. public override void Write(byte[] buffer, int offset, int count) { - if (buffer == null) + if (buffer is null) { throw new ArgumentNullException(nameof(buffer)); } diff --git a/src/Renci.SshNet/Common/PortForwardEventArgs.cs b/src/Renci.SshNet/Common/PortForwardEventArgs.cs index 4d1f1656d..a94748b6f 100644 --- a/src/Renci.SshNet/Common/PortForwardEventArgs.cs +++ b/src/Renci.SshNet/Common/PortForwardEventArgs.cs @@ -17,7 +17,7 @@ public class PortForwardEventArgs : EventArgs /// is not within and . internal PortForwardEventArgs(string host, uint port) { - if (host == null) + if (host is null) { throw new ArgumentNullException(nameof(host)); } diff --git a/src/Renci.SshNet/Common/PosixPath.cs b/src/Renci.SshNet/Common/PosixPath.cs index 2d028bd67..0dae95ea1 100644 --- a/src/Renci.SshNet/Common/PosixPath.cs +++ b/src/Renci.SshNet/Common/PosixPath.cs @@ -38,7 +38,7 @@ private PosixPath() /// is empty (""). public static PosixPath CreateAbsoluteOrRelativeFilePath(string path) { - if (path == null) + if (path is null) { throw new ArgumentNullException(nameof(path)); } @@ -95,7 +95,7 @@ public static PosixPath CreateAbsoluteOrRelativeFilePath(string path) /// public static string GetFileName(string path) { - if (path == null) + if (path is null) { throw new ArgumentNullException(nameof(path)); } @@ -125,7 +125,7 @@ public static string GetFileName(string path) /// is null. public static string GetDirectoryName(string path) { - if (path == null) + if (path is null) { throw new ArgumentNullException(nameof(path)); } diff --git a/src/Renci.SshNet/Common/SemaphoreLight.cs b/src/Renci.SshNet/Common/SemaphoreLight.cs index f3210c788..8ee4167d1 100644 --- a/src/Renci.SshNet/Common/SemaphoreLight.cs +++ b/src/Renci.SshNet/Common/SemaphoreLight.cs @@ -52,7 +52,7 @@ public WaitHandle AvailableWaitHandle { get { - if (_waitHandle == null) + if (_waitHandle is null) { lock (_lock) { diff --git a/src/Renci.SshNet/Common/SshData.cs b/src/Renci.SshNet/Common/SshData.cs index 0a10eee64..67823ec2d 100644 --- a/src/Renci.SshNet/Common/SshData.cs +++ b/src/Renci.SshNet/Common/SshData.cs @@ -85,7 +85,7 @@ protected virtual void WriteBytes(SshDataStream stream) /// is null. public void Load(byte[] data) { - if (data == null) + if (data is null) { throw new ArgumentNullException(nameof(data)); } @@ -102,7 +102,7 @@ public void Load(byte[] data) /// is null. public void Load(byte[] data, int offset, int count) { - if (data == null) + if (data is null) { throw new ArgumentNullException(nameof(data)); } diff --git a/src/Renci.SshNet/Common/SshDataStream.cs b/src/Renci.SshNet/Common/SshDataStream.cs index 54a5505f5..1eedd3ffc 100644 --- a/src/Renci.SshNet/Common/SshDataStream.cs +++ b/src/Renci.SshNet/Common/SshDataStream.cs @@ -93,7 +93,7 @@ public void Write(BigInteger data) /// is null. public void Write(byte[] data) { - if (data == null) + if (data is null) { throw new ArgumentNullException(nameof(data)); } @@ -126,7 +126,7 @@ public byte[] ReadBinary() /// is null. public void WriteBinary(byte[] buffer) { - if (buffer == null) + if (buffer is null) { throw new ArgumentNullException(nameof(buffer)); } @@ -158,7 +158,7 @@ public void WriteBinary(byte[] buffer, int offset, int count) /// is null. public void Write(string s, Encoding encoding) { - if (encoding == null) + if (encoding is null) { throw new ArgumentNullException(nameof(encoding)); } diff --git a/src/Renci.SshNet/Compression/ZlibStream.cs b/src/Renci.SshNet/Compression/ZlibStream.cs index e12996943..5c9d3b841 100644 --- a/src/Renci.SshNet/Compression/ZlibStream.cs +++ b/src/Renci.SshNet/Compression/ZlibStream.cs @@ -14,7 +14,9 @@ public class ZlibStream /// /// The stream. /// The mode. +#pragma warning disable IDE0060 // Remove unused parameter public ZlibStream(Stream stream, CompressionMode mode) +#pragma warning restore IDE0060 // Remove unused parameter { //switch (mode) //{ @@ -37,7 +39,9 @@ public ZlibStream(Stream stream, CompressionMode mode) /// The buffer. /// The offset. /// The count. +#pragma warning disable IDE0060 // Remove unused parameter public void Write(byte[] buffer, int offset, int count) +#pragma warning restore IDE0060 // Remove unused parameter { //this._baseStream.Write(buffer, offset, count); } diff --git a/src/Renci.SshNet/Connection/ConnectorBase.cs b/src/Renci.SshNet/Connection/ConnectorBase.cs index 1725657f5..bdea64a6f 100644 --- a/src/Renci.SshNet/Connection/ConnectorBase.cs +++ b/src/Renci.SshNet/Connection/ConnectorBase.cs @@ -14,7 +14,7 @@ internal abstract class ConnectorBase : IConnector { protected ConnectorBase(ISocketFactory socketFactory) { - if (socketFactory == null) + if (socketFactory is null) { throw new ArgumentNullException(nameof(socketFactory)); } diff --git a/src/Renci.SshNet/Connection/HttpConnector.cs b/src/Renci.SshNet/Connection/HttpConnector.cs index 01fa6fa10..832bb3dd3 100644 --- a/src/Renci.SshNet/Connection/HttpConnector.cs +++ b/src/Renci.SshNet/Connection/HttpConnector.cs @@ -63,13 +63,13 @@ protected override void HandleProxyConnect(IConnectionInfo connectionInfo, Socke while (true) { var response = SocketReadLine(socket, connectionInfo.Timeout); - if (response == null) + if (response is null) { // server shut down socket break; } - if (statusCode == null) + if (statusCode is null) { var statusMatch = httpResponseRe.Match(response); if (statusMatch.Success) @@ -112,7 +112,7 @@ protected override void HandleProxyConnect(IConnectionInfo connectionInfo, Socke } } - if (statusCode == null) + if (statusCode is null) { throw new ProxyException("HTTP response does not contain status line."); } diff --git a/src/Renci.SshNet/Connection/ProtocolVersionExchange.cs b/src/Renci.SshNet/Connection/ProtocolVersionExchange.cs index 044f58715..8f3beb51f 100644 --- a/src/Renci.SshNet/Connection/ProtocolVersionExchange.cs +++ b/src/Renci.SshNet/Connection/ProtocolVersionExchange.cs @@ -47,7 +47,7 @@ public SshIdentification Start(string clientVersion, Socket socket, TimeSpan tim while (true) { var line = SocketReadLine(socket, timeout, bytesReceived); - if (line == null) + if (line is null) { if (bytesReceived.Count == 0) { @@ -80,7 +80,7 @@ public async Task StartAsync(string clientVersion, Socket soc while (true) { var line = await SocketReadLineAsync(socket, bytesReceived, cancellationToken).ConfigureAwait(false); - if (line == null) + if (line is null) { if (bytesReceived.Count == 0) { @@ -143,7 +143,7 @@ private static string SocketReadLine(Socket socket, TimeSpan timeout, List buffer.Add(byteRead); // The null character MUST NOT be sent - if (byteRead == Null) + if (byteRead is Null) { throw CreateServerResponseContainsNullCharacterException(buffer); } @@ -187,7 +187,7 @@ private static async Task SocketReadLineAsync(Socket socket, List buffer.Add(byteRead); // The null character MUST NOT be sent - if (byteRead == Null) + if (byteRead is Null) { throw CreateServerResponseContainsNullCharacterException(buffer); } diff --git a/src/Renci.SshNet/Connection/Socks5Connector.cs b/src/Renci.SshNet/Connection/Socks5Connector.cs index 9cfc4758f..ef9f9974c 100644 --- a/src/Renci.SshNet/Connection/Socks5Connector.cs +++ b/src/Renci.SshNet/Connection/Socks5Connector.cs @@ -49,6 +49,7 @@ protected override void HandleProxyConnect(IConnectionInfo connectionInfo, Socke switch (authenticationMethod) { case 0x00: + // No authentication break; case 0x02: // Create username/password authentication request @@ -73,6 +74,8 @@ protected override void HandleProxyConnect(IConnectionInfo connectionInfo, Socke break; case 0xFF: throw new ProxyException("SOCKS5: No acceptable authentication methods were offered."); + default: + throw new ProxyException($"SOCKS5: Chosen authentication method '0x{authenticationMethod:x2}' is not supported."); } var connectionRequest = CreateSocks5ConnectionRequest(connectionInfo.Host, (ushort) connectionInfo.Port); @@ -238,6 +241,7 @@ private static byte[] GetSocks5DestinationAddress(string hostname, out byte addr byte[] address; +#pragma warning disable IDE0010 // Add missing cases switch (ip.AddressFamily) { case AddressFamily.InterNetwork: @@ -251,6 +255,7 @@ private static byte[] GetSocks5DestinationAddress(string hostname, out byte addr default: throw new ProxyException(string.Format("SOCKS5: IP address '{0}' is not supported.", ip)); } +#pragma warning restore IDE0010 // Add missing cases return address; } diff --git a/src/Renci.SshNet/Connection/SshIdentification.cs b/src/Renci.SshNet/Connection/SshIdentification.cs index 9484ea0c8..a950ad71f 100644 --- a/src/Renci.SshNet/Connection/SshIdentification.cs +++ b/src/Renci.SshNet/Connection/SshIdentification.cs @@ -31,12 +31,12 @@ public SshIdentification(string protocolVersion, string softwareVersion) /// is . public SshIdentification(string protocolVersion, string softwareVersion, string comments) { - if (protocolVersion == null) + if (protocolVersion is null) { throw new ArgumentNullException(nameof(protocolVersion)); } - if (softwareVersion == null) + if (softwareVersion is null) { throw new ArgumentNullException(nameof(softwareVersion)); } diff --git a/src/Renci.SshNet/ConnectionInfo.cs b/src/Renci.SshNet/ConnectionInfo.cs index b36b4eb15..89abcd63d 100644 --- a/src/Renci.SshNet/ConnectionInfo.cs +++ b/src/Renci.SshNet/ConnectionInfo.cs @@ -297,14 +297,14 @@ public ConnectionInfo(string host, int port, string username, params Authenticat /// No specified. public ConnectionInfo(string host, int port, string username, ProxyTypes proxyType, string proxyHost, int proxyPort, string proxyUsername, string proxyPassword, params AuthenticationMethod[] authenticationMethods) { - if (host == null) + if (host is null) { throw new ArgumentNullException(nameof(host)); } port.ValidatePort("port"); - if (username == null) + if (username is null) { throw new ArgumentNullException(nameof(username)); } @@ -316,7 +316,7 @@ public ConnectionInfo(string host, int port, string username, ProxyTypes proxyTy if (proxyType != ProxyTypes.None) { - if (proxyHost == null) + if (proxyHost is null) { throw new ArgumentNullException(nameof(proxyHost)); } @@ -324,7 +324,7 @@ public ConnectionInfo(string host, int port, string username, ProxyTypes proxyTy proxyPort.ValidatePort("proxyPort"); } - if (authenticationMethods == null) + if (authenticationMethods is null) { throw new ArgumentNullException(nameof(authenticationMethods)); } @@ -445,7 +445,7 @@ public ConnectionInfo(string host, int port, string username, ProxyTypes proxyTy /// No suitable authentication method found to complete authentication, or permission denied. internal void Authenticate(ISession session, IServiceFactory serviceFactory) { - if (serviceFactory == null) + if (serviceFactory is null) { throw new ArgumentNullException(nameof(serviceFactory)); } diff --git a/src/Renci.SshNet/ExpectAction.cs b/src/Renci.SshNet/ExpectAction.cs index 4a52c889d..2274c52a3 100644 --- a/src/Renci.SshNet/ExpectAction.cs +++ b/src/Renci.SshNet/ExpectAction.cs @@ -26,12 +26,12 @@ public class ExpectAction /// or is null. public ExpectAction(Regex expect, Action action) { - if (expect == null) + if (expect is null) { throw new ArgumentNullException(nameof(expect)); } - if (action == null) + if (action is null) { throw new ArgumentNullException(nameof(action)); } @@ -48,12 +48,12 @@ public ExpectAction(Regex expect, Action action) /// or is null. public ExpectAction(string expect, Action action) { - if (expect == null) + if (expect is null) { throw new ArgumentNullException(nameof(expect)); } - if (action == null) + if (action is null) { throw new ArgumentNullException(nameof(action)); } diff --git a/src/Renci.SshNet/ForwardedPort.cs b/src/Renci.SshNet/ForwardedPort.cs index deca52423..f4544094c 100644 --- a/src/Renci.SshNet/ForwardedPort.cs +++ b/src/Renci.SshNet/ForwardedPort.cs @@ -60,7 +60,7 @@ public virtual void Start() throw new InvalidOperationException("Forwarded port is already started."); } - if (Session == null) + if (Session is null) { throw new InvalidOperationException("Forwarded port is not added to a client."); } diff --git a/src/Renci.SshNet/ForwardedPortDynamic.NET.cs b/src/Renci.SshNet/ForwardedPortDynamic.NET.cs index 957483f71..eca6f6427 100644 --- a/src/Renci.SshNet/ForwardedPortDynamic.NET.cs +++ b/src/Renci.SshNet/ForwardedPortDynamic.NET.cs @@ -43,7 +43,7 @@ partial void InternalStart() private void StartAccept(SocketAsyncEventArgs e) { - if (e == null) + if (e is null) { e = new SocketAsyncEventArgs(); e.Completed += AcceptCompleted; @@ -178,9 +178,12 @@ private void InitializePendingChannelCountdown() private bool HandleSocks(IChannelDirectTcpip channel, Socket clientSocket, TimeSpan timeout) { - // create eventhandler which is to be invoked to interrupt a blocking receive - // when we're closing the forwarded port + +#pragma warning disable IDE0039 // Use lambda instead of local function to reduce allocations + // Create eventhandler which is to be invoked to interrupt a blocking receive + // when we're closing the forwarded port. EventHandler closeClientSocket = (_, args) => CloseClientSocket(clientSocket); +#pragma warning restore IDE0039 // Use lambda instead of local function to reduce allocations Closing += closeClientSocket; @@ -351,7 +354,7 @@ private bool HandleSocks4(Socket socket, IChannelDirectTcpip channel, TimeSpan t var ipAddress = new IPAddress(ipBuffer); var username = ReadString(socket, timeout); - if (username == null) + if (username is null) { // SOCKS client closed connection return false; @@ -418,7 +421,9 @@ private bool HandleSocks5(Socket socket, IChannelDirectTcpip channel, TimeSpan t } if (version != 5) + { throw new ProxyException("SOCKS5: Version 5 is expected."); + } var commandCode = SocketAbstraction.ReadByte(socket, timeout); if (commandCode == -1) @@ -447,7 +452,7 @@ private bool HandleSocks5(Socket socket, IChannelDirectTcpip channel, TimeSpan t } var host = GetSocks5Host(addressType, socket, timeout); - if (host == null) + if (host is null) { // SOCKS client closed connection return false; diff --git a/src/Renci.SshNet/ForwardedPortLocal.NET.cs b/src/Renci.SshNet/ForwardedPortLocal.NET.cs index 60777b97a..3bd9e3f52 100644 --- a/src/Renci.SshNet/ForwardedPortLocal.NET.cs +++ b/src/Renci.SshNet/ForwardedPortLocal.NET.cs @@ -38,7 +38,7 @@ partial void InternalStart() private void StartAccept(SocketAsyncEventArgs e) { - if (e == null) + if (e is null) { e = new SocketAsyncEventArgs(); e.Completed += AcceptCompleted; diff --git a/src/Renci.SshNet/ForwardedPortLocal.cs b/src/Renci.SshNet/ForwardedPortLocal.cs index fe3215de2..8dabb09fb 100644 --- a/src/Renci.SshNet/ForwardedPortLocal.cs +++ b/src/Renci.SshNet/ForwardedPortLocal.cs @@ -88,12 +88,12 @@ public ForwardedPortLocal(string boundHost, string host, uint port) /// is greater than . public ForwardedPortLocal(string boundHost, uint boundPort, string host, uint port) { - if (boundHost == null) + if (boundHost is null) { throw new ArgumentNullException(nameof(boundHost)); } - if (host == null) + if (host is null) { throw new ArgumentNullException(nameof(host)); } diff --git a/src/Renci.SshNet/ForwardedPortRemote.cs b/src/Renci.SshNet/ForwardedPortRemote.cs index 6405f13a1..4d220c644 100644 --- a/src/Renci.SshNet/ForwardedPortRemote.cs +++ b/src/Renci.SshNet/ForwardedPortRemote.cs @@ -86,12 +86,12 @@ public string Host /// is greater than . public ForwardedPortRemote(IPAddress boundHostAddress, uint boundPort, IPAddress hostAddress, uint port) { - if (boundHostAddress == null) + if (boundHostAddress is null) { throw new ArgumentNullException(nameof(boundHostAddress)); } - if (hostAddress == null) + if (hostAddress is null) { throw new ArgumentNullException(nameof(hostAddress)); } @@ -328,7 +328,7 @@ private void Session_RequestSuccess(object sender, MessageEventArgs hash) { KeySize = keySize; - HashAlgorithm = key => (hash(key.Take(KeySize / 8))); + HashAlgorithm = key => hash(key.Take(KeySize / 8)); } } } diff --git a/src/Renci.SshNet/MessageEventArgs.cs b/src/Renci.SshNet/MessageEventArgs.cs index fead62e1e..c3886dce1 100644 --- a/src/Renci.SshNet/MessageEventArgs.cs +++ b/src/Renci.SshNet/MessageEventArgs.cs @@ -20,7 +20,7 @@ public class MessageEventArgs : EventArgs /// is null. public MessageEventArgs(T message) { - if (message == null) + if (message is null) { throw new ArgumentNullException(nameof(message)); } diff --git a/src/Renci.SshNet/Messages/Authentication/RequestMessagePublicKey.cs b/src/Renci.SshNet/Messages/Authentication/RequestMessagePublicKey.cs index 9a888e295..391e60e76 100644 --- a/src/Renci.SshNet/Messages/Authentication/RequestMessagePublicKey.cs +++ b/src/Renci.SshNet/Messages/Authentication/RequestMessagePublicKey.cs @@ -92,7 +92,9 @@ protected override void SaveData() WriteBinaryString(PublicKeyAlgorithmName); WriteBinaryString(PublicKeyData); if (Signature != null) + { WriteBinaryString(Signature); + } } } } diff --git a/src/Renci.SshNet/Messages/Connection/ChannelDataMessage.cs b/src/Renci.SshNet/Messages/Connection/ChannelDataMessage.cs index 7e88d2828..8a764d798 100644 --- a/src/Renci.SshNet/Messages/Connection/ChannelDataMessage.cs +++ b/src/Renci.SshNet/Messages/Connection/ChannelDataMessage.cs @@ -74,7 +74,7 @@ public ChannelDataMessage() public ChannelDataMessage(uint localChannelNumber, byte[] data) : base(localChannelNumber) { - if (data == null) + if (data is null) { throw new ArgumentNullException(nameof(data)); } @@ -94,7 +94,7 @@ public ChannelDataMessage(uint localChannelNumber, byte[] data) public ChannelDataMessage(uint localChannelNumber, byte[] data, int offset, int size) : base(localChannelNumber) { - if (data == null) + if (data is null) { throw new ArgumentNullException(nameof(data)); } diff --git a/src/Renci.SshNet/Messages/Connection/ChannelRequest/ExecRequestInfo.cs b/src/Renci.SshNet/Messages/Connection/ChannelRequest/ExecRequestInfo.cs index 877dd4326..412a86d88 100644 --- a/src/Renci.SshNet/Messages/Connection/ChannelRequest/ExecRequestInfo.cs +++ b/src/Renci.SshNet/Messages/Connection/ChannelRequest/ExecRequestInfo.cs @@ -6,7 +6,7 @@ namespace Renci.SshNet.Messages.Connection /// /// Represents "exec" type channel request information. /// - internal class ExecRequestInfo : RequestInfo + internal sealed class ExecRequestInfo : RequestInfo { private byte[] _command; @@ -79,12 +79,12 @@ public ExecRequestInfo() public ExecRequestInfo(string command, Encoding encoding) : this() { - if (command == null) + if (command is null) { throw new ArgumentNullException(nameof(command)); } - if (encoding == null) + if (encoding is null) { throw new ArgumentNullException(nameof(encoding)); } diff --git a/src/Renci.SshNet/Messages/Transport/IgnoreMessage.cs b/src/Renci.SshNet/Messages/Transport/IgnoreMessage.cs index 72fc10699..7c9fa247c 100644 --- a/src/Renci.SshNet/Messages/Transport/IgnoreMessage.cs +++ b/src/Renci.SshNet/Messages/Transport/IgnoreMessage.cs @@ -49,7 +49,7 @@ protected override int BufferCapacity /// The data. public IgnoreMessage(byte[] data) { - if (data == null) + if (data is null) { throw new ArgumentNullException(nameof(data)); } diff --git a/src/Renci.SshNet/Netconf/NetConfSession.cs b/src/Renci.SshNet/Netconf/NetConfSession.cs index 6e4e251f7..6e6f8c6c8 100644 --- a/src/Renci.SshNet/Netconf/NetConfSession.cs +++ b/src/Renci.SshNet/Netconf/NetConfSession.cs @@ -110,7 +110,7 @@ protected override void OnDataReceived(byte[] data) { var chunk = Encoding.UTF8.GetString(data); - if (ServerCapabilities == null) + if (ServerCapabilities is null) { _ = _data.Append(chunk); diff --git a/src/Renci.SshNet/NoneAuthenticationMethod.cs b/src/Renci.SshNet/NoneAuthenticationMethod.cs index 468d46559..71e100175 100644 --- a/src/Renci.SshNet/NoneAuthenticationMethod.cs +++ b/src/Renci.SshNet/NoneAuthenticationMethod.cs @@ -43,7 +43,7 @@ public NoneAuthenticationMethod(string username) /// is null. public override AuthenticationResult Authenticate(Session session) { - if (session == null) + if (session is null) { throw new ArgumentNullException(nameof(session)); } diff --git a/src/Renci.SshNet/PasswordAuthenticationMethod.cs b/src/Renci.SshNet/PasswordAuthenticationMethod.cs index a60b40ebf..5c7e8aaa9 100644 --- a/src/Renci.SshNet/PasswordAuthenticationMethod.cs +++ b/src/Renci.SshNet/PasswordAuthenticationMethod.cs @@ -68,7 +68,7 @@ public PasswordAuthenticationMethod(string username, string password) public PasswordAuthenticationMethod(string username, byte[] password) : base(username) { - if (password == null) + if (password is null) { throw new ArgumentNullException(nameof(password)); } @@ -87,7 +87,7 @@ public PasswordAuthenticationMethod(string username, byte[] password) /// is null. public override AuthenticationResult Authenticate(Session session) { - if (session == null) + if (session is null) { throw new ArgumentNullException(nameof(session)); } diff --git a/src/Renci.SshNet/PrivateKeyAuthenticationMethod.cs b/src/Renci.SshNet/PrivateKeyAuthenticationMethod.cs index 25f3f7605..1606ef757 100644 --- a/src/Renci.SshNet/PrivateKeyAuthenticationMethod.cs +++ b/src/Renci.SshNet/PrivateKeyAuthenticationMethod.cs @@ -41,7 +41,7 @@ public override string Name public PrivateKeyAuthenticationMethod(string username, params IPrivateKeySource[] keyFiles) : base(username) { - if (keyFiles == null) + if (keyFiles is null) { throw new ArgumentNullException(nameof(keyFiles)); } diff --git a/src/Renci.SshNet/PrivateKeyFile.cs b/src/Renci.SshNet/PrivateKeyFile.cs index 4da514384..e00a27fcd 100644 --- a/src/Renci.SshNet/PrivateKeyFile.cs +++ b/src/Renci.SshNet/PrivateKeyFile.cs @@ -147,7 +147,7 @@ public PrivateKeyFile(Stream privateKey, string passPhrase) /// The pass phrase. private void Open(Stream privateKey, string passPhrase) { - if (privateKey == null) + if (privateKey is null) { throw new ArgumentNullException(nameof(privateKey)); } @@ -258,7 +258,9 @@ private void Open(Stream privateKey, string passPhrase) else if (ssh2CipherName == "3des-cbc") { if (string.IsNullOrEmpty(passPhrase)) + { throw new SshPassPhraseNullOrEmptyException("Private key is encrypted but passphrase is empty."); + } var key = GetCipherKey(passPhrase, 192 / 8); var ssh2Сipher = new TripleDesCipher(key, new CbcCipherMode(new byte[8]), new PKCS7Padding()); @@ -349,17 +351,17 @@ private static byte[] GetCipherKey(string passphrase, int length) /// , , or is null. private static byte[] DecryptKey(CipherInfo cipherInfo, byte[] cipherData, string passPhrase, byte[] binarySalt) { - if (cipherInfo == null) + if (cipherInfo is null) { throw new ArgumentNullException(nameof(cipherInfo)); } - if (cipherData == null) + if (cipherData is null) { throw new ArgumentNullException(nameof(cipherData)); } - if (binarySalt == null) + if (binarySalt is null) { throw new ArgumentNullException(nameof(binarySalt)); } diff --git a/src/Renci.SshNet/RemotePathDoubleQuoteTransformation.cs b/src/Renci.SshNet/RemotePathDoubleQuoteTransformation.cs index e4f5496f2..68abce256 100644 --- a/src/Renci.SshNet/RemotePathDoubleQuoteTransformation.cs +++ b/src/Renci.SshNet/RemotePathDoubleQuoteTransformation.cs @@ -50,7 +50,7 @@ internal class RemotePathDoubleQuoteTransformation : IRemotePathTransformation /// public string Transform(string path) { - if (path == null) + if (path is null) { throw new ArgumentNullException(nameof(path)); } diff --git a/src/Renci.SshNet/RemotePathNoneTransformation.cs b/src/Renci.SshNet/RemotePathNoneTransformation.cs index f7bfbab6a..31dea7a87 100644 --- a/src/Renci.SshNet/RemotePathNoneTransformation.cs +++ b/src/Renci.SshNet/RemotePathNoneTransformation.cs @@ -21,7 +21,7 @@ internal class RemotePathNoneTransformation : IRemotePathTransformation /// public string Transform(string path) { - if (path == null) + if (path is null) { throw new ArgumentNullException(nameof(path)); } diff --git a/src/Renci.SshNet/RemotePathShellQuoteTransformation.cs b/src/Renci.SshNet/RemotePathShellQuoteTransformation.cs index 53424286c..9f247ccff 100644 --- a/src/Renci.SshNet/RemotePathShellQuoteTransformation.cs +++ b/src/Renci.SshNet/RemotePathShellQuoteTransformation.cs @@ -80,7 +80,7 @@ internal class RemotePathShellQuoteTransformation : IRemotePathTransformation /// public string Transform(string path) { - if (path == null) + if (path is null) { throw new ArgumentNullException(nameof(path)); } diff --git a/src/Renci.SshNet/ScpClient.NET.cs b/src/Renci.SshNet/ScpClient.NET.cs index 8ca396e7d..ede001942 100644 --- a/src/Renci.SshNet/ScpClient.NET.cs +++ b/src/Renci.SshNet/ScpClient.NET.cs @@ -27,7 +27,7 @@ public partial class ScpClient /// The secure copy execution request was rejected by the server. public void Upload(FileInfo fileInfo, string path) { - if (fileInfo == null) + if (fileInfo is null) { throw new ArgumentNullException(nameof(fileInfo)); } @@ -70,12 +70,12 @@ public void Upload(FileInfo fileInfo, string path) /// The secure copy execution request was rejected by the server. public void Upload(DirectoryInfo directoryInfo, string path) { - if (directoryInfo == null) + if (directoryInfo is null) { throw new ArgumentNullException(nameof(directoryInfo)); } - if (path == null) + if (path is null) { throw new ArgumentNullException(nameof(path)); } @@ -123,7 +123,7 @@ public void Download(string filename, FileInfo fileInfo) throw new ArgumentException("filename"); } - if (fileInfo == null) + if (fileInfo is null) { throw new ArgumentNullException(nameof(fileInfo)); } @@ -163,7 +163,7 @@ public void Download(string directoryName, DirectoryInfo directoryInfo) throw new ArgumentException("directoryName"); } - if (directoryInfo == null) + if (directoryInfo is null) { throw new ArgumentNullException(nameof(directoryInfo)); } diff --git a/src/Renci.SshNet/ScpClient.cs b/src/Renci.SshNet/ScpClient.cs index 7907bfe7d..7269e81c3 100644 --- a/src/Renci.SshNet/ScpClient.cs +++ b/src/Renci.SshNet/ScpClient.cs @@ -77,7 +77,7 @@ public IRemotePathTransformation RemotePathTransformation get { return _remotePathTransformation; } set { - if (value == null) + if (value is null) { throw new ArgumentNullException(nameof(value)); } @@ -248,7 +248,7 @@ public void Download(string filename, Stream destination) throw new ArgumentException(Message); } - if (destination == null) + if (destination is null) { throw new ArgumentNullException(nameof(destination)); } diff --git a/src/Renci.SshNet/Security/Cryptography/BlockCipher.cs b/src/Renci.SshNet/Security/Cryptography/BlockCipher.cs index 17e14c5dc..5a06d7a37 100644 --- a/src/Renci.SshNet/Security/Cryptography/BlockCipher.cs +++ b/src/Renci.SshNet/Security/Cryptography/BlockCipher.cs @@ -60,8 +60,7 @@ protected BlockCipher(byte[] key, byte blockSize, CipherMode mode, CipherPadding _mode = mode; _padding = padding; - if (_mode != null) - _mode.Init(this); + _mode?.Init(this); } /// @@ -75,10 +74,11 @@ public override byte[] Encrypt(byte[] data, int offset, int length) { if (length % _blockSize > 0) { - if (_padding == null) + if (_padding is null) { throw new ArgumentException("data"); } + var paddingLength = _blockSize - (length % _blockSize); data = _padding.Pad(data, offset, length, paddingLength); length += paddingLength; @@ -90,7 +90,7 @@ public override byte[] Encrypt(byte[] data, int offset, int length) for (var i = 0; i < length / _blockSize; i++) { - if (_mode == null) + if (_mode is null) { writtenBytes += EncryptBlock(data, offset + (i * _blockSize), _blockSize, output, i * _blockSize); } @@ -131,7 +131,7 @@ public override byte[] Decrypt(byte[] data, int offset, int length) { if (length % _blockSize > 0) { - if (_padding == null) + if (_padding is null) { throw new ArgumentException("data"); } @@ -146,7 +146,7 @@ public override byte[] Decrypt(byte[] data, int offset, int length) var writtenBytes = 0; for (var i = 0; i < length / _blockSize; i++) { - if (_mode == null) + if (_mode is null) { writtenBytes += DecryptBlock(data, offset + (i * _blockSize), _blockSize, output, i * _blockSize); } diff --git a/src/Renci.SshNet/Security/Cryptography/CipherDigitalSignature.cs b/src/Renci.SshNet/Security/Cryptography/CipherDigitalSignature.cs index 7312a6292..ec9243fe6 100644 --- a/src/Renci.SshNet/Security/Cryptography/CipherDigitalSignature.cs +++ b/src/Renci.SshNet/Security/Cryptography/CipherDigitalSignature.cs @@ -18,7 +18,7 @@ public abstract class CipherDigitalSignature : DigitalSignature /// The cipher. protected CipherDigitalSignature(ObjectIdentifier oid, AsymmetricCipher cipher) { - if (cipher == null) + if (cipher is null) { throw new ArgumentNullException(nameof(cipher)); } diff --git a/src/Renci.SshNet/Security/Cryptography/Ciphers/AesCipher.cs b/src/Renci.SshNet/Security/Cryptography/Ciphers/AesCipher.cs index 9fb8d0a25..29e4c42e7 100644 --- a/src/Renci.SshNet/Security/Cryptography/Ciphers/AesCipher.cs +++ b/src/Renci.SshNet/Security/Cryptography/Ciphers/AesCipher.cs @@ -1,5 +1,6 @@ using System; using System.Globalization; + using Renci.SshNet.Common; namespace Renci.SshNet.Security.Cryptography.Ciphers @@ -9,19 +10,14 @@ namespace Renci.SshNet.Security.Cryptography.Ciphers /// public sealed class AesCipher : BlockCipher { - private const uint m1 = 0x80808080; - - private const uint m2 = 0x7f7f7f7f; - - private const uint m3 = 0x0000001b; + private const uint M1 = 0x80808080; + private const uint M2 = 0x7f7f7f7f; + private const uint M3 = 0x0000001b; private int _rounds; - private uint[] _encryptionKey; - private uint[] _decryptionKey; - - private uint C0, C1, C2, C3; + private uint _c0, _c1, _c2, _c3; #region Static Definition Tables @@ -99,7 +95,7 @@ public sealed class AesCipher : BlockCipher }; // vector used in calculating key schedule (powers of x in GF(256)) - private static readonly byte[] rcon = + private static readonly byte[] Rcon = { 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91 @@ -590,12 +586,12 @@ public AesCipher(byte[] key, CipherMode mode, CipherPadding padding) /// or is too short. public override int EncryptBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset) { - if (inputBuffer == null) + if (inputBuffer is null) { throw new ArgumentNullException(nameof(inputBuffer)); } - if (outputBuffer == null) + if (outputBuffer is null) { throw new ArgumentNullException(nameof(outputBuffer)); } @@ -636,12 +632,12 @@ public override int EncryptBlock(byte[] inputBuffer, int inputOffset, int inputC /// or is too short. public override int DecryptBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset) { - if (inputBuffer == null) + if (inputBuffer is null) { throw new ArgumentNullException(nameof(inputBuffer)); } - if (outputBuffer == null) + if (outputBuffer is null) { throw new ArgumentNullException(nameof(outputBuffer)); } @@ -669,7 +665,7 @@ public override int DecryptBlock(byte[] inputBuffer, int inputOffset, int inputC private uint[] GenerateWorkingKey(bool isEncryption, byte[] key) { - int KC = key.Length / 4; // key length in words + var KC = key.Length / 4; // key length in words if (((KC != 4) && (KC != 6) && (KC != 8)) || ((KC * 4) != key.Length)) { @@ -677,13 +673,13 @@ private uint[] GenerateWorkingKey(bool isEncryption, byte[] key) } _rounds = KC + 6; // This is not always true for the generalized Rijndael that allows larger block sizes - uint[] W = new uint[(_rounds + 1) * 4]; // 4 words in a block + var W = new uint[(_rounds + 1) * 4]; // 4 words in a block // // copy the key into the round key array // - int t = 0; + var t = 0; for (var i = 0; i < key.Length; t++) { @@ -695,13 +691,13 @@ private uint[] GenerateWorkingKey(bool isEncryption, byte[] key) // while not enough round key material calculated // calculate new values // - int k = (_rounds + 1) << 2; - for (int i = KC; (i < k); i++) + var k = (_rounds + 1) << 2; + for (var i = KC; i < k; i++) { - uint temp = W[((i - 1) >> 2) * 4 + ((i - 1) & 3)]; + var temp = W[((i - 1) >> 2) * 4 + ((i - 1) & 3)]; if ((i % KC) == 0) { - temp = SubWord(Shift(temp, 8)) ^ rcon[(i / KC) - 1]; + temp = SubWord(Shift(temp, 8)) ^ Rcon[(i / KC) - 1]; } else if ((KC > 6) && ((i % KC) == 4)) { @@ -713,9 +709,9 @@ private uint[] GenerateWorkingKey(bool isEncryption, byte[] key) if (!isEncryption) { - for (int j = 1; j < _rounds; j++) + for (var j = 1; j < _rounds; j++) { - for (int i = 0; i < 4; i++) + for (var i = 0; i < 4; i++) { W[j * 4 + i] = InvMcol(W[j * 4 + i]); } @@ -732,15 +728,15 @@ private static uint Shift(uint r, int shift) private static uint FFmulX(uint x) { - return ((x & m2) << 1) ^ (((x & m1) >> 7) * m3); + return ((x & M2) << 1) ^ (((x & M1) >> 7) * M3); } private static uint InvMcol(uint x) { - uint f2 = FFmulX(x); - uint f4 = FFmulX(f2); - uint f8 = FFmulX(f4); - uint f9 = x ^ f8; + var f2 = FFmulX(x); + var f4 = FFmulX(f2); + var f8 = FFmulX(f4); + var f9 = x ^ f8; return f2 ^ f4 ^ f8 ^ Shift(f2 ^ f9, 8) ^ Shift(f4 ^ f9, 16) ^ Shift(f9, 24); } @@ -755,18 +751,18 @@ private static uint SubWord(uint x) private void UnPackBlock(byte[] bytes, int off) { - C0 = Pack.LittleEndianToUInt32(bytes, off); - C1 = Pack.LittleEndianToUInt32(bytes, off + 4); - C2 = Pack.LittleEndianToUInt32(bytes, off + 8); - C3 = Pack.LittleEndianToUInt32(bytes, off + 12); + _c0 = Pack.LittleEndianToUInt32(bytes, off); + _c1 = Pack.LittleEndianToUInt32(bytes, off + 4); + _c2 = Pack.LittleEndianToUInt32(bytes, off + 8); + _c3 = Pack.LittleEndianToUInt32(bytes, off + 12); } private void PackBlock(byte[] bytes, int off) { - Pack.UInt32ToLittleEndian(C0, bytes, off); - Pack.UInt32ToLittleEndian(C1, bytes, off + 4); - Pack.UInt32ToLittleEndian(C2, bytes, off + 8); - Pack.UInt32ToLittleEndian(C3, bytes, off + 12); + Pack.UInt32ToLittleEndian(_c0, bytes, off); + Pack.UInt32ToLittleEndian(_c1, bytes, off + 4); + Pack.UInt32ToLittleEndian(_c2, bytes, off + 8); + Pack.UInt32ToLittleEndian(_c3, bytes, off + 12); } private void EncryptBlock(uint[] KW) @@ -774,34 +770,34 @@ private void EncryptBlock(uint[] KW) int r; uint r0, r1, r2, r3; - C0 ^= KW[0 * 4 + 0]; - C1 ^= KW[0 * 4 + 1]; - C2 ^= KW[0 * 4 + 2]; - C3 ^= KW[0 * 4 + 3]; + _c0 ^= KW[0 * 4 + 0]; + _c1 ^= KW[0 * 4 + 1]; + _c2 ^= KW[0 * 4 + 2]; + _c3 ^= KW[0 * 4 + 3]; for (r = 1; r < _rounds - 1;) { - r0 = T0[C0 & 255] ^ T1[(C1 >> 8) & 255] ^ T2[(C2 >> 16) & 255] ^ T3[C3 >> 24] ^ KW[r * 4 + 0]; - r1 = T0[C1 & 255] ^ T1[(C2 >> 8) & 255] ^ T2[(C3 >> 16) & 255] ^ T3[C0 >> 24] ^ KW[r * 4 + 1]; - r2 = T0[C2 & 255] ^ T1[(C3 >> 8) & 255] ^ T2[(C0 >> 16) & 255] ^ T3[C1 >> 24] ^ KW[r * 4 + 2]; - r3 = T0[C3 & 255] ^ T1[(C0 >> 8) & 255] ^ T2[(C1 >> 16) & 255] ^ T3[C2 >> 24] ^ KW[r++ * 4 + 3]; - C0 = T0[r0 & 255] ^ T1[(r1 >> 8) & 255] ^ T2[(r2 >> 16) & 255] ^ T3[r3 >> 24] ^ KW[r * 4 + 0]; - C1 = T0[r1 & 255] ^ T1[(r2 >> 8) & 255] ^ T2[(r3 >> 16) & 255] ^ T3[r0 >> 24] ^ KW[r * 4 + 1]; - C2 = T0[r2 & 255] ^ T1[(r3 >> 8) & 255] ^ T2[(r0 >> 16) & 255] ^ T3[r1 >> 24] ^ KW[r * 4 + 2]; - C3 = T0[r3 & 255] ^ T1[(r0 >> 8) & 255] ^ T2[(r1 >> 16) & 255] ^ T3[r2 >> 24] ^ KW[r++ * 4 + 3]; + r0 = T0[_c0 & 255] ^ T1[(_c1 >> 8) & 255] ^ T2[(_c2 >> 16) & 255] ^ T3[_c3 >> 24] ^ KW[r * 4 + 0]; + r1 = T0[_c1 & 255] ^ T1[(_c2 >> 8) & 255] ^ T2[(_c3 >> 16) & 255] ^ T3[_c0 >> 24] ^ KW[r * 4 + 1]; + r2 = T0[_c2 & 255] ^ T1[(_c3 >> 8) & 255] ^ T2[(_c0 >> 16) & 255] ^ T3[_c1 >> 24] ^ KW[r * 4 + 2]; + r3 = T0[_c3 & 255] ^ T1[(_c0 >> 8) & 255] ^ T2[(_c1 >> 16) & 255] ^ T3[_c2 >> 24] ^ KW[r++ * 4 + 3]; + _c0 = T0[r0 & 255] ^ T1[(r1 >> 8) & 255] ^ T2[(r2 >> 16) & 255] ^ T3[r3 >> 24] ^ KW[r * 4 + 0]; + _c1 = T0[r1 & 255] ^ T1[(r2 >> 8) & 255] ^ T2[(r3 >> 16) & 255] ^ T3[r0 >> 24] ^ KW[r * 4 + 1]; + _c2 = T0[r2 & 255] ^ T1[(r3 >> 8) & 255] ^ T2[(r0 >> 16) & 255] ^ T3[r1 >> 24] ^ KW[r * 4 + 2]; + _c3 = T0[r3 & 255] ^ T1[(r0 >> 8) & 255] ^ T2[(r1 >> 16) & 255] ^ T3[r2 >> 24] ^ KW[r++ * 4 + 3]; } - r0 = T0[C0 & 255] ^ T1[(C1 >> 8) & 255] ^ T2[(C2 >> 16) & 255] ^ T3[C3 >> 24] ^ KW[r * 4 + 0]; - r1 = T0[C1 & 255] ^ T1[(C2 >> 8) & 255] ^ T2[(C3 >> 16) & 255] ^ T3[C0 >> 24] ^ KW[r * 4 + 1]; - r2 = T0[C2 & 255] ^ T1[(C3 >> 8) & 255] ^ T2[(C0 >> 16) & 255] ^ T3[C1 >> 24] ^ KW[r * 4 + 2]; - r3 = T0[C3 & 255] ^ T1[(C0 >> 8) & 255] ^ T2[(C1 >> 16) & 255] ^ T3[C2 >> 24] ^ KW[r++ * 4 + 3]; + r0 = T0[_c0 & 255] ^ T1[(_c1 >> 8) & 255] ^ T2[(_c2 >> 16) & 255] ^ T3[_c3 >> 24] ^ KW[r * 4 + 0]; + r1 = T0[_c1 & 255] ^ T1[(_c2 >> 8) & 255] ^ T2[(_c3 >> 16) & 255] ^ T3[_c0 >> 24] ^ KW[r * 4 + 1]; + r2 = T0[_c2 & 255] ^ T1[(_c3 >> 8) & 255] ^ T2[(_c0 >> 16) & 255] ^ T3[_c1 >> 24] ^ KW[r * 4 + 2]; + r3 = T0[_c3 & 255] ^ T1[(_c0 >> 8) & 255] ^ T2[(_c1 >> 16) & 255] ^ T3[_c2 >> 24] ^ KW[r++ * 4 + 3]; // the final round's table is a simple function of S so we don't use a whole other four tables for it - C0 = (uint)S[r0 & 255] ^ (((uint)S[(r1 >> 8) & 255]) << 8) ^ (((uint)S[(r2 >> 16) & 255]) << 16) ^ (((uint)S[r3 >> 24]) << 24) ^ KW[r * 4 + 0]; - C1 = (uint)S[r1 & 255] ^ (((uint)S[(r2 >> 8) & 255]) << 8) ^ (((uint)S[(r3 >> 16) & 255]) << 16) ^ (((uint)S[r0 >> 24]) << 24) ^ KW[r * 4 + 1]; - C2 = (uint)S[r2 & 255] ^ (((uint)S[(r3 >> 8) & 255]) << 8) ^ (((uint)S[(r0 >> 16) & 255]) << 16) ^ (((uint)S[r1 >> 24]) << 24) ^ KW[r * 4 + 2]; - C3 = (uint)S[r3 & 255] ^ (((uint)S[(r0 >> 8) & 255]) << 8) ^ (((uint)S[(r1 >> 16) & 255]) << 16) ^ (((uint)S[r2 >> 24]) << 24) ^ KW[r * 4 + 3]; + _c0 = (uint)S[r0 & 255] ^ (((uint)S[(r1 >> 8) & 255]) << 8) ^ (((uint)S[(r2 >> 16) & 255]) << 16) ^ (((uint)S[r3 >> 24]) << 24) ^ KW[r * 4 + 0]; + _c1 = (uint)S[r1 & 255] ^ (((uint)S[(r2 >> 8) & 255]) << 8) ^ (((uint)S[(r3 >> 16) & 255]) << 16) ^ (((uint)S[r0 >> 24]) << 24) ^ KW[r * 4 + 1]; + _c2 = (uint)S[r2 & 255] ^ (((uint)S[(r3 >> 8) & 255]) << 8) ^ (((uint)S[(r0 >> 16) & 255]) << 16) ^ (((uint)S[r1 >> 24]) << 24) ^ KW[r * 4 + 2]; + _c3 = (uint)S[r3 & 255] ^ (((uint)S[(r0 >> 8) & 255]) << 8) ^ (((uint)S[(r1 >> 16) & 255]) << 16) ^ (((uint)S[r2 >> 24]) << 24) ^ KW[r * 4 + 3]; } private void DecryptBlock(uint[] KW) @@ -809,34 +805,34 @@ private void DecryptBlock(uint[] KW) int r; uint r0, r1, r2, r3; - C0 ^= KW[_rounds * 4 + 0]; - C1 ^= KW[_rounds * 4 + 1]; - C2 ^= KW[_rounds * 4 + 2]; - C3 ^= KW[_rounds * 4 + 3]; + _c0 ^= KW[_rounds * 4 + 0]; + _c1 ^= KW[_rounds * 4 + 1]; + _c2 ^= KW[_rounds * 4 + 2]; + _c3 ^= KW[_rounds * 4 + 3]; for (r = _rounds - 1; r > 1;) { - r0 = Tinv0[C0 & 255] ^ Tinv1[(C3 >> 8) & 255] ^ Tinv2[(C2 >> 16) & 255] ^ Tinv3[C1 >> 24] ^ KW[r * 4 + 0]; - r1 = Tinv0[C1 & 255] ^ Tinv1[(C0 >> 8) & 255] ^ Tinv2[(C3 >> 16) & 255] ^ Tinv3[C2 >> 24] ^ KW[r * 4 + 1]; - r2 = Tinv0[C2 & 255] ^ Tinv1[(C1 >> 8) & 255] ^ Tinv2[(C0 >> 16) & 255] ^ Tinv3[C3 >> 24] ^ KW[r * 4 + 2]; - r3 = Tinv0[C3 & 255] ^ Tinv1[(C2 >> 8) & 255] ^ Tinv2[(C1 >> 16) & 255] ^ Tinv3[C0 >> 24] ^ KW[r-- * 4 + 3]; - C0 = Tinv0[r0 & 255] ^ Tinv1[(r3 >> 8) & 255] ^ Tinv2[(r2 >> 16) & 255] ^ Tinv3[r1 >> 24] ^ KW[r * 4 + 0]; - C1 = Tinv0[r1 & 255] ^ Tinv1[(r0 >> 8) & 255] ^ Tinv2[(r3 >> 16) & 255] ^ Tinv3[r2 >> 24] ^ KW[r * 4 + 1]; - C2 = Tinv0[r2 & 255] ^ Tinv1[(r1 >> 8) & 255] ^ Tinv2[(r0 >> 16) & 255] ^ Tinv3[r3 >> 24] ^ KW[r * 4 + 2]; - C3 = Tinv0[r3 & 255] ^ Tinv1[(r2 >> 8) & 255] ^ Tinv2[(r1 >> 16) & 255] ^ Tinv3[r0 >> 24] ^ KW[r-- * 4 + 3]; + r0 = Tinv0[_c0 & 255] ^ Tinv1[(_c3 >> 8) & 255] ^ Tinv2[(_c2 >> 16) & 255] ^ Tinv3[_c1 >> 24] ^ KW[r * 4 + 0]; + r1 = Tinv0[_c1 & 255] ^ Tinv1[(_c0 >> 8) & 255] ^ Tinv2[(_c3 >> 16) & 255] ^ Tinv3[_c2 >> 24] ^ KW[r * 4 + 1]; + r2 = Tinv0[_c2 & 255] ^ Tinv1[(_c1 >> 8) & 255] ^ Tinv2[(_c0 >> 16) & 255] ^ Tinv3[_c3 >> 24] ^ KW[r * 4 + 2]; + r3 = Tinv0[_c3 & 255] ^ Tinv1[(_c2 >> 8) & 255] ^ Tinv2[(_c1 >> 16) & 255] ^ Tinv3[_c0 >> 24] ^ KW[r-- * 4 + 3]; + _c0 = Tinv0[r0 & 255] ^ Tinv1[(r3 >> 8) & 255] ^ Tinv2[(r2 >> 16) & 255] ^ Tinv3[r1 >> 24] ^ KW[r * 4 + 0]; + _c1 = Tinv0[r1 & 255] ^ Tinv1[(r0 >> 8) & 255] ^ Tinv2[(r3 >> 16) & 255] ^ Tinv3[r2 >> 24] ^ KW[r * 4 + 1]; + _c2 = Tinv0[r2 & 255] ^ Tinv1[(r1 >> 8) & 255] ^ Tinv2[(r0 >> 16) & 255] ^ Tinv3[r3 >> 24] ^ KW[r * 4 + 2]; + _c3 = Tinv0[r3 & 255] ^ Tinv1[(r2 >> 8) & 255] ^ Tinv2[(r1 >> 16) & 255] ^ Tinv3[r0 >> 24] ^ KW[r-- * 4 + 3]; } - r0 = Tinv0[C0 & 255] ^ Tinv1[(C3 >> 8) & 255] ^ Tinv2[(C2 >> 16) & 255] ^ Tinv3[C1 >> 24] ^ KW[r * 4 + 0]; - r1 = Tinv0[C1 & 255] ^ Tinv1[(C0 >> 8) & 255] ^ Tinv2[(C3 >> 16) & 255] ^ Tinv3[C2 >> 24] ^ KW[r * 4 + 1]; - r2 = Tinv0[C2 & 255] ^ Tinv1[(C1 >> 8) & 255] ^ Tinv2[(C0 >> 16) & 255] ^ Tinv3[C3 >> 24] ^ KW[r * 4 + 2]; - r3 = Tinv0[C3 & 255] ^ Tinv1[(C2 >> 8) & 255] ^ Tinv2[(C1 >> 16) & 255] ^ Tinv3[C0 >> 24] ^ KW[r * 4 + 3]; + r0 = Tinv0[_c0 & 255] ^ Tinv1[(_c3 >> 8) & 255] ^ Tinv2[(_c2 >> 16) & 255] ^ Tinv3[_c1 >> 24] ^ KW[r * 4 + 0]; + r1 = Tinv0[_c1 & 255] ^ Tinv1[(_c0 >> 8) & 255] ^ Tinv2[(_c3 >> 16) & 255] ^ Tinv3[_c2 >> 24] ^ KW[r * 4 + 1]; + r2 = Tinv0[_c2 & 255] ^ Tinv1[(_c1 >> 8) & 255] ^ Tinv2[(_c0 >> 16) & 255] ^ Tinv3[_c3 >> 24] ^ KW[r * 4 + 2]; + r3 = Tinv0[_c3 & 255] ^ Tinv1[(_c2 >> 8) & 255] ^ Tinv2[(_c1 >> 16) & 255] ^ Tinv3[_c0 >> 24] ^ KW[r * 4 + 3]; // the final round's table is a simple function of Si so we don't use a whole other four tables for it - C0 = (uint)Si[r0 & 255] ^ (((uint)Si[(r3 >> 8) & 255]) << 8) ^ (((uint)Si[(r2 >> 16) & 255]) << 16) ^ (((uint)Si[r1 >> 24]) << 24) ^ KW[0 * 4 + 0]; - C1 = (uint)Si[r1 & 255] ^ (((uint)Si[(r0 >> 8) & 255]) << 8) ^ (((uint)Si[(r3 >> 16) & 255]) << 16) ^ (((uint)Si[r2 >> 24]) << 24) ^ KW[0 * 4 + 1]; - C2 = (uint)Si[r2 & 255] ^ (((uint)Si[(r1 >> 8) & 255]) << 8) ^ (((uint)Si[(r0 >> 16) & 255]) << 16) ^ (((uint)Si[r3 >> 24]) << 24) ^ KW[0 * 4 + 2]; - C3 = (uint)Si[r3 & 255] ^ (((uint)Si[(r2 >> 8) & 255]) << 8) ^ (((uint)Si[(r1 >> 16) & 255]) << 16) ^ (((uint)Si[r0 >> 24]) << 24) ^ KW[0 * 4 + 3]; + _c0 = (uint)Si[r0 & 255] ^ (((uint)Si[(r3 >> 8) & 255]) << 8) ^ (((uint)Si[(r2 >> 16) & 255]) << 16) ^ (((uint)Si[r1 >> 24]) << 24) ^ KW[0 * 4 + 0]; + _c1 = (uint)Si[r1 & 255] ^ (((uint)Si[(r0 >> 8) & 255]) << 8) ^ (((uint)Si[(r3 >> 16) & 255]) << 16) ^ (((uint)Si[r2 >> 24]) << 24) ^ KW[0 * 4 + 1]; + _c2 = (uint)Si[r2 & 255] ^ (((uint)Si[(r1 >> 8) & 255]) << 8) ^ (((uint)Si[(r0 >> 16) & 255]) << 16) ^ (((uint)Si[r3 >> 24]) << 24) ^ KW[0 * 4 + 2]; + _c3 = (uint)Si[r3 & 255] ^ (((uint)Si[(r2 >> 8) & 255]) << 8) ^ (((uint)Si[(r1 >> 16) & 255]) << 16) ^ (((uint)Si[r0 >> 24]) << 24) ^ KW[0 * 4 + 3]; } } } diff --git a/src/Renci.SshNet/Security/Cryptography/Ciphers/Arc4Cipher.cs b/src/Renci.SshNet/Security/Cryptography/Ciphers/Arc4Cipher.cs index 831b7f3cc..fc2174bf9 100644 --- a/src/Renci.SshNet/Security/Cryptography/Ciphers/Arc4Cipher.cs +++ b/src/Renci.SshNet/Security/Cryptography/Ciphers/Arc4Cipher.cs @@ -47,7 +47,9 @@ public Arc4Cipher(byte[] key, bool dischargeFirstBytes) // first encrypted packet MUST be encrypted using the 1537th byte of // keystream. if (dischargeFirstBytes) - Encrypt(new byte[1536]); + { + _ = Encrypt(new byte[1536]); + } } /// @@ -94,7 +96,7 @@ public override int DecryptBlock(byte[] inputBuffer, int inputOffset, int inputC public override byte[] Encrypt(byte[] input, int offset, int length) { var output = new byte[length]; - ProcessBytes(input, offset, length, output, 0); + _ = ProcessBytes(input, offset, length, output, 0); return output; } @@ -122,7 +124,7 @@ public override byte[] Decrypt(byte[] input) public override byte[] Decrypt(byte[] input, int offset, int length) { var output = new byte[length]; - ProcessBytes(input, offset, length, output, 0); + _ = ProcessBytes(input, offset, length, output, 0); return output; } diff --git a/src/Renci.SshNet/Security/Cryptography/Ciphers/BlowfishCipher.cs b/src/Renci.SshNet/Security/Cryptography/Ciphers/BlowfishCipher.cs index 2dfa7909e..f43940c5c 100644 --- a/src/Renci.SshNet/Security/Cryptography/Ciphers/BlowfishCipher.cs +++ b/src/Renci.SshNet/Security/Cryptography/Ciphers/BlowfishCipher.cs @@ -322,8 +322,10 @@ public BlowfishCipher(byte[] key, CipherMode mode, CipherPadding padding) { var keySize = key.Length * 8; - if (keySize < 1 || keySize > 448) + if (keySize is < 1 or > 448) + { throw new ArgumentException(string.Format("KeySize '{0}' is not valid for this algorithm.", keySize)); + } _s0 = new uint[SboxSk]; _s1 = new uint[SboxSk]; @@ -352,12 +354,12 @@ public override int EncryptBlock(byte[] inputBuffer, int inputOffset, int inputC throw new ArgumentException("inputCount"); } - uint xl = Pack.BigEndianToUInt32(inputBuffer, inputOffset); - uint xr = Pack.BigEndianToUInt32(inputBuffer, inputOffset + 4); + var xl = Pack.BigEndianToUInt32(inputBuffer, inputOffset); + var xr = Pack.BigEndianToUInt32(inputBuffer, inputOffset + 4); xl ^= _p[0]; - for (int i = 1; i < Rounds; i += 2) + for (var i = 1; i < Rounds; i += 2) { xr ^= F(xl) ^ _p[i]; xl ^= F(xr) ^ _p[i + 1]; @@ -385,7 +387,9 @@ public override int EncryptBlock(byte[] inputBuffer, int inputOffset, int inputC public override int DecryptBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset) { if (inputCount != BlockSize) + { throw new ArgumentException("inputCount"); + } var xl = Pack.BigEndianToUInt32(inputBuffer, inputOffset); var xr = Pack.BigEndianToUInt32(inputBuffer, inputOffset + 4); @@ -408,7 +412,7 @@ public override int DecryptBlock(byte[] inputBuffer, int inputOffset, int inputC private uint F(uint x) { - return (((_s0[x >> 24] + _s1[(x >> 16) & 0xff]) ^ _s2[(x >> 8) & 0xff]) + _s3[x & 0xff]); + return ((_s0[x >> 24] + _s1[(x >> 16) & 0xff]) ^ _s2[(x >> 8) & 0xff]) + _s3[x & 0xff]; } private void SetKey(byte[] key) diff --git a/src/Renci.SshNet/Security/Cryptography/Ciphers/CastCipher.cs b/src/Renci.SshNet/Security/Cryptography/Ciphers/CastCipher.cs index e7577f39f..e2b0779e1 100644 --- a/src/Renci.SshNet/Security/Cryptography/Ciphers/CastCipher.cs +++ b/src/Renci.SshNet/Security/Cryptography/Ciphers/CastCipher.cs @@ -38,7 +38,9 @@ public CastCipher(byte[] key, CipherMode mode, CipherPadding padding) var keySize = key.Length * 8; if (!(keySize >= 40 && keySize <= 128 && keySize % 8 == 0)) + { throw new ArgumentException(string.Format("KeySize '{0}' is not valid for this algorithm.", keySize)); + } SetKey(key); } @@ -625,6 +627,7 @@ private void CastEncipher(uint l0, uint r0, uint[] result) var rp = ri; // equivalent to R[i-1] li = rp; + switch (i) { case 1: @@ -649,6 +652,9 @@ private void CastEncipher(uint l0, uint r0, uint[] result) case 15: ri = lp ^ F3(rp, _km[i], _kr[i]); break; + default: + // We should never get here as max. rounds is 16 + break; } } @@ -666,6 +672,7 @@ private void CastDecipher(uint l16, uint r16, uint[] result) var rp = ri; // equivalent to R[i-1] li = rp; + switch (i) { case 1: @@ -690,6 +697,9 @@ private void CastDecipher(uint l16, uint r16, uint[] result) case 15: ri = lp ^ F3(rp, _km[i], _kr[i]); break; + default: + // We should never get here as max. rounds is 16 + break; } } diff --git a/src/Renci.SshNet/Security/Cryptography/Ciphers/Modes/CtrCipherMode.cs b/src/Renci.SshNet/Security/Cryptography/Ciphers/Modes/CtrCipherMode.cs index 47146567b..90149f575 100644 --- a/src/Renci.SshNet/Security/Cryptography/Ciphers/Modes/CtrCipherMode.cs +++ b/src/Renci.SshNet/Security/Cryptography/Ciphers/Modes/CtrCipherMode.cs @@ -56,7 +56,10 @@ public override int EncryptBlock(byte[] inputBuffer, int inputOffset, int inputC } var j = IV.Length; - while (--j >= 0 && ++IV[j] == 0) ; + while (--j >= 0 && ++IV[j] == 0) + { + // Intentionally empty block + } return _blockSize; } @@ -97,7 +100,10 @@ public override int DecryptBlock(byte[] inputBuffer, int inputOffset, int inputC } var j = IV.Length; - while (--j >= 0 && ++IV[j] == 0) ; + while (--j >= 0 && ++IV[j] == 0) + { + // Intentionally empty block + } return _blockSize; } diff --git a/src/Renci.SshNet/Security/Cryptography/Ciphers/RsaCipher.cs b/src/Renci.SshNet/Security/Cryptography/Ciphers/RsaCipher.cs index 0bfce1aad..d3644ba3b 100644 --- a/src/Renci.SshNet/Security/Cryptography/Ciphers/RsaCipher.cs +++ b/src/Renci.SshNet/Security/Cryptography/Ciphers/RsaCipher.cs @@ -18,7 +18,7 @@ public class RsaCipher : AsymmetricCipher /// The RSA key. public RsaCipher(RsaKey key) { - if (key == null) + if (key is null) { throw new ArgumentNullException(nameof(key)); } diff --git a/src/Renci.SshNet/Security/Cryptography/Ciphers/TripleDesCipher.cs b/src/Renci.SshNet/Security/Cryptography/Ciphers/TripleDesCipher.cs index f83ed24d0..3d52e2a26 100644 --- a/src/Renci.SshNet/Security/Cryptography/Ciphers/TripleDesCipher.cs +++ b/src/Renci.SshNet/Security/Cryptography/Ciphers/TripleDesCipher.cs @@ -40,12 +40,16 @@ public TripleDesCipher(byte[] key, CipherMode mode, CipherPadding padding) public override int EncryptBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset) { if ((inputOffset + BlockSize) > inputBuffer.Length) + { throw new IndexOutOfRangeException("input buffer too short"); + } if ((outputOffset + BlockSize) > outputBuffer.Length) + { throw new IndexOutOfRangeException("output buffer too short"); + } - if (_encryptionKey1 == null || _encryptionKey2 == null || _encryptionKey3 == null) + if (_encryptionKey1 is null || _encryptionKey2 is null || _encryptionKey3 is null) { var part1 = new byte[8]; var part2 = new byte[8]; @@ -102,7 +106,7 @@ public override int DecryptBlock(byte[] inputBuffer, int inputOffset, int inputC throw new IndexOutOfRangeException("output buffer too short"); } - if (_decryptionKey1 == null || _decryptionKey2 == null || _decryptionKey3 == null) + if (_decryptionKey1 is null || _decryptionKey2 is null || _decryptionKey3 is null) { var part1 = new byte[8]; var part2 = new byte[8]; diff --git a/src/Renci.SshNet/Security/Cryptography/Ciphers/TwofishCipher.cs b/src/Renci.SshNet/Security/Cryptography/Ciphers/TwofishCipher.cs index ac33dce9c..1a4bf2cc5 100644 --- a/src/Renci.SshNet/Security/Cryptography/Ciphers/TwofishCipher.cs +++ b/src/Renci.SshNet/Security/Cryptography/Ciphers/TwofishCipher.cs @@ -42,13 +42,13 @@ public TwofishCipher(byte[] key, CipherMode mode, CipherPadding padding) mX[1] = Mx_X(j) & 0xff; mY[1] = Mx_Y(j) & 0xff; - gMDS0[i] = m1[P_00] | mX[P_00] << 8 | mY[P_00] << 16 | mY[P_00] << 24; + _gMDS0[i] = m1[P_00] | mX[P_00] << 8 | mY[P_00] << 16 | mY[P_00] << 24; - gMDS1[i] = mY[P_10] | mY[P_10] << 8 | mX[P_10] << 16 | m1[P_10] << 24; + _gMDS1[i] = mY[P_10] | mY[P_10] << 8 | mX[P_10] << 16 | m1[P_10] << 24; - gMDS2[i] = mX[P_20] | mY[P_20] << 8 | m1[P_20] << 16 | mY[P_20] << 24; + _gMDS2[i] = mX[P_20] | mY[P_20] << 8 | m1[P_20] << 16 | mY[P_20] << 24; - gMDS3[i] = mX[P_30] | m1[P_30] << 8 | mY[P_30] << 16 | mX[P_30] << 24; + _gMDS3[i] = mX[P_30] | m1[P_30] << 8 | mY[P_30] << 16 | mX[P_30] << 24; } _k64Cnt = key.Length / 8; // pre-padded ? @@ -68,31 +68,31 @@ public TwofishCipher(byte[] key, CipherMode mode, CipherPadding padding) /// public override int EncryptBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset) { - var x0 = BytesTo32Bits(inputBuffer, inputOffset) ^ gSubKeys[INPUT_WHITEN]; - var x1 = BytesTo32Bits(inputBuffer, inputOffset + 4) ^ gSubKeys[INPUT_WHITEN + 1]; - var x2 = BytesTo32Bits(inputBuffer, inputOffset + 8) ^ gSubKeys[INPUT_WHITEN + 2]; - var x3 = BytesTo32Bits(inputBuffer, inputOffset + 12) ^ gSubKeys[INPUT_WHITEN + 3]; + var x0 = BytesTo32Bits(inputBuffer, inputOffset) ^ _gSubKeys[INPUT_WHITEN]; + var x1 = BytesTo32Bits(inputBuffer, inputOffset + 4) ^ _gSubKeys[INPUT_WHITEN + 1]; + var x2 = BytesTo32Bits(inputBuffer, inputOffset + 8) ^ _gSubKeys[INPUT_WHITEN + 2]; + var x3 = BytesTo32Bits(inputBuffer, inputOffset + 12) ^ _gSubKeys[INPUT_WHITEN + 3]; var k = ROUND_SUBKEYS; for (var r = 0; r < ROUNDS; r += 2) { - var t0 = Fe32_0(gSBox, x0); - var t1 = Fe32_3(gSBox, x1); - x2 ^= t0 + t1 + gSubKeys[k++]; + var t0 = Fe32_0(_gSBox, x0); + var t1 = Fe32_3(_gSBox, x1); + x2 ^= t0 + t1 + _gSubKeys[k++]; x2 = (int)((uint)x2 >> 1) | x2 << 31; - x3 = (x3 << 1 | (int)((uint)x3 >> 31)) ^ (t0 + 2 * t1 + gSubKeys[k++]); + x3 = (x3 << 1 | (int)((uint)x3 >> 31)) ^ (t0 + 2 * t1 + _gSubKeys[k++]); - t0 = Fe32_0(gSBox, x2); - t1 = Fe32_3(gSBox, x3); - x0 ^= t0 + t1 + gSubKeys[k++]; + t0 = Fe32_0(_gSBox, x2); + t1 = Fe32_3(_gSBox, x3); + x0 ^= t0 + t1 + _gSubKeys[k++]; x0 = (int)((uint)x0 >> 1) | x0 << 31; - x1 = (x1 << 1 | (int)((uint)x1 >> 31)) ^ (t0 + 2 * t1 + gSubKeys[k++]); + x1 = (x1 << 1 | (int)((uint)x1 >> 31)) ^ (t0 + 2 * t1 + _gSubKeys[k++]); } - Bits32ToBytes(x2 ^ gSubKeys[OUTPUT_WHITEN], outputBuffer, outputOffset); - Bits32ToBytes(x3 ^ gSubKeys[OUTPUT_WHITEN + 1], outputBuffer, outputOffset + 4); - Bits32ToBytes(x0 ^ gSubKeys[OUTPUT_WHITEN + 2], outputBuffer, outputOffset + 8); - Bits32ToBytes(x1 ^ gSubKeys[OUTPUT_WHITEN + 3], outputBuffer, outputOffset + 12); + Bits32ToBytes(x2 ^ _gSubKeys[OUTPUT_WHITEN], outputBuffer, outputOffset); + Bits32ToBytes(x3 ^ _gSubKeys[OUTPUT_WHITEN + 1], outputBuffer, outputOffset + 4); + Bits32ToBytes(x0 ^ _gSubKeys[OUTPUT_WHITEN + 2], outputBuffer, outputOffset + 8); + Bits32ToBytes(x1 ^ _gSubKeys[OUTPUT_WHITEN + 3], outputBuffer, outputOffset + 12); return BlockSize; } @@ -110,31 +110,31 @@ public override int EncryptBlock(byte[] inputBuffer, int inputOffset, int inputC /// public override int DecryptBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset) { - var x2 = BytesTo32Bits(inputBuffer, inputOffset) ^ gSubKeys[OUTPUT_WHITEN]; - var x3 = BytesTo32Bits(inputBuffer, inputOffset + 4) ^ gSubKeys[OUTPUT_WHITEN + 1]; - var x0 = BytesTo32Bits(inputBuffer, inputOffset + 8) ^ gSubKeys[OUTPUT_WHITEN + 2]; - var x1 = BytesTo32Bits(inputBuffer, inputOffset + 12) ^ gSubKeys[OUTPUT_WHITEN + 3]; + var x2 = BytesTo32Bits(inputBuffer, inputOffset) ^ _gSubKeys[OUTPUT_WHITEN]; + var x3 = BytesTo32Bits(inputBuffer, inputOffset + 4) ^ _gSubKeys[OUTPUT_WHITEN + 1]; + var x0 = BytesTo32Bits(inputBuffer, inputOffset + 8) ^ _gSubKeys[OUTPUT_WHITEN + 2]; + var x1 = BytesTo32Bits(inputBuffer, inputOffset + 12) ^ _gSubKeys[OUTPUT_WHITEN + 3]; var k = ROUND_SUBKEYS + 2 * ROUNDS - 1; for (var r = 0; r < ROUNDS; r += 2) { - var t0 = Fe32_0(gSBox, x2); - var t1 = Fe32_3(gSBox, x3); - x1 ^= t0 + 2 * t1 + gSubKeys[k--]; - x0 = (x0 << 1 | (int)((uint)x0 >> 31)) ^ (t0 + t1 + gSubKeys[k--]); + var t0 = Fe32_0(_gSBox, x2); + var t1 = Fe32_3(_gSBox, x3); + x1 ^= t0 + 2 * t1 + _gSubKeys[k--]; + x0 = (x0 << 1 | (int)((uint)x0 >> 31)) ^ (t0 + t1 + _gSubKeys[k--]); x1 = (int)((uint)x1 >> 1) | x1 << 31; - t0 = Fe32_0(gSBox, x0); - t1 = Fe32_3(gSBox, x1); - x3 ^= t0 + 2 * t1 + gSubKeys[k--]; - x2 = (x2 << 1 | (int)((uint)x2 >> 31)) ^ (t0 + t1 + gSubKeys[k--]); + t0 = Fe32_0(_gSBox, x0); + t1 = Fe32_3(_gSBox, x1); + x3 ^= t0 + 2 * t1 + _gSubKeys[k--]; + x2 = (x2 << 1 | (int)((uint)x2 >> 31)) ^ (t0 + t1 + _gSubKeys[k--]); x3 = (int)((uint)x3 >> 1) | x3 << 31; } - Bits32ToBytes(x0 ^ gSubKeys[INPUT_WHITEN], outputBuffer, outputOffset); - Bits32ToBytes(x1 ^ gSubKeys[INPUT_WHITEN + 1], outputBuffer, outputOffset + 4); - Bits32ToBytes(x2 ^ gSubKeys[INPUT_WHITEN + 2], outputBuffer, outputOffset + 8); - Bits32ToBytes(x3 ^ gSubKeys[INPUT_WHITEN + 3], outputBuffer, outputOffset + 12); + Bits32ToBytes(x0 ^ _gSubKeys[INPUT_WHITEN], outputBuffer, outputOffset); + Bits32ToBytes(x1 ^ _gSubKeys[INPUT_WHITEN + 1], outputBuffer, outputOffset + 4); + Bits32ToBytes(x2 ^ _gSubKeys[INPUT_WHITEN + 2], outputBuffer, outputOffset + 8); + Bits32ToBytes(x3 ^ _gSubKeys[INPUT_WHITEN + 3], outputBuffer, outputOffset + 12); return BlockSize; } @@ -228,19 +228,19 @@ public override int DecryptBlock(byte[] inputBuffer, int inputOffset, int inputC private const int SK_BUMP = 0x01010101; private const int SK_ROTL = 9; - private readonly int[] gMDS0 = new int[MAX_KEY_BITS]; - private readonly int[] gMDS1 = new int[MAX_KEY_BITS]; - private readonly int[] gMDS2 = new int[MAX_KEY_BITS]; - private readonly int[] gMDS3 = new int[MAX_KEY_BITS]; + private readonly int[] _gMDS0 = new int[MAX_KEY_BITS]; + private readonly int[] _gMDS1 = new int[MAX_KEY_BITS]; + private readonly int[] _gMDS2 = new int[MAX_KEY_BITS]; + private readonly int[] _gMDS3 = new int[MAX_KEY_BITS]; private readonly int _k64Cnt; /** - * gSubKeys[] and gSBox[] are eventually used in the + * _gSubKeys[] and _gSBox[] are eventually used in the * encryption and decryption methods. */ - private int[] gSubKeys; - private int[] gSBox; + private int[] _gSubKeys; + private int[] _gSBox; private void SetKey(byte[] key) { @@ -248,7 +248,7 @@ private void SetKey(byte[] key) var k32o = new int[MAX_KEY_BITS / 64]; // 4 var sBoxKeys = new int[MAX_KEY_BITS / 64]; // 4 - gSubKeys = new int[TOTAL_SUBKEYS]; + _gSubKeys = new int[TOTAL_SUBKEYS]; if (_k64Cnt < 1) { @@ -283,9 +283,9 @@ private void SetKey(byte[] key) var b = F32(q + SK_BUMP, k32o); b = b << 8 | (int)((uint)b >> 24); a += b; - gSubKeys[i * 2] = a; + _gSubKeys[i * 2] = a; a += b; - gSubKeys[i * 2 + 1] = a << SK_ROTL | (int)((uint)a >> (32 - SK_ROTL)); + _gSubKeys[i * 2 + 1] = a << SK_ROTL | (int)((uint)a >> (32 - SK_ROTL)); } /* @@ -295,18 +295,20 @@ private void SetKey(byte[] key) var k1 = sBoxKeys[1]; var k2 = sBoxKeys[2]; var k3 = sBoxKeys[3]; - gSBox = new int[4 * MAX_KEY_BITS]; + _gSBox = new int[4 * MAX_KEY_BITS]; for (var i = 0; i < MAX_KEY_BITS; i++) { int b1, b2, b3; var b0 = b1 = b2 = b3 = i; + +#pragma warning disable IDE0010 // Add missing cases switch (_k64Cnt & 3) { case 1: - gSBox[i * 2] = gMDS0[(P[P_01 * 256 + b0] & 0xff) ^ M_b0(k0)]; - gSBox[i * 2 + 1] = gMDS1[(P[P_11 * 256 + b1] & 0xff) ^ M_b1(k0)]; - gSBox[i * 2 + 0x200] = gMDS2[(P[P_21 * 256 + b2] & 0xff) ^ M_b2(k0)]; - gSBox[i * 2 + 0x201] = gMDS3[(P[P_31 * 256 + b3] & 0xff) ^ M_b3(k0)]; + _gSBox[i * 2] = _gMDS0[(P[P_01 * 256 + b0] & 0xff) ^ M_b0(k0)]; + _gSBox[i * 2 + 1] = _gMDS1[(P[P_11 * 256 + b1] & 0xff) ^ M_b1(k0)]; + _gSBox[i * 2 + 0x200] = _gMDS2[(P[P_21 * 256 + b2] & 0xff) ^ M_b2(k0)]; + _gSBox[i * 2 + 0x201] = _gMDS3[(P[P_31 * 256 + b3] & 0xff) ^ M_b3(k0)]; break; case 0: /* 256 bits of key */ b0 = (P[P_04 * 256 + b0] & 0xff) ^ M_b0(k3); @@ -321,12 +323,13 @@ private void SetKey(byte[] key) b3 = (P[P_33 * 256 + b3] & 0xff) ^ M_b3(k2); goto case 2; case 2: - gSBox[i * 2] = gMDS0[(P[P_01 * 256 + (P[P_02 * 256 + b0] & 0xff) ^ M_b0(k1)] & 0xff) ^ M_b0(k0)]; - gSBox[i * 2 + 1] = gMDS1[(P[P_11 * 256 + (P[P_12 * 256 + b1] & 0xff) ^ M_b1(k1)] & 0xff) ^ M_b1(k0)]; - gSBox[i * 2 + 0x200] = gMDS2[(P[P_21 * 256 + (P[P_22 * 256 + b2] & 0xff) ^ M_b2(k1)] & 0xff) ^ M_b2(k0)]; - gSBox[i * 2 + 0x201] = gMDS3[(P[P_31 * 256 + (P[P_32 * 256 + b3] & 0xff) ^ M_b3(k1)] & 0xff) ^ M_b3(k0)]; + _gSBox[i * 2] = _gMDS0[(P[P_01 * 256 + (P[P_02 * 256 + b0] & 0xff) ^ M_b0(k1)] & 0xff) ^ M_b0(k0)]; + _gSBox[i * 2 + 1] = _gMDS1[(P[P_11 * 256 + (P[P_12 * 256 + b1] & 0xff) ^ M_b1(k1)] & 0xff) ^ M_b1(k0)]; + _gSBox[i * 2 + 0x200] = _gMDS2[(P[P_21 * 256 + (P[P_22 * 256 + b2] & 0xff) ^ M_b2(k1)] & 0xff) ^ M_b2(k0)]; + _gSBox[i * 2 + 0x201] = _gMDS3[(P[P_31 * 256 + (P[P_32 * 256 + b3] & 0xff) ^ M_b3(k1)] & 0xff) ^ M_b3(k0)]; break; } +#pragma warning restore IDE0010 // Add missing cases } /* @@ -352,13 +355,15 @@ private int F32(int x, int[] k32) var k3 = k32[3]; var result = 0; + +#pragma warning disable IDE0010 // Add missing cases switch (_k64Cnt & 3) { case 1: - result = gMDS0[(P[P_01 * 256 + b0] & 0xff) ^ M_b0(k0)] ^ - gMDS1[(P[P_11 * 256 + b1] & 0xff) ^ M_b1(k0)] ^ - gMDS2[(P[P_21 * 256 + b2] & 0xff) ^ M_b2(k0)] ^ - gMDS3[(P[P_31 * 256 + b3] & 0xff) ^ M_b3(k0)]; + result = _gMDS0[(P[P_01 * 256 + b0] & 0xff) ^ M_b0(k0)] ^ + _gMDS1[(P[P_11 * 256 + b1] & 0xff) ^ M_b1(k0)] ^ + _gMDS2[(P[P_21 * 256 + b2] & 0xff) ^ M_b2(k0)] ^ + _gMDS3[(P[P_31 * 256 + b3] & 0xff) ^ M_b3(k0)]; break; case 0: /* 256 bits of key */ b0 = (P[P_04 * 256 + b0] & 0xff) ^ M_b0(k3); @@ -374,12 +379,13 @@ private int F32(int x, int[] k32) goto case 2; case 2: result = - gMDS0[(P[P_01 * 256 + (P[P_02 * 256 + b0] & 0xff) ^ M_b0(k1)] & 0xff) ^ M_b0(k0)] ^ - gMDS1[(P[P_11 * 256 + (P[P_12 * 256 + b1] & 0xff) ^ M_b1(k1)] & 0xff) ^ M_b1(k0)] ^ - gMDS2[(P[P_21 * 256 + (P[P_22 * 256 + b2] & 0xff) ^ M_b2(k1)] & 0xff) ^ M_b2(k0)] ^ - gMDS3[(P[P_31 * 256 + (P[P_32 * 256 + b3] & 0xff) ^ M_b3(k1)] & 0xff) ^ M_b3(k0)]; + _gMDS0[(P[P_01 * 256 + (P[P_02 * 256 + b0] & 0xff) ^ M_b0(k1)] & 0xff) ^ M_b0(k0)] ^ + _gMDS1[(P[P_11 * 256 + (P[P_12 * 256 + b1] & 0xff) ^ M_b1(k1)] & 0xff) ^ M_b1(k0)] ^ + _gMDS2[(P[P_21 * 256 + (P[P_22 * 256 + b2] & 0xff) ^ M_b2(k1)] & 0xff) ^ M_b2(k0)] ^ + _gMDS3[(P[P_31 * 256 + (P[P_32 * 256 + b3] & 0xff) ^ M_b3(k1)] & 0xff) ^ M_b3(k0)]; break; } +#pragma warning restore IDE0010 // Add missing cases return result; } @@ -423,24 +429,19 @@ private static int RS_MDS_Encode(int k0, int k1) private static int RS_rem(int x) { var b = (int)(((uint)x >> 24) & 0xff); - var g2 = ((b << 1) ^ - ((b & 0x80) != 0 ? RS_GF_FDBK : 0)) & 0xff; - var g3 = ((int)((uint)b >> 1) ^ - ((b & 0x01) != 0 ? (int)((uint)RS_GF_FDBK >> 1) : 0)) ^ g2; + var g2 = ((b << 1) ^ ((b & 0x80) != 0 ? RS_GF_FDBK : 0)) & 0xff; + var g3 = ((int)((uint)b >> 1) ^ ((b & 0x01) != 0 ? (int)((uint)RS_GF_FDBK >> 1) : 0)) ^ g2; return (x << 8) ^ (g3 << 24) ^ (g2 << 16) ^ (g3 << 8) ^ b; } private static int LFSR1(int x) { - return (x >> 1) ^ - (((x & 0x01) != 0) ? GF256_FDBK_2 : 0); + return (x >> 1) ^ (((x & 0x01) != 0) ? GF256_FDBK_2 : 0); } private static int LFSR2(int x) { - return (x >> 2) ^ - (((x & 0x02) != 0) ? GF256_FDBK_2 : 0) ^ - (((x & 0x01) != 0) ? GF256_FDBK_4 : 0); + return (x >> 2) ^ (((x & 0x02) != 0) ? GF256_FDBK_2 : 0) ^ (((x & 0x01) != 0) ? GF256_FDBK_4 : 0); } private static int Mx_X(int x) @@ -453,22 +454,30 @@ private static int Mx_Y(int x) return x ^ LFSR1(x) ^ LFSR2(x); } // EF +#pragma warning disable IDE1006 // Naming Styles private static int M_b0(int x) +#pragma warning restore IDE1006 // Naming Styles { return x & 0xff; } +#pragma warning disable IDE1006 // Naming Styles private static int M_b1(int x) +#pragma warning restore IDE1006 // Naming Styles { return (int)((uint)x >> 8) & 0xff; } +#pragma warning disable IDE1006 // Naming Styles private static int M_b2(int x) +#pragma warning restore IDE1006 // Naming Styles { return (int)((uint)x >> 16) & 0xff; } +#pragma warning disable IDE1006 // Naming Styles private static int M_b3(int x) +#pragma warning restore IDE1006 // Naming Styles { return (int)((uint)x >> 24) & 0xff; } diff --git a/src/Renci.SshNet/Security/Cryptography/DsaDigitalSignature.cs b/src/Renci.SshNet/Security/Cryptography/DsaDigitalSignature.cs index be84f7f83..467a5e0a7 100644 --- a/src/Renci.SshNet/Security/Cryptography/DsaDigitalSignature.cs +++ b/src/Renci.SshNet/Security/Cryptography/DsaDigitalSignature.cs @@ -22,7 +22,7 @@ public class DsaDigitalSignature : DigitalSignature, IDisposable /// is null. public DsaDigitalSignature(DsaKey key) { - if (key == null) + if (key is null) { throw new ArgumentNullException(nameof(key)); } diff --git a/src/Renci.SshNet/Security/Cryptography/DsaKey.cs b/src/Renci.SshNet/Security/Cryptography/DsaKey.cs index bfb185a65..d9664bdd9 100644 --- a/src/Renci.SshNet/Security/Cryptography/DsaKey.cs +++ b/src/Renci.SshNet/Security/Cryptography/DsaKey.cs @@ -147,12 +147,7 @@ public DsaKey(byte[] data) /// The x. public DsaKey(BigInteger p, BigInteger q, BigInteger g, BigInteger y, BigInteger x) { - _privateKey = new BigInteger[5]; - _privateKey[0] = p; - _privateKey[1] = q; - _privateKey[2] = g; - _privateKey[3] = y; - _privateKey[4] = x; + _privateKey = new BigInteger[5] { p, q, g, y, x }; } /// diff --git a/src/Renci.SshNet/Security/Cryptography/ED25519DigitalSignature.cs b/src/Renci.SshNet/Security/Cryptography/ED25519DigitalSignature.cs index 4e32772e2..c777f4d48 100644 --- a/src/Renci.SshNet/Security/Cryptography/ED25519DigitalSignature.cs +++ b/src/Renci.SshNet/Security/Cryptography/ED25519DigitalSignature.cs @@ -19,7 +19,7 @@ public class ED25519DigitalSignature : DigitalSignature, IDisposable /// is null. public ED25519DigitalSignature(ED25519Key key) { - if (key == null) + if (key is null) { throw new ArgumentNullException(nameof(key)); } diff --git a/src/Renci.SshNet/Security/Cryptography/ED25519Key.cs b/src/Renci.SshNet/Security/Cryptography/ED25519Key.cs index 8e0862f4d..99892fa59 100644 --- a/src/Renci.SshNet/Security/Cryptography/ED25519Key.cs +++ b/src/Renci.SshNet/Security/Cryptography/ED25519Key.cs @@ -13,8 +13,10 @@ public class ED25519Key : Key, IDisposable { private ED25519DigitalSignature _digitalSignature; - private byte[] publicKey = new byte[Ed25519.PublicKeySizeInBytes]; + private byte[] _publicKey = new byte[Ed25519.PublicKeySizeInBytes]; +#pragma warning disable IDE1006 // Naming Styles private readonly byte[] privateKey = new byte[Ed25519.ExpandedPrivateKeySizeInBytes]; +#pragma warning restore IDE1006 // Naming Styles private bool _isDisposed; /// @@ -35,11 +37,11 @@ public override BigInteger[] Public { get { - return new BigInteger[] { publicKey.ToBigInteger2() }; + return new BigInteger[] { _publicKey.ToBigInteger2() }; } set { - publicKey = value[0].ToByteArray().Reverse().TrimLeadingZeros().Pad(Ed25519.PublicKeySizeInBytes); + _publicKey = value[0].ToByteArray().Reverse().TrimLeadingZeros().Pad(Ed25519.PublicKeySizeInBytes); } } @@ -76,7 +78,7 @@ public byte[] PublicKey { get { - return publicKey; + return _publicKey; } } @@ -104,7 +106,7 @@ public ED25519Key() /// pk data. public ED25519Key(byte[] pk) { - publicKey = pk.TrimLeadingZeros().Pad(Ed25519.PublicKeySizeInBytes); + _publicKey = pk.TrimLeadingZeros().Pad(Ed25519.PublicKeySizeInBytes); } /// @@ -114,10 +116,10 @@ public ED25519Key(byte[] pk) /// sk data. public ED25519Key(byte[] pk, byte[] sk) { - publicKey = pk.TrimLeadingZeros().Pad(Ed25519.PublicKeySizeInBytes); + _publicKey = pk.TrimLeadingZeros().Pad(Ed25519.PublicKeySizeInBytes); var seed = new byte[Ed25519.PrivateKeySeedSizeInBytes]; Buffer.BlockCopy(sk, 0, seed, 0, seed.Length); - Ed25519.KeyPairFromSeed(out publicKey, out privateKey, seed); + Ed25519.KeyPairFromSeed(out _publicKey, out privateKey, seed); } /// diff --git a/src/Renci.SshNet/Security/Cryptography/EcdsaDigitalSignature.cs b/src/Renci.SshNet/Security/Cryptography/EcdsaDigitalSignature.cs index e358c1ecf..48446c52d 100644 --- a/src/Renci.SshNet/Security/Cryptography/EcdsaDigitalSignature.cs +++ b/src/Renci.SshNet/Security/Cryptography/EcdsaDigitalSignature.cs @@ -23,7 +23,7 @@ public class EcdsaDigitalSignature : DigitalSignature, IDisposable /// is null. public EcdsaDigitalSignature(EcdsaKey key) { - if (key == null) + if (key is null) { throw new ArgumentNullException(nameof(key)); } diff --git a/src/Renci.SshNet/Security/Cryptography/EcdsaKey.cs b/src/Renci.SshNet/Security/Cryptography/EcdsaKey.cs index 0a5da1963..3de4beac5 100644 --- a/src/Renci.SshNet/Security/Cryptography/EcdsaKey.cs +++ b/src/Renci.SshNet/Security/Cryptography/EcdsaKey.cs @@ -26,6 +26,8 @@ public class EcdsaKey : Key, IDisposable private bool _isDisposed; #if NETFRAMEWORK + private CngKey _key; + internal enum KeyBlobMagicNumber : int { BCRYPT_ECDSA_PUBLIC_P256_MAGIC = 0x31534345, @@ -52,8 +54,6 @@ internal struct BCRYPT_ECCKEY_BLOB internal KeyBlobMagicNumber Magic; internal int cbKey; } - - private CngKey key; #endif /// @@ -104,9 +104,9 @@ public HashAlgorithmName HashAlgorithm return HashAlgorithmName.SHA384; case 521: return HashAlgorithmName.SHA512; + default: + return HashAlgorithmName.SHA256; } - - return HashAlgorithmName.SHA256; } } #endif @@ -152,7 +152,7 @@ public override BigInteger[] Public byte[] qx; byte[] qy; #if NETFRAMEWORK - var blob = key.Export(CngKeyBlobFormat.EccPublicBlob); + var blob = _key.Export(CngKeyBlobFormat.EccPublicBlob); KeyBlobMagicNumber magic; using (var br = new BinaryReader(new MemoryStream(blob))) @@ -163,6 +163,7 @@ public override BigInteger[] Public qy = br.ReadBytes(cbKey); } +#pragma warning disable IDE0010 // Add missing cases switch (magic) { case KeyBlobMagicNumber.BCRYPT_ECDSA_PUBLIC_P256_MAGIC: @@ -177,6 +178,7 @@ public override BigInteger[] Public default: throw new SshException("Unexpected Curve Magic: " + magic); } +#pragma warning restore IDE0010 // Add missing cases #else var parameter = Ecdsa.ExportParameters(false); qx = parameter.Q.X; @@ -377,9 +379,9 @@ private void Import(string curve_oid, byte[] publickey, byte[] privatekey) bw.Write(privatekey); // d } } - key = CngKey.Import(blob, privatekey == null ? CngKeyBlobFormat.EccPublicBlob : CngKeyBlobFormat.EccPrivateBlob); + _key = CngKey.Import(blob, privatekey is null ? CngKeyBlobFormat.EccPublicBlob : CngKeyBlobFormat.EccPrivateBlob); - Ecdsa = new ECDsaCng(key); + Ecdsa = new ECDsaCng(_key); #else var curve = ECCurve.CreateFromValue(curve_oid); var parameter = new ECParameters diff --git a/src/Renci.SshNet/Security/Cryptography/Key.cs b/src/Renci.SshNet/Security/Cryptography/Key.cs index 6f5a6312b..e23673b1e 100644 --- a/src/Renci.SshNet/Security/Cryptography/Key.cs +++ b/src/Renci.SshNet/Security/Cryptography/Key.cs @@ -48,7 +48,7 @@ public abstract class Key /// DER encoded private key data. protected Key(byte[] data) { - if (data == null) + if (data is null) { throw new ArgumentNullException(nameof(data)); } diff --git a/src/Renci.SshNet/Security/Cryptography/RsaDigitalSignature.cs b/src/Renci.SshNet/Security/Cryptography/RsaDigitalSignature.cs index 15ac6c056..25a375f6b 100644 --- a/src/Renci.SshNet/Security/Cryptography/RsaDigitalSignature.cs +++ b/src/Renci.SshNet/Security/Cryptography/RsaDigitalSignature.cs @@ -55,7 +55,9 @@ public void Dispose() protected virtual void Dispose(bool disposing) { if (_isDisposed) + { return; + } if (disposing) { diff --git a/src/Renci.SshNet/Security/Cryptography/RsaKey.cs b/src/Renci.SshNet/Security/Cryptography/RsaKey.cs index b80e4302c..6d0180114 100644 --- a/src/Renci.SshNet/Security/Cryptography/RsaKey.cs +++ b/src/Renci.SshNet/Security/Cryptography/RsaKey.cs @@ -9,6 +9,7 @@ namespace Renci.SshNet.Security /// public class RsaKey : Key, IDisposable { + private bool _isDisposed; /// /// Gets the Key String. @@ -48,7 +49,10 @@ public BigInteger D get { if (_privateKey.Length > 2) + { return _privateKey[2]; + } + return BigInteger.Zero; } } @@ -61,7 +65,11 @@ public BigInteger P get { if (_privateKey.Length > 3) + { return _privateKey[3]; + } + + return BigInteger.Zero; } } @@ -74,7 +82,10 @@ public BigInteger Q get { if (_privateKey.Length > 4) + { return _privateKey[4]; + } + return BigInteger.Zero; } } @@ -87,7 +98,10 @@ public BigInteger DP get { if (_privateKey.Length > 5) + { return _privateKey[5]; + } + return BigInteger.Zero; } } @@ -100,7 +114,10 @@ public BigInteger DQ get { if (_privateKey.Length > 6) + { return _privateKey[6]; + } + return BigInteger.Zero; } } @@ -113,7 +130,10 @@ public BigInteger InverseQ get { if (_privateKey.Length > 7) + { return _privateKey[7]; + } + return BigInteger.Zero; } } @@ -140,10 +160,8 @@ protected override DigitalSignature DigitalSignature { get { - if (_digitalSignature == null) - { - _digitalSignature = new RsaDigitalSignature(this); - } + _digitalSignature ??= new RsaDigitalSignature(this); + return _digitalSignature; } } @@ -163,7 +181,9 @@ public override BigInteger[] Public set { if (value.Length != 2) + { throw new InvalidOperationException("Invalid private key."); + } _privateKey = new[] { value[1], value[0] }; } @@ -184,7 +204,9 @@ public RsaKey(byte[] data) : base(data) { if (_privateKey.Length != 8) + { throw new InvalidOperationException("Invalid private key."); + } } /// @@ -198,15 +220,17 @@ public RsaKey(byte[] data) /// The inverse Q. public RsaKey(BigInteger modulus, BigInteger exponent, BigInteger d, BigInteger p, BigInteger q, BigInteger inverseQ) { - _privateKey = new BigInteger[8]; - _privateKey[0] = modulus; - _privateKey[1] = exponent; - _privateKey[2] = d; - _privateKey[3] = p; - _privateKey[4] = q; - _privateKey[5] = PrimeExponent(d, p); - _privateKey[6] = PrimeExponent(d, q); - _privateKey[7] = inverseQ; + _privateKey = new BigInteger[8] + { + modulus, + exponent, + d, + p, + q, + PrimeExponent(d, p), + PrimeExponent(d, q), + inverseQ + }; } private static BigInteger PrimeExponent(BigInteger privateExponent, BigInteger prime) @@ -215,10 +239,6 @@ private static BigInteger PrimeExponent(BigInteger privateExponent, BigInteger p return privateExponent % pe; } - #region IDisposable Members - - private bool _isDisposed; - /// /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// @@ -235,7 +255,9 @@ public void Dispose() protected virtual void Dispose(bool disposing) { if (_isDisposed) + { return; + } if (disposing) { @@ -258,7 +280,5 @@ protected virtual void Dispose(bool disposing) { Dispose(false); } - - #endregion } } diff --git a/src/Renci.SshNet/Security/Cryptography/SymmetricCipher.cs b/src/Renci.SshNet/Security/Cryptography/SymmetricCipher.cs index f4e35c375..667492501 100644 --- a/src/Renci.SshNet/Security/Cryptography/SymmetricCipher.cs +++ b/src/Renci.SshNet/Security/Cryptography/SymmetricCipher.cs @@ -19,7 +19,7 @@ public abstract class SymmetricCipher : Cipher /// is null. protected SymmetricCipher(byte[] key) { - if (key == null) + if (key is null) { throw new ArgumentNullException(nameof(key)); } diff --git a/src/Renci.SshNet/Security/KeyExchange.cs b/src/Renci.SshNet/Security/KeyExchange.cs index 92a61973f..194358271 100644 --- a/src/Renci.SshNet/Security/KeyExchange.cs +++ b/src/Renci.SshNet/Security/KeyExchange.cs @@ -49,10 +49,7 @@ public byte[] ExchangeHash { get { - if (_exchangeHash == null) - { - _exchangeHash = CalculateHash(); - } + _exchangeHash ??= CalculateHash(); return _exchangeHash; } @@ -262,7 +259,7 @@ public HashAlgorithm CreateClientHash() /// public Compressor CreateCompressor() { - if (_compressionType == null) + if (_compressionType is null) { return null; } @@ -282,7 +279,7 @@ public Compressor CreateCompressor() /// public Compressor CreateDecompressor() { - if (_decompressionType == null) + if (_decompressionType is null) { return null; } diff --git a/src/Renci.SshNet/ServiceFactory.cs b/src/Renci.SshNet/ServiceFactory.cs index 42e541f0b..210df0229 100644 --- a/src/Renci.SshNet/ServiceFactory.cs +++ b/src/Renci.SshNet/ServiceFactory.cs @@ -92,12 +92,12 @@ public PipeStream CreatePipeStream() /// No key exchange algorithms are supported by both client and server. public IKeyExchange CreateKeyExchange(IDictionary clientAlgorithms, string[] serverAlgorithms) { - if (clientAlgorithms == null) + if (clientAlgorithms is null) { throw new ArgumentNullException(nameof(clientAlgorithms)); } - if (serverAlgorithms == null) + if (serverAlgorithms is null) { throw new ArgumentNullException(nameof(serverAlgorithms)); } @@ -108,7 +108,7 @@ from s in serverAlgorithms where s == c.Key select c.Value).FirstOrDefault(); - if (keyExchangeAlgorithmType == null) + if (keyExchangeAlgorithmType is null) { throw new SshConnectionException("Failed to negotiate key exchange algorithm.", DisconnectReason.KeyExchangeFailed); } @@ -215,12 +215,12 @@ public IRemotePathTransformation CreateRemotePathDoubleQuoteTransformation() /// The value of is not supported. public IConnector CreateConnector(IConnectionInfo connectionInfo, ISocketFactory socketFactory) { - if (connectionInfo == null) + if (connectionInfo is null) { throw new ArgumentNullException(nameof(connectionInfo)); } - if (socketFactory == null) + if (socketFactory is null) { throw new ArgumentNullException(nameof(socketFactory)); } diff --git a/src/Renci.SshNet/Session.cs b/src/Renci.SshNet/Session.cs index 17dd51256..02013bd22 100644 --- a/src/Renci.SshNet/Session.cs +++ b/src/Renci.SshNet/Session.cs @@ -207,14 +207,11 @@ public SemaphoreLight SessionSemaphore { get { - if (_sessionSemaphore == null) + if (_sessionSemaphore is null) { lock (this) { - if (_sessionSemaphore == null) - { - _sessionSemaphore = new SemaphoreLight(ConnectionInfo.MaxSessions); - } + _sessionSemaphore ??= new SemaphoreLight(ConnectionInfo.MaxSessions); } } @@ -282,7 +279,7 @@ public bool IsConnected return false; } - if (_messageListenerCompleted == null || _messageListenerCompleted.WaitOne(0)) + if (_messageListenerCompleted is null || _messageListenerCompleted.WaitOne(0)) { return false; } @@ -309,24 +306,21 @@ public Message ClientInitMessage { get { - if (_clientInitMessage == null) - { - _clientInitMessage = new KeyExchangeInitMessage - { - KeyExchangeAlgorithms = ConnectionInfo.KeyExchangeAlgorithms.Keys.ToArray(), - ServerHostKeyAlgorithms = ConnectionInfo.HostKeyAlgorithms.Keys.ToArray(), - EncryptionAlgorithmsClientToServer = ConnectionInfo.Encryptions.Keys.ToArray(), - EncryptionAlgorithmsServerToClient = ConnectionInfo.Encryptions.Keys.ToArray(), - MacAlgorithmsClientToServer = ConnectionInfo.HmacAlgorithms.Keys.ToArray(), - MacAlgorithmsServerToClient = ConnectionInfo.HmacAlgorithms.Keys.ToArray(), - CompressionAlgorithmsClientToServer = ConnectionInfo.CompressionAlgorithms.Keys.ToArray(), - CompressionAlgorithmsServerToClient = ConnectionInfo.CompressionAlgorithms.Keys.ToArray(), - LanguagesClientToServer = new[] { string.Empty }, - LanguagesServerToClient = new[] { string.Empty }, - FirstKexPacketFollows = false, - Reserved = 0 - }; - } + _clientInitMessage ??= new KeyExchangeInitMessage + { + KeyExchangeAlgorithms = ConnectionInfo.KeyExchangeAlgorithms.Keys.ToArray(), + ServerHostKeyAlgorithms = ConnectionInfo.HostKeyAlgorithms.Keys.ToArray(), + EncryptionAlgorithmsClientToServer = ConnectionInfo.Encryptions.Keys.ToArray(), + EncryptionAlgorithmsServerToClient = ConnectionInfo.Encryptions.Keys.ToArray(), + MacAlgorithmsClientToServer = ConnectionInfo.HmacAlgorithms.Keys.ToArray(), + MacAlgorithmsServerToClient = ConnectionInfo.HmacAlgorithms.Keys.ToArray(), + CompressionAlgorithmsClientToServer = ConnectionInfo.CompressionAlgorithms.Keys.ToArray(), + CompressionAlgorithmsServerToClient = ConnectionInfo.CompressionAlgorithms.Keys.ToArray(), + LanguagesClientToServer = new[] { string.Empty }, + LanguagesServerToClient = new[] { string.Empty }, + FirstKexPacketFollows = false, + Reserved = 0 + }; return _clientInitMessage; } @@ -547,17 +541,17 @@ public Message ClientInitMessage /// is null. internal Session(ConnectionInfo connectionInfo, IServiceFactory serviceFactory, ISocketFactory socketFactory) { - if (connectionInfo == null) + if (connectionInfo is null) { throw new ArgumentNullException(nameof(connectionInfo)); } - if (serviceFactory == null) + if (serviceFactory is null) { throw new ArgumentNullException(nameof(serviceFactory)); } - if (socketFactory == null) + if (socketFactory is null) { throw new ArgumentNullException(nameof(socketFactory)); } @@ -641,13 +635,13 @@ public void Connect() // Start incoming request listener // ToDo: Make message pump async, to not consume a thread for every session - ThreadAbstraction.ExecuteThreadLongRunning(() => MessageListener()); + ThreadAbstraction.ExecuteThreadLongRunning(MessageListener); // Wait for key exchange to be completed WaitOnHandle(_keyExchangeCompletedWaitHandle); // If sessionId is not set then its not connected - if (SessionId == null) + if (SessionId is null) { Disconnect(); return; @@ -753,13 +747,13 @@ public async Task ConnectAsync(CancellationToken cancellationToken) // Start incoming request listener // ToDo: Make message pump async, to not consume a thread for every session - ThreadAbstraction.ExecuteThreadLongRunning(() => MessageListener()); + ThreadAbstraction.ExecuteThreadLongRunning(MessageListener); // Wait for key exchange to be completed WaitOnHandle(_keyExchangeCompletedWaitHandle); // If sessionId is not set then its not connected - if (SessionId == null) + if (SessionId is null) { Disconnect(); return; @@ -934,7 +928,7 @@ WaitResult ISession.TryWait(WaitHandle waitHandle, TimeSpan timeout, out Excepti /// private WaitResult TryWait(WaitHandle waitHandle, TimeSpan timeout, out Exception exception) { - if (waitHandle == null) + if (waitHandle is null) { throw new ArgumentNullException(nameof(waitHandle)); } @@ -982,7 +976,7 @@ private WaitResult TryWait(WaitHandle waitHandle, TimeSpan timeout, out Exceptio /// A socket error was signaled while receiving messages from the server. internal void WaitOnHandle(WaitHandle waitHandle, TimeSpan timeout) { - if (waitHandle == null) + if (waitHandle is null) { throw new ArgumentNullException(nameof(waitHandle)); } @@ -994,12 +988,16 @@ internal void WaitOnHandle(WaitHandle waitHandle, TimeSpan timeout) waitHandle }; - switch (WaitHandle.WaitAny(waitHandles, timeout)) + var signaledElement = WaitHandle.WaitAny(waitHandles, timeout); + switch (signaledElement) { case 0: throw _exception; case 1: throw new SshConnectionException("Client not connected."); + case 2: + // Specified waithandle was signaled + break; case WaitHandle.WaitTimeout: // when the session is disconnecting, a timeout is likely when no // network connectivity is available; depending on the configured @@ -1013,6 +1011,8 @@ internal void WaitOnHandle(WaitHandle waitHandle, TimeSpan timeout) } break; + default: + throw new SshException($"Unexpected element '{signaledElement.ToString(CultureInfo.InvariantCulture)}' signaled."); } } @@ -1038,7 +1038,7 @@ internal void SendMessage(Message message) DiagnosticAbstraction.Log(string.Format("[{0}] Sending message '{1}' to server: '{2}'.", ToHex(SessionId), message.GetType().Name, message)); - var paddingMultiplier = _clientCipher == null ? (byte) 8 : Math.Max((byte) 8, _serverCipher.MinimumSize); + var paddingMultiplier = _clientCipher is null ? (byte) 8 : Math.Max((byte) 8, _serverCipher.MinimumSize); var packetData = message.GetPacket(paddingMultiplier, _clientCompression); // take a write lock to ensure the outbound packet sequence number is incremented @@ -1070,7 +1070,7 @@ internal void SendMessage(Message message) } var packetLength = packetData.Length - packetDataOffset; - if (hash == null) + if (hash is null) { SendPacket(packetData, packetDataOffset, packetLength); } @@ -1174,7 +1174,7 @@ private Message ReceiveMessage(Socket socket) const int paddingLengthFieldLength = 1; // Determine the size of the first block, which is 8 or cipher block size (whichever is larger) bytes - var blockSize = _serverCipher == null ? (byte) 8 : Math.Max((byte) 8, _serverCipher.MinimumSize); + var blockSize = _serverCipher is null ? (byte) 8 : Math.Max((byte) 8, _serverCipher.MinimumSize); var serverMacLength = _serverMac != null ? _serverMac.HashSize/8 : 0; @@ -1708,7 +1708,7 @@ private static string ToHex(byte[] bytes, int offset) internal static string ToHex(byte[] bytes) { - if (bytes == null) + if (bytes is null) { return null; } @@ -1842,7 +1842,7 @@ private void MessageListener() { var socket = _socket; - if (socket == null || !socket.Connected) + if (socket is null || !socket.Connected) { break; } @@ -1867,7 +1867,7 @@ private void MessageListener() } var message = ReceiveMessage(socket); - if (message == null) + if (message is null) { // connection with SSH server was closed; // break out of the message loop diff --git a/src/Renci.SshNet/Sftp/Requests/ExtendedRequests/FStatVfsRequest.cs b/src/Renci.SshNet/Sftp/Requests/ExtendedRequests/FStatVfsRequest.cs index 06eeef1e2..49341e89a 100644 --- a/src/Renci.SshNet/Sftp/Requests/ExtendedRequests/FStatVfsRequest.cs +++ b/src/Renci.SshNet/Sftp/Requests/ExtendedRequests/FStatVfsRequest.cs @@ -1,4 +1,5 @@ using System; + using Renci.SshNet.Sftp.Responses; namespace Renci.SshNet.Sftp.Requests diff --git a/src/Renci.SshNet/Sftp/Requests/ExtendedRequests/HardLinkRequest.cs b/src/Renci.SshNet/Sftp/Requests/ExtendedRequests/HardLinkRequest.cs index 963249d22..cd744f0e2 100644 --- a/src/Renci.SshNet/Sftp/Requests/ExtendedRequests/HardLinkRequest.cs +++ b/src/Renci.SshNet/Sftp/Requests/ExtendedRequests/HardLinkRequest.cs @@ -1,4 +1,5 @@ using System; + using Renci.SshNet.Sftp.Responses; namespace Renci.SshNet.Sftp.Requests diff --git a/src/Renci.SshNet/Sftp/Requests/SftpMkDirRequest.cs b/src/Renci.SshNet/Sftp/Requests/SftpMkDirRequest.cs index 752e88c1d..126925b95 100644 --- a/src/Renci.SshNet/Sftp/Requests/SftpMkDirRequest.cs +++ b/src/Renci.SshNet/Sftp/Requests/SftpMkDirRequest.cs @@ -28,10 +28,7 @@ private byte[] AttributesBytes { get { - if (_attributesBytes == null) - { - _attributesBytes = Attributes.GetBytes(); - } + _attributesBytes ??= Attributes.GetBytes(); return _attributesBytes; } diff --git a/src/Renci.SshNet/Sftp/Requests/SftpRealPathRequest.cs b/src/Renci.SshNet/Sftp/Requests/SftpRealPathRequest.cs index 52e57bbe3..d19497f0b 100644 --- a/src/Renci.SshNet/Sftp/Requests/SftpRealPathRequest.cs +++ b/src/Renci.SshNet/Sftp/Requests/SftpRealPathRequest.cs @@ -43,7 +43,7 @@ protected override int BufferCapacity public SftpRealPathRequest(uint protocolVersion, uint requestId, string path, Encoding encoding, Action nameAction, Action statusAction) : base(protocolVersion, requestId, statusAction) { - if (nameAction == null) + if (nameAction is null) { throw new ArgumentNullException(nameof(nameAction)); } diff --git a/src/Renci.SshNet/Sftp/Requests/SftpSetStatRequest.cs b/src/Renci.SshNet/Sftp/Requests/SftpSetStatRequest.cs index 9f44a92a6..8731b9fc6 100644 --- a/src/Renci.SshNet/Sftp/Requests/SftpSetStatRequest.cs +++ b/src/Renci.SshNet/Sftp/Requests/SftpSetStatRequest.cs @@ -28,10 +28,8 @@ private byte[] AttributesBytes { get { - if (_attributesBytes == null) - { - _attributesBytes = Attributes.GetBytes(); - } + _attributesBytes ??= Attributes.GetBytes(); + return _attributesBytes; } } diff --git a/src/Renci.SshNet/Sftp/SftpFile.cs b/src/Renci.SshNet/Sftp/SftpFile.cs index 07d1039e1..b5fe3af36 100644 --- a/src/Renci.SshNet/Sftp/SftpFile.cs +++ b/src/Renci.SshNet/Sftp/SftpFile.cs @@ -25,17 +25,17 @@ public sealed class SftpFile : ISftpFile /// or is null. internal SftpFile(ISftpSession sftpSession, string fullName, SftpFileAttributes attributes) { - if (sftpSession == null) + if (sftpSession is null) { throw new SshConnectionException("Client not connected."); } - if (attributes == null) + if (attributes is null) { throw new ArgumentNullException(nameof(attributes)); } - if (fullName == null) + if (fullName is null) { throw new ArgumentNullException(nameof(fullName)); } @@ -481,7 +481,7 @@ public void Delete() /// is null. public void MoveTo(string destFileName) { - if (destFileName == null) + if (destFileName is null) { throw new ArgumentNullException(nameof(destFileName)); } diff --git a/src/Renci.SshNet/Sftp/SftpFileAttributes.cs b/src/Renci.SshNet/Sftp/SftpFileAttributes.cs index 901d6ee5a..e0cea9dba 100644 --- a/src/Renci.SshNet/Sftp/SftpFileAttributes.cs +++ b/src/Renci.SshNet/Sftp/SftpFileAttributes.cs @@ -12,45 +12,28 @@ namespace Renci.SshNet.Sftp /// public class SftpFileAttributes { +#pragma warning disable IDE1006 // Naming Styles private const uint S_IFMT = 0xF000; // bitmask for the file type bitfields - private const uint S_IFSOCK = 0xC000; // socket - private const uint S_IFLNK = 0xA000; // symbolic link - private const uint S_IFREG = 0x8000; // regular file - private const uint S_IFBLK = 0x6000; // block device - private const uint S_IFDIR = 0x4000; // directory - private const uint S_IFCHR = 0x2000; // character device - private const uint S_IFIFO = 0x1000; // FIFO - private const uint S_ISUID = 0x0800; // set UID bit - private const uint S_ISGID = 0x0400; // set-group-ID bit (see below) - private const uint S_ISVTX = 0x0200; // sticky bit (see below) - private const uint S_IRUSR = 0x0100; // owner has read permission - private const uint S_IWUSR = 0x0080; // owner has write permission - private const uint S_IXUSR = 0x0040; // owner has execute permission - private const uint S_IRGRP = 0x0020; // group has read permission - private const uint S_IWGRP = 0x0010; // group has write permission - private const uint S_IXGRP = 0x0008; // group has execute permission - private const uint S_IROTH = 0x0004; // others have read permission - private const uint S_IWOTH = 0x0002; // others have write permission - private const uint S_IXOTH = 0x0001; // others have execute permission +#pragma warning restore IDE1006 // Naming Styles private readonly DateTime _originalLastAccessTimeUtc; private readonly DateTime _originalLastWriteTimeUtc; diff --git a/src/Renci.SshNet/Sftp/SftpFileReader.cs b/src/Renci.SshNet/Sftp/SftpFileReader.cs index a6a1f0898..ca8ed29d1 100644 --- a/src/Renci.SshNet/Sftp/SftpFileReader.cs +++ b/src/Renci.SshNet/Sftp/SftpFileReader.cs @@ -94,7 +94,7 @@ public byte[] Read() { // wait until either the next chunk is available, an exception has occurred or the current // instance is already disposed - while (!_queue.TryGetValue(_nextChunkIndex, out nextChunk) && _exception == null) + while (!_queue.TryGetValue(_nextChunkIndex, out nextChunk) && _exception is null) { _ =Monitor.Wait(_readLock); } @@ -281,7 +281,7 @@ private void StartReadAhead() { ThreadAbstraction.ExecuteThread(() => { - while (!_endOfFileReceived && _exception == null) + while (!_endOfFileReceived && _exception is null) { // check if we should continue with the read-ahead loop // note that the EOF and exception check are not included diff --git a/src/Renci.SshNet/Sftp/SftpFileStream.cs b/src/Renci.SshNet/Sftp/SftpFileStream.cs index e42cad978..26e22ee88 100644 --- a/src/Renci.SshNet/Sftp/SftpFileStream.cs +++ b/src/Renci.SshNet/Sftp/SftpFileStream.cs @@ -201,12 +201,12 @@ private SftpFileStream(ISftpSession session, string path, FileAccess access, int internal SftpFileStream(ISftpSession session, string path, FileMode mode, FileAccess access, int bufferSize) { - if (session == null) + if (session is null) { throw new SshConnectionException("Client not connected."); } - if (path == null) + if (path is null) { throw new ArgumentNullException(nameof(path)); } @@ -267,7 +267,7 @@ internal SftpFileStream(ISftpSession session, string path, FileMode mode, FileAc break; case FileMode.Create: _handle = _session.RequestOpen(path, flags | Flags.Truncate, nullOnError: true); - if (_handle == null) + if (_handle is null) { flags |= Flags.CreateNew; } @@ -312,12 +312,12 @@ internal SftpFileStream(ISftpSession session, string path, FileMode mode, FileAc internal static async Task OpenAsync(ISftpSession session, string path, FileMode mode, FileAccess access, int bufferSize, CancellationToken cancellationToken) { - if (session == null) + if (session is null) { throw new SshConnectionException("Client not connected."); } - if (path == null) + if (path is null) { throw new ArgumentNullException(nameof(path)); } @@ -501,7 +501,7 @@ public override int Read(byte[] buffer, int offset, int count) { var readLen = 0; - if (buffer == null) + if (buffer is null) { throw new ArgumentNullException(nameof(buffer)); } @@ -642,7 +642,7 @@ public override async Task ReadAsync(byte[] buffer, int offset, int count, { var readLen = 0; - if (buffer == null) + if (buffer is null) { throw new ArgumentNullException(nameof(buffer)); } @@ -987,7 +987,7 @@ public override void SetLength(long value) /// Methods were called after the stream was closed. public override void Write(byte[] buffer, int offset, int count) { - if (buffer == null) + if (buffer is null) { throw new ArgumentNullException(nameof(buffer)); } @@ -1086,7 +1086,7 @@ public override void Write(byte[] buffer, int offset, int count) /// Methods were called after the stream was closed. public override async Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { - if (buffer == null) + if (buffer is null) { throw new ArgumentNullException(nameof(buffer)); } @@ -1318,7 +1318,7 @@ private void SetupWrite() private void CheckSessionIsOpen() { - if (_session == null) + if (_session is null) { throw new ObjectDisposedException(GetType().FullName); } diff --git a/src/Renci.SshNet/Sftp/SftpResponseFactory.cs b/src/Renci.SshNet/Sftp/SftpResponseFactory.cs index 0edcfcf7c..1d5b4ad50 100644 --- a/src/Renci.SshNet/Sftp/SftpResponseFactory.cs +++ b/src/Renci.SshNet/Sftp/SftpResponseFactory.cs @@ -14,6 +14,7 @@ public SftpMessage Create(uint protocolVersion, byte messageType, Encoding encod SftpMessage message; +#pragma warning disable IDE0010 // Add missing cases switch (sftpMessageType) { case SftpMessageTypes.Version: @@ -40,6 +41,7 @@ public SftpMessage Create(uint protocolVersion, byte messageType, Encoding encod default: throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, "Message type '{0}' is not supported.", sftpMessageType)); } +#pragma warning restore IDE0010 // Add missing cases return message; } diff --git a/src/Renci.SshNet/Sftp/SftpSession.cs b/src/Renci.SshNet/Sftp/SftpSession.cs index 7bba929ed..c43a7af96 100644 --- a/src/Renci.SshNet/Sftp/SftpSession.cs +++ b/src/Renci.SshNet/Sftp/SftpSession.cs @@ -526,7 +526,7 @@ public SftpOpenAsyncResult BeginOpen(string path, Flags flags, AsyncCallback cal /// is null. public byte[] EndOpen(SftpOpenAsyncResult asyncResult) { - if (asyncResult == null) + if (asyncResult is null) { throw new ArgumentNullException(nameof(asyncResult)); } @@ -638,7 +638,7 @@ public SftpCloseAsyncResult BeginClose(byte[] handle, AsyncCallback callback, ob /// is null. public void EndClose(SftpCloseAsyncResult asyncResult) { - if (asyncResult == null) + if (asyncResult is null) { throw new ArgumentNullException(nameof(asyncResult)); } @@ -716,7 +716,7 @@ public SftpReadAsyncResult BeginRead(byte[] handle, ulong offset, uint length, A /// is null. public byte[] EndRead(SftpReadAsyncResult asyncResult) { - if (asyncResult == null) + if (asyncResult is null) { throw new ArgumentNullException(nameof(asyncResult)); } @@ -984,7 +984,7 @@ public SFtpStatAsyncResult BeginLStat(string path, AsyncCallback callback, objec /// is null. public SftpFileAttributes EndLStat(SFtpStatAsyncResult asyncResult) { - if (asyncResult == null) + if (asyncResult is null) { throw new ArgumentNullException(nameof(asyncResult)); } @@ -1492,7 +1492,7 @@ public SftpRealPathAsyncResult BeginRealPath(string path, AsyncCallback callback /// is null. public string EndRealPath(SftpRealPathAsyncResult asyncResult) { - if (asyncResult == null) + if (asyncResult is null) { throw new ArgumentNullException(nameof(asyncResult)); } @@ -1592,7 +1592,7 @@ public SFtpStatAsyncResult BeginStat(string path, AsyncCallback callback, object /// is null. public SftpFileAttributes EndStat(SFtpStatAsyncResult asyncResult) { - if (asyncResult == null) + if (asyncResult is null) { throw new ArgumentNullException(nameof(asyncResult)); } @@ -2044,6 +2044,7 @@ public uint CalculateOptimalWriteLength(uint bufferSize, byte[] handle) private static SshException GetSftpException(SftpStatusResponse response) { +#pragma warning disable IDE0010 // Add missing cases switch (response.StatusCode) { case StatusCodes.Ok: @@ -2055,6 +2056,7 @@ private static SshException GetSftpException(SftpStatusResponse response) default: return new SshException(response.ErrorMessage); } +#pragma warning restore IDE0010 // Add missing cases } private void HandleResponse(SftpResponse response) @@ -2069,7 +2071,7 @@ private void HandleResponse(SftpResponse response) } } - if (request == null) + if (request is null) { throw new InvalidOperationException("Invalid response."); } diff --git a/src/Renci.SshNet/SftpClient.cs b/src/Renci.SshNet/SftpClient.cs index 937f4a1a0..8190df20c 100644 --- a/src/Renci.SshNet/SftpClient.cs +++ b/src/Renci.SshNet/SftpClient.cs @@ -3,7 +3,6 @@ using System.Diagnostics.CodeAnalysis; using System.IO; using System.Globalization; -using System.Linq; using System.Net; using System.Text; using System.Threading; @@ -45,7 +44,7 @@ public class SftpClient : BaseClient, ISftpClient /// one (-1) milliseconds, which indicates an infinite timeout period. /// /// The method was called after the client was disposed. - /// represents a value that is less than -1 or greater than milliseconds. + /// represents a value that is less than -1 or greater than milliseconds. public TimeSpan OperationTimeout { get @@ -59,8 +58,10 @@ public TimeSpan OperationTimeout CheckDisposed(); var timeoutInMilliseconds = value.TotalMilliseconds; - if (timeoutInMilliseconds < -1d || timeoutInMilliseconds > int.MaxValue) - throw new ArgumentOutOfRangeException("value", "The timeout must represent a value between -1 and Int32.MaxValue, inclusive."); + if (timeoutInMilliseconds is < -1d or > int.MaxValue) + { + throw new ArgumentOutOfRangeException(nameof(value), "The timeout must represent a value between -1 and Int32.MaxValue, inclusive."); + } _operationTimeout = (int) timeoutInMilliseconds; } @@ -121,8 +122,12 @@ public string WorkingDirectory get { CheckDisposed(); - if (_sftpSession == null) + + if (_sftpSession is null) + { throw new SshConnectionException("Client not connected."); + } + return _sftpSession.WorkingDirectory; } } @@ -137,8 +142,12 @@ public int ProtocolVersion get { CheckDisposed(); - if (_sftpSession == null) + + if (_sftpSession is null) + { throw new SshConnectionException("Client not connected."); + } + return (int) _sftpSession.ProtocolVersion; } } @@ -274,11 +283,15 @@ public void ChangeDirectory(string path) { CheckDisposed(); - if (path == null) - throw new ArgumentNullException("path"); + if (path is null) + { + throw new ArgumentNullException(nameof(path)); + } - if (_sftpSession == null) + if (_sftpSession is null) + { throw new SshConnectionException("Client not connected."); + } _sftpSession.ChangeDirectory(path); } @@ -314,10 +327,14 @@ public void CreateDirectory(string path) CheckDisposed(); if (path.IsNullOrWhiteSpace()) + { throw new ArgumentException(path); + } - if (_sftpSession == null) + if (_sftpSession is null) + { throw new SshConnectionException("Client not connected."); + } var fullPath = _sftpSession.GetCanonicalPath(path); @@ -339,10 +356,14 @@ public void DeleteDirectory(string path) CheckDisposed(); if (path.IsNullOrWhiteSpace()) + { throw new ArgumentException("path"); + } - if (_sftpSession == null) + if (_sftpSession is null) + { throw new SshConnectionException("Client not connected."); + } var fullPath = _sftpSession.GetCanonicalPath(path); @@ -364,10 +385,14 @@ public void DeleteFile(string path) CheckDisposed(); if (path.IsNullOrWhiteSpace()) + { throw new ArgumentException("path"); + } - if (_sftpSession == null) + if (_sftpSession is null) + { throw new SshConnectionException("Client not connected."); + } var fullPath = _sftpSession.GetCanonicalPath(path); @@ -388,11 +413,18 @@ public void DeleteFile(string path) /// The method was called after the client was disposed. public async Task DeleteFileAsync(string path, CancellationToken cancellationToken) { - base.CheckDisposed(); + CheckDisposed(); + if (path.IsNullOrWhiteSpace()) + { throw new ArgumentException("path"); - if (_sftpSession == null) + } + + if (_sftpSession is null) + { throw new SshConnectionException("Client not connected."); + } + cancellationToken.ThrowIfCancellationRequested(); var fullPath = await _sftpSession.GetCanonicalPathAsync(path, cancellationToken).ConfigureAwait(false); @@ -428,13 +460,23 @@ public void RenameFile(string oldPath, string newPath) /// The method was called after the client was disposed. public async Task RenameFileAsync(string oldPath, string newPath, CancellationToken cancellationToken) { - base.CheckDisposed(); - if (oldPath == null) + CheckDisposed(); + + if (oldPath is null) + { throw new ArgumentNullException("oldPath"); - if (newPath == null) + } + + if (newPath is null) + { throw new ArgumentNullException("newPath"); - if (_sftpSession == null) + } + + if (_sftpSession is null) + { throw new SshConnectionException("Client not connected."); + } + cancellationToken.ThrowIfCancellationRequested(); var oldFullPath = await _sftpSession.GetCanonicalPathAsync(oldPath, cancellationToken).ConfigureAwait(false); @@ -457,14 +499,20 @@ public void RenameFile(string oldPath, string newPath, bool isPosix) { CheckDisposed(); - if (oldPath == null) + if (oldPath is null) + { throw new ArgumentNullException("oldPath"); + } - if (newPath == null) + if (newPath is null) + { throw new ArgumentNullException("newPath"); + } - if (_sftpSession == null) + if (_sftpSession is null) + { throw new SshConnectionException("Client not connected."); + } var oldFullPath = _sftpSession.GetCanonicalPath(oldPath); @@ -495,13 +543,19 @@ public void SymbolicLink(string path, string linkPath) CheckDisposed(); if (path.IsNullOrWhiteSpace()) + { throw new ArgumentException("path"); + } if (linkPath.IsNullOrWhiteSpace()) + { throw new ArgumentException("linkPath"); + } - if (_sftpSession == null) + if (_sftpSession is null) + { throw new SshConnectionException("Client not connected."); + } var fullPath = _sftpSession.GetCanonicalPath(path); @@ -546,11 +600,18 @@ public IEnumerable ListDirectory(string path, Action listCallbac /// The method was called after the client was disposed. public async Task> ListDirectoryAsync(string path, CancellationToken cancellationToken) { - base.CheckDisposed(); - if (path == null) + CheckDisposed(); + + if (path is null) + { throw new ArgumentNullException("path"); - if (_sftpSession == null) + } + + if (_sftpSession is null) + { throw new SshConnectionException("Client not connected."); + } + cancellationToken.ThrowIfCancellationRequested(); var fullPath = await _sftpSession.GetCanonicalPathAsync(path, cancellationToken).ConfigureAwait(false); @@ -566,7 +627,7 @@ public async Task> ListDirectoryAsync(string path, Cancel while (true) { var files = await _sftpSession.RequestReadDirAsync(handle, cancellationToken).ConfigureAwait(false); - if (files == null) + if (files is null) { break; } @@ -611,10 +672,7 @@ public IAsyncResult BeginListDirectory(string path, AsyncCallback asyncCallback, { asyncResult.Update(count); - if (listCallback != null) - { - listCallback(count); - } + listCallback?.Invoke(count); }); asyncResult.SetAsCompleted(result, false); @@ -638,10 +696,10 @@ public IAsyncResult BeginListDirectory(string path, AsyncCallback asyncCallback, /// The object did not come from the corresponding async method on this type.-or- was called multiple times with the same . public IEnumerable EndListDirectory(IAsyncResult asyncResult) { - var ar = asyncResult as SftpListDirectoryAsyncResult; - - if (ar == null || ar.EndInvokeCalled) + if (asyncResult is not SftpListDirectoryAsyncResult ar || ar.EndInvokeCalled) + { throw new ArgumentException("Either the IAsyncResult object did not come from the corresponding async method on this type, or EndExecute was called multiple times with the same IAsyncResult."); + } // Wait for operation to complete, then return result or throw exception return ar.EndInvoke(); @@ -662,11 +720,15 @@ public ISftpFile Get(string path) { CheckDisposed(); - if (path == null) + if (path is null) + { throw new ArgumentNullException("path"); + } - if (_sftpSession == null) + if (_sftpSession is null) + { throw new SshConnectionException("Client not connected."); + } var fullPath = _sftpSession.GetCanonicalPath(path); @@ -692,10 +754,14 @@ public bool Exists(string path) CheckDisposed(); if (path.IsNullOrWhiteSpace()) + { throw new ArgumentException("path"); + } - if (_sftpSession == null) + if (_sftpSession is null) + { throw new SshConnectionException("Client not connected."); + } var fullPath = _sftpSession.GetCanonicalPath(path); @@ -718,7 +784,7 @@ public bool Exists(string path) try { - _sftpSession.RequestLStat(fullPath); + _ = _sftpSession.RequestLStat(fullPath); return true; } catch (SftpPathNotFoundException) @@ -817,10 +883,14 @@ public IAsyncResult BeginDownloadFile(string path, Stream output, AsyncCallback CheckDisposed(); if (path.IsNullOrWhiteSpace()) + { throw new ArgumentException("path"); + } - if (output == null) + if (output is null) + { throw new ArgumentNullException("output"); + } var asyncResult = new SftpDownloadAsyncResult(asyncCallback, state); @@ -832,10 +902,7 @@ public IAsyncResult BeginDownloadFile(string path, Stream output, AsyncCallback { asyncResult.Update(offset); - if (downloadCallback != null) - { - downloadCallback(offset); - } + downloadCallback?.Invoke(offset); }); asyncResult.SetAsCompleted(null, false); @@ -860,10 +927,10 @@ public IAsyncResult BeginDownloadFile(string path, Stream output, AsyncCallback /// A SSH error where is the message from the remote host. public void EndDownloadFile(IAsyncResult asyncResult) { - var ar = asyncResult as SftpDownloadAsyncResult; - - if (ar == null || ar.EndInvokeCalled) + if (asyncResult is not SftpDownloadAsyncResult ar || ar.EndInvokeCalled) + { throw new ArgumentException("Either the IAsyncResult object did not come from the corresponding async method on this type, or EndExecute was called multiple times with the same IAsyncResult."); + } // Wait for operation to complete, then return result or throw exception ar.EndInvoke(); @@ -912,9 +979,13 @@ public void UploadFile(Stream input, string path, bool canOverride, ActionA SSH error where is the message from the remote host. public void EndUploadFile(IAsyncResult asyncResult) { - var ar = asyncResult as SftpUploadAsyncResult; - - if (ar == null || ar.EndInvokeCalled) + if (asyncResult is not SftpUploadAsyncResult ar || ar.EndInvokeCalled) + { throw new ArgumentException("Either the IAsyncResult object did not come from the corresponding async method on this type, or EndExecute was called multiple times with the same IAsyncResult."); + } // Wait for operation to complete, then return result or throw exception ar.EndInvoke(); @@ -1108,11 +1184,15 @@ public SftpFileSytemInformation GetStatus(string path) { CheckDisposed(); - if (path == null) + if (path is null) + { throw new ArgumentNullException("path"); + } - if (_sftpSession == null) + if (_sftpSession is null) + { throw new SshConnectionException("Client not connected."); + } var fullPath = _sftpSession.GetCanonicalPath(path); @@ -1133,11 +1213,18 @@ public SftpFileSytemInformation GetStatus(string path) /// The method was called after the client was disposed. public async Task GetStatusAsync(string path, CancellationToken cancellationToken) { - base.CheckDisposed(); - if (path == null) + CheckDisposed(); + + if (path is null) + { throw new ArgumentNullException("path"); - if (_sftpSession == null) + } + + if (_sftpSession is null) + { throw new SshConnectionException("Client not connected."); + } + cancellationToken.ThrowIfCancellationRequested(); var fullPath = await _sftpSession.GetCanonicalPathAsync(path, cancellationToken).ConfigureAwait(false); @@ -1162,8 +1249,10 @@ public void AppendAllLines(string path, IEnumerable contents) { CheckDisposed(); - if (contents == null) + if (contents is null) + { throw new ArgumentNullException("contents"); + } using (var stream = AppendText(path)) { @@ -1188,8 +1277,10 @@ public void AppendAllLines(string path, IEnumerable contents, Encoding e { CheckDisposed(); - if (contents == null) + if (contents is null) + { throw new ArgumentNullException("contents"); + } using (var stream = AppendText(path, encoding)) { @@ -1273,8 +1364,10 @@ public StreamWriter AppendText(string path, Encoding encoding) { CheckDisposed(); - if (encoding == null) + if (encoding is null) + { throw new ArgumentNullException("encoding"); + } return new StreamWriter(new SftpFileStream(_sftpSession, path, FileMode.Append, FileAccess.Write, (int) _bufferSize), encoding); } @@ -1507,11 +1600,18 @@ public SftpFileStream Open(string path, FileMode mode, FileAccess access) /// The method was called after the client was disposed. public Task OpenAsync(string path, FileMode mode, FileAccess access, CancellationToken cancellationToken) { - base.CheckDisposed(); - if (path == null) + CheckDisposed(); + + if (path is null) + { throw new ArgumentNullException("path"); - if (_sftpSession == null) + } + + if (_sftpSession is null) + { throw new SshConnectionException("Client not connected."); + } + cancellationToken.ThrowIfCancellationRequested(); return SftpFileStream.OpenAsync(_sftpSession, path, mode, access, (int)_bufferSize, cancellationToken); @@ -1582,7 +1682,7 @@ public byte[] ReadAllBytes(string path) using (var stream = OpenRead(path)) { var buffer = new byte[stream.Length]; - stream.Read(buffer, 0, buffer.Length); + _ = stream.Read(buffer, 0, buffer.Length); return buffer; } } @@ -1943,8 +2043,10 @@ public SftpFileAttributes GetAttributes(string path) { CheckDisposed(); - if (_sftpSession == null) + if (_sftpSession is null) + { throw new SshConnectionException("Client not connected."); + } var fullPath = _sftpSession.GetCanonicalPath(path); @@ -1963,8 +2065,10 @@ public void SetAttributes(string path, SftpFileAttributes fileAttributes) { CheckDisposed(); - if (_sftpSession == null) + if (_sftpSession is null) + { throw new SshConnectionException("Client not connected."); + } var fullPath = _sftpSession.GetCanonicalPath(path); @@ -1999,10 +2103,15 @@ public void SetAttributes(string path, SftpFileAttributes fileAttributes) /// If a problem occurs while copying the file public IEnumerable SynchronizeDirectories(string sourcePath, string destinationPath, string searchPattern) { - if (sourcePath == null) + if (sourcePath is null) + { throw new ArgumentNullException("sourcePath"); + } + if (destinationPath.IsNullOrWhiteSpace()) + { throw new ArgumentException("destinationPath"); + } return InternalSynchronizeDirectories(sourcePath, destinationPath, searchPattern, null); } @@ -2023,10 +2132,15 @@ public IEnumerable SynchronizeDirectories(string sourcePath, string de /// If a problem occurs while copying the file public IAsyncResult BeginSynchronizeDirectories(string sourcePath, string destinationPath, string searchPattern, AsyncCallback asyncCallback, object state) { - if (sourcePath == null) + if (sourcePath is null) + { throw new ArgumentNullException("sourcePath"); + } + if (destinationPath.IsNullOrWhiteSpace()) + { throw new ArgumentException("destDir"); + } var asyncResult = new SftpSynchronizeDirectoriesAsyncResult(asyncCallback, state); @@ -2058,10 +2172,10 @@ public IAsyncResult BeginSynchronizeDirectories(string sourcePath, string destin /// The destination path was not found on the remote host. public IEnumerable EndSynchronizeDirectories(IAsyncResult asyncResult) { - var ar = asyncResult as SftpSynchronizeDirectoriesAsyncResult; - - if (ar == null || ar.EndInvokeCalled) + if (asyncResult is not SftpSynchronizeDirectoriesAsyncResult ar || ar.EndInvokeCalled) + { throw new ArgumentException("Either the IAsyncResult object did not come from the corresponding async method on this type, or EndExecute was called multiple times with the same IAsyncResult."); + } // Wait for operation to complete, then return result or throw exception return ar.EndInvoke(); @@ -2070,7 +2184,9 @@ public IEnumerable EndSynchronizeDirectories(IAsyncResult asyncResult) private IEnumerable InternalSynchronizeDirectories(string sourcePath, string destinationPath, string searchPattern, SftpSynchronizeDirectoriesAsyncResult asynchResult) { if (!Directory.Exists(sourcePath)) + { throw new FileNotFoundException(string.Format("Source directory not found: {0}", sourcePath)); + } var uploadedFiles = new List(); @@ -2105,7 +2221,7 @@ private IEnumerable InternalSynchronizeDirectories(string sourcePath, do { var localFile = sourceFiles.Current; - if (localFile == null) + if (localFile is null) { continue; } @@ -2130,10 +2246,7 @@ private IEnumerable InternalSynchronizeDirectories(string sourcePath, uploadedFiles.Add(localFile); - if (asynchResult != null) - { - asynchResult.Update(uploadedFiles.Count); - } + asynchResult?.Update(uploadedFiles.Count); } catch (Exception ex) { @@ -2163,11 +2276,15 @@ private IEnumerable InternalSynchronizeDirectories(string sourcePath, /// Client not connected. private IEnumerable InternalListDirectory(string path, Action listCallback) { - if (path == null) + if (path is null) + { throw new ArgumentNullException("path"); + } - if (_sftpSession == null) + if (_sftpSession is null) + { throw new SshConnectionException("Client not connected."); + } var fullPath = _sftpSession.GetCanonicalPath(path); @@ -2176,7 +2293,9 @@ private IEnumerable InternalListDirectory(string path, Action li var basePath = fullPath; if (!basePath.EndsWith("/")) + { basePath = string.Format("{0}/", fullPath); + } var result = new List(); @@ -2186,10 +2305,9 @@ private IEnumerable InternalListDirectory(string path, Action li { foreach (var f in files) { - result.Add(new SftpFile( - _sftpSession, - string.Format(CultureInfo.InvariantCulture, "{0}{1}", basePath, f.Key), - f.Value)); + result.Add(new SftpFile(_sftpSession, + string.Format(CultureInfo.InvariantCulture, "{0}{1}", basePath, f.Key), + f.Value)); } // Call callback to report number of files read @@ -2219,14 +2337,20 @@ private IEnumerable InternalListDirectory(string path, Action li /// Client not connected. private void InternalDownloadFile(string path, Stream output, SftpDownloadAsyncResult asyncResult, Action downloadCallback) { - if (output == null) + if (output is null) + { throw new ArgumentNullException("output"); + } if (path.IsNullOrWhiteSpace()) + { throw new ArgumentException("path"); + } - if (_sftpSession == null) + if (_sftpSession is null) + { throw new SshConnectionException("Client not connected."); + } var fullPath = _sftpSession.GetCanonicalPath(path); @@ -2238,11 +2362,15 @@ private void InternalDownloadFile(string path, Stream output, SftpDownloadAsyncR { // Cancel download if (asyncResult != null && asyncResult.IsDownloadCanceled) + { break; + } var data = fileReader.Read(); if (data.Length == 0) + { break; + } output.Write(data, 0, data.Length); @@ -2273,14 +2401,20 @@ private void InternalDownloadFile(string path, Stream output, SftpDownloadAsyncR /// Client not connected. private void InternalUploadFile(Stream input, string path, Flags flags, SftpUploadAsyncResult asyncResult, Action uploadCallback) { - if (input == null) + if (input is null) + { throw new ArgumentNullException("input"); + } if (path.IsNullOrWhiteSpace()) + { throw new ArgumentException("path"); + } - if (_sftpSession == null) + if (_sftpSession is null) + { throw new SshConnectionException("Client not connected."); + } var fullPath = _sftpSession.GetCanonicalPath(path); @@ -2299,7 +2433,9 @@ private void InternalUploadFile(Stream input, string path, Flags flags, SftpUplo { // Cancel upload if (asyncResult != null && asyncResult.IsUploadCanceled) + { break; + } if (bytesRead > 0) { @@ -2309,8 +2445,8 @@ private void InternalUploadFile(Stream input, string path, Flags flags, SftpUplo { if (s.StatusCode == StatusCodes.Ok) { - Interlocked.Decrement(ref expectedResponses); - responseReceivedWaitHandle.Set(); + _ = Interlocked.Decrement(ref expectedResponses); + _ = responseReceivedWaitHandle.Set(); // Call callback to report number of bytes written if (uploadCallback != null) @@ -2320,7 +2456,8 @@ private void InternalUploadFile(Stream input, string path, Flags flags, SftpUplo } } }); - Interlocked.Increment(ref expectedResponses); + + _ = Interlocked.Increment(ref expectedResponses); offset += (ulong) bytesRead; @@ -2331,7 +2468,8 @@ private void InternalUploadFile(Stream input, string path, Flags flags, SftpUplo // Wait for expectedResponses to change _sftpSession.WaitOnHandle(responseReceivedWaitHandle, _operationTimeout); } - } while (expectedResponses > 0 || bytesRead > 0); + } + while (expectedResponses > 0 || bytesRead > 0); _sftpSession.RequestClose(handle); } @@ -2400,4 +2538,4 @@ private ISftpSession CreateAndConnectToSftpSession() } } } -} \ No newline at end of file +} diff --git a/src/Renci.SshNet/Shell.cs b/src/Renci.SshNet/Shell.cs index 63ebcf7e7..892c530b4 100644 --- a/src/Renci.SshNet/Shell.cs +++ b/src/Renci.SshNet/Shell.cs @@ -236,7 +236,7 @@ private void Channel_Closed(object sender, ChannelEventArgs e) /// private void UnsubscribeFromSessionEvents(ISession session) { - if (session == null) + if (session is null) { return; } diff --git a/src/Renci.SshNet/ShellStream.cs b/src/Renci.SshNet/ShellStream.cs index 004b962a3..37c3ac4de 100644 --- a/src/Renci.SshNet/ShellStream.cs +++ b/src/Renci.SshNet/ShellStream.cs @@ -155,7 +155,7 @@ public override bool CanWrite /// Methods were called after the stream was closed. public override void Flush() { - if (_channel == null) + if (_channel is null) { throw new ObjectDisposedException("ShellStream"); } @@ -676,12 +676,12 @@ public string Read() /// public void Write(string text) { - if (text == null) + if (text is null) { return; } - if (_channel == null) + if (_channel is null) { throw new ObjectDisposedException("ShellStream"); } @@ -750,7 +750,7 @@ protected override void Dispose(bool disposing) /// private void UnsubscribeFromSessionEvents(ISession session) { - if (session == null) + if (session is null) { return; } @@ -766,10 +766,7 @@ private void Session_ErrorOccured(object sender, ExceptionEventArgs e) private void Session_Disconnected(object sender, EventArgs e) { - if (_channel != null) - { - _channel.Dispose(); - } + _channel?.Dispose(); } private void Channel_Closed(object sender, ChannelEventArgs e) diff --git a/src/Renci.SshNet/SshClient.cs b/src/Renci.SshNet/SshClient.cs index 26a3cb1b4..5ed7036c5 100644 --- a/src/Renci.SshNet/SshClient.cs +++ b/src/Renci.SshNet/SshClient.cs @@ -184,7 +184,7 @@ protected override void OnDisconnecting() /// Client is not connected. public void AddForwardedPort(ForwardedPort port) { - if (port == null) + if (port is null) { throw new ArgumentNullException(nameof(port)); } @@ -202,7 +202,7 @@ public void AddForwardedPort(ForwardedPort port) /// is null. public void RemoveForwardedPort(ForwardedPort port) { - if (port == null) + if (port is null) { throw new ArgumentNullException(nameof(port)); } @@ -509,7 +509,7 @@ protected override void Dispose(bool disposing) private void EnsureSessionIsOpen() { - if (Session == null) + if (Session is null) { throw new SshConnectionException("Client not connected."); } diff --git a/src/Renci.SshNet/SshCommand.cs b/src/Renci.SshNet/SshCommand.cs index 2fa78d4a5..30a6bfe54 100644 --- a/src/Renci.SshNet/SshCommand.cs +++ b/src/Renci.SshNet/SshCommand.cs @@ -131,17 +131,17 @@ public string Error /// Either , is null. internal SshCommand(ISession session, string commandText, Encoding encoding) { - if (session == null) + if (session is null) { throw new ArgumentNullException(nameof(session)); } - if (commandText == null) + if (commandText is null) { throw new ArgumentNullException(nameof(commandText)); } - if (encoding == null) + if (encoding is null) { throw new ArgumentNullException(nameof(encoding)); } @@ -291,7 +291,7 @@ public IAsyncResult BeginExecute(string commandText, AsyncCallback callback, obj /// is null. public string EndExecute(IAsyncResult asyncResult) { - if (asyncResult == null) + if (asyncResult is null) { throw new ArgumentNullException(nameof(asyncResult)); } @@ -479,12 +479,19 @@ private void WaitOnHandle(WaitHandle waitHandle) waitHandle }; - switch (WaitHandle.WaitAny(waitHandles, CommandTimeout)) + var signaledElement = WaitHandle.WaitAny(waitHandles, CommandTimeout); + switch (signaledElement) { case 0: throw _exception; + case 1: + // Specified waithandle was signaled + break; case WaitHandle.WaitTimeout: throw new SshOperationTimeoutException(string.Format(CultureInfo.CurrentCulture, "Command '{0}' has timed out.", CommandText)); + default: + throw new SshException($"Unexpected element '{signaledElement.ToString(CultureInfo.InvariantCulture)}' signaled."); + } } @@ -498,7 +505,7 @@ private void WaitOnHandle(WaitHandle waitHandle) /// private void UnsubscribeFromEventsAndDisposeChannel(IChannel channel) { - if (channel == null) + if (channel is null) { return; } diff --git a/src/Renci.SshNet/SshMessageFactory.cs b/src/Renci.SshNet/SshMessageFactory.cs index 61952f4b5..5941c120e 100644 --- a/src/Renci.SshNet/SshMessageFactory.cs +++ b/src/Renci.SshNet/SshMessageFactory.cs @@ -99,7 +99,7 @@ public Message Create(byte messageNumber) } var enabledMessageMetadata = _enabledMessagesByNumber[messageNumber]; - if (enabledMessageMetadata == null) + if (enabledMessageMetadata is null) { MessageMetadata definedMessageMetadata = null; @@ -114,7 +114,7 @@ public Message Create(byte messageNumber) } } - if (definedMessageMetadata == null) + if (definedMessageMetadata is null) { throw CreateMessageTypeNotSupportedException(messageNumber); } @@ -164,7 +164,7 @@ public void EnableActivatedMessages() public void EnableAndActivateMessage(string messageName) { - if (messageName == null) + if (messageName is null) { throw new ArgumentNullException(nameof(messageName)); } @@ -191,7 +191,7 @@ public void EnableAndActivateMessage(string messageName) public void DisableAndDeactivateMessage(string messageName) { - if (messageName == null) + if (messageName is null) { throw new ArgumentNullException(nameof(messageName)); } diff --git a/src/Renci.SshNet/SubsystemSession.cs b/src/Renci.SshNet/SubsystemSession.cs index 922312e37..2c2b66c06 100644 --- a/src/Renci.SshNet/SubsystemSession.cs +++ b/src/Renci.SshNet/SubsystemSession.cs @@ -82,12 +82,12 @@ public bool IsOpen /// or is null. protected SubsystemSession(ISession session, string subsystemName, int operationTimeout) { - if (session == null) + if (session is null) { throw new ArgumentNullException(nameof(session)); } - if (subsystemName == null) + if (subsystemName is null) { throw new ArgumentNullException(nameof(subsystemName)); } @@ -472,7 +472,7 @@ private void EnsureSessionIsOpen() /// private void UnsubscribeFromSessionEvents(ISession session) { - if (session == null) + if (session is null) { return; }