SshCommandTest_Dispose.cs 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. using System;
  2. using System.Globalization;
  3. using System.IO;
  4. using System.Text;
  5. using Microsoft.VisualStudio.TestTools.UnitTesting;
  6. using Moq;
  7. using Renci.SshNet.Channels;
  8. using Renci.SshNet.Common;
  9. using Renci.SshNet.Tests.Common;
  10. namespace Renci.SshNet.Tests.Classes
  11. {
  12. [TestClass]
  13. public class SshCommandTest_Dispose : TestBase
  14. {
  15. private Mock<ISession> _sessionMock;
  16. private Mock<IChannelSession> _channelSessionMock;
  17. private string _commandText;
  18. private Encoding _encoding;
  19. private SshCommand _sshCommand;
  20. private Stream _outputStream;
  21. private Stream _extendedOutputStream;
  22. protected override void OnInit()
  23. {
  24. base.OnInit();
  25. Arrange();
  26. Act();
  27. }
  28. private void Arrange()
  29. {
  30. _sessionMock = new Mock<ISession>(MockBehavior.Strict);
  31. _commandText = new Random().Next().ToString(CultureInfo.InvariantCulture);
  32. _encoding = Encoding.UTF8;
  33. _channelSessionMock = new Mock<IChannelSession>(MockBehavior.Strict);
  34. var seq = new MockSequence();
  35. _sessionMock.InSequence(seq).Setup(p => p.CreateChannelSession()).Returns(_channelSessionMock.Object);
  36. _channelSessionMock.InSequence(seq).Setup(p => p.Open());
  37. _channelSessionMock.InSequence(seq).Setup(p => p.SendExecRequest(_commandText)).Returns(true);
  38. _channelSessionMock.InSequence(seq).Setup(p => p.Dispose());
  39. _sshCommand = new SshCommand(_sessionMock.Object, _commandText, _encoding);
  40. _sshCommand.BeginExecute();
  41. _outputStream = _sshCommand.OutputStream;
  42. _extendedOutputStream = _sshCommand.ExtendedOutputStream;
  43. }
  44. private void Act()
  45. {
  46. _sshCommand.Dispose();
  47. }
  48. [TestMethod]
  49. public void ChannelSessionShouldBeDisposedOnce()
  50. {
  51. _channelSessionMock.Verify(p => p.Dispose(), Times.Once);
  52. }
  53. [TestMethod]
  54. public void OutputStreamShouldHaveBeenDisposed()
  55. {
  56. Assert.AreEqual(-1, _outputStream.ReadByte());
  57. }
  58. [TestMethod]
  59. public void ExtendedOutputStreamShouldHaveBeenDisposed()
  60. {
  61. Assert.AreEqual(-1, _extendedOutputStream.ReadByte());
  62. }
  63. [TestMethod]
  64. public void RaisingDisconnectedOnSessionShouldDoNothing()
  65. {
  66. _sessionMock.Raise(s => s.Disconnected += null, new EventArgs());
  67. }
  68. [TestMethod]
  69. public void RaisingErrorOccuredOnSessionShouldDoNothing()
  70. {
  71. _sessionMock.Raise(s => s.ErrorOccured += null, new ExceptionEventArgs(new Exception()));
  72. }
  73. [TestMethod]
  74. public void InvokingDisposeAgainShouldNotRaiseAnException()
  75. {
  76. _sshCommand.Dispose();
  77. }
  78. }
  79. }