Socks4ConnectorTest_Connect_ConnectionToProxyRefused.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. using System;
  2. using System.Diagnostics;
  3. using System.Net.Sockets;
  4. using Microsoft.VisualStudio.TestTools.UnitTesting;
  5. using Moq;
  6. namespace Renci.SshNet.Tests.Classes.Connection
  7. {
  8. [TestClass]
  9. public class Socks4ConnectorTest_Connect_ConnectionToProxyRefused : Socks4ConnectorTestBase
  10. {
  11. private ConnectionInfo _connectionInfo;
  12. private SocketException _actualException;
  13. private Socket _clientSocket;
  14. private Stopwatch _stopWatch;
  15. protected override void SetupData()
  16. {
  17. base.SetupData();
  18. _connectionInfo = CreateConnectionInfo("proxyUser", "proxyPwd");
  19. _connectionInfo.Timeout = TimeSpan.FromMilliseconds(5000);
  20. _stopWatch = new Stopwatch();
  21. _actualException = null;
  22. _clientSocket = SocketFactory.Create(SocketType.Stream, ProtocolType.Tcp);
  23. }
  24. protected override void SetupMocks()
  25. {
  26. _ = SocketFactoryMock.Setup(p => p.Create(SocketType.Stream, ProtocolType.Tcp))
  27. .Returns(_clientSocket);
  28. }
  29. protected override void TearDown()
  30. {
  31. base.TearDown();
  32. _clientSocket?.Dispose();
  33. }
  34. protected override void Act()
  35. {
  36. _stopWatch.Start();
  37. try
  38. {
  39. _ = Connector.Connect(_connectionInfo);
  40. Assert.Fail();
  41. }
  42. catch (SocketException ex)
  43. {
  44. _actualException = ex;
  45. }
  46. finally
  47. {
  48. _stopWatch.Stop();
  49. }
  50. }
  51. [TestMethod]
  52. public void ConnectShouldHaveThrownSocketException()
  53. {
  54. Assert.IsNull(_actualException.InnerException);
  55. Assert.AreEqual(SocketError.ConnectionRefused, _actualException.SocketErrorCode);
  56. }
  57. [TestMethod]
  58. public void ConnectShouldHaveRespectedTimeout()
  59. {
  60. var errorText = string.Format("Elapsed: {0}, Timeout: {1}",
  61. _stopWatch.ElapsedMilliseconds,
  62. _connectionInfo.Timeout.TotalMilliseconds);
  63. // Compare elapsed time with configured timeout, allowing for a margin of error
  64. Assert.IsTrue(_stopWatch.ElapsedMilliseconds < _connectionInfo.Timeout.TotalMilliseconds + 100, errorText);
  65. }
  66. [TestMethod]
  67. public void ClientSocketShouldHaveBeenDisposed()
  68. {
  69. try
  70. {
  71. _ = _clientSocket.Receive(new byte[0]);
  72. Assert.Fail();
  73. }
  74. catch (ObjectDisposedException)
  75. {
  76. }
  77. }
  78. [TestMethod]
  79. public void CreateOnSocketFactoryShouldHaveBeenInvokedOnce()
  80. {
  81. SocketFactoryMock.Verify(p => p.Create(SocketType.Stream, ProtocolType.Tcp),
  82. Times.Once());
  83. }
  84. }
  85. }