SshCommandTest_EndExecute.cs 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. using System;
  2. using System.Globalization;
  3. using System.Text;
  4. using Microsoft.VisualStudio.TestTools.UnitTesting;
  5. using Moq;
  6. using Renci.SshNet.Channels;
  7. using Renci.SshNet.Common;
  8. using Renci.SshNet.Tests.Common;
  9. namespace Renci.SshNet.Tests.Classes
  10. {
  11. [TestClass]
  12. public class SShCommand_EndExecute : TestBase
  13. {
  14. private Mock<ISession> _sessionMock;
  15. private Mock<IChannelSession> _channelSessionMock;
  16. private string _commandText;
  17. private Encoding _encoding;
  18. private SshCommand _sshCommand;
  19. protected override void OnInit()
  20. {
  21. base.OnInit();
  22. _sessionMock = new Mock<ISession>(MockBehavior.Strict);
  23. _commandText = new Random().Next().ToString(CultureInfo.InvariantCulture);
  24. _encoding = Encoding.UTF8;
  25. _channelSessionMock = new Mock<IChannelSession>(MockBehavior.Strict);
  26. _sshCommand = new SshCommand(_sessionMock.Object, _commandText, _encoding);
  27. }
  28. [TestMethod]
  29. public void EndExecute_ChannelClosed_ShouldDisposeChannelSession()
  30. {
  31. var seq = new MockSequence();
  32. _sessionMock.InSequence(seq).Setup(p => p.CreateChannelSession()).Returns(_channelSessionMock.Object);
  33. _channelSessionMock.InSequence(seq).Setup(p => p.Open());
  34. _channelSessionMock.InSequence(seq).Setup(p => p.SendExecRequest(_commandText))
  35. .Returns(true)
  36. .Raises(c => c.Closed += null, new ChannelEventArgs(5));
  37. _channelSessionMock.InSequence(seq).Setup(p => p.IsOpen).Returns(false);
  38. _channelSessionMock.InSequence(seq).Setup(p => p.Dispose());
  39. var asyncResult = _sshCommand.BeginExecute();
  40. _sshCommand.EndExecute(asyncResult);
  41. _channelSessionMock.Verify(p => p.Dispose(), Times.Once);
  42. }
  43. [TestMethod]
  44. public void EndExecute_ChannelOpen_ShouldSendEofAndCloseAndDisposeChannelSession()
  45. {
  46. var seq = new MockSequence();
  47. _sessionMock.InSequence(seq).Setup(p => p.CreateChannelSession()).Returns(_channelSessionMock.Object);
  48. _channelSessionMock.InSequence(seq).Setup(p => p.Open());
  49. _channelSessionMock.InSequence(seq).Setup(p => p.SendExecRequest(_commandText))
  50. .Returns(true)
  51. .Raises(c => c.Closed += null, new ChannelEventArgs(5));
  52. _channelSessionMock.InSequence(seq).Setup(p => p.IsOpen).Returns(true);
  53. _channelSessionMock.InSequence(seq).Setup(p => p.SendEof());
  54. _channelSessionMock.InSequence(seq).Setup(p => p.Close());
  55. _channelSessionMock.InSequence(seq).Setup(p => p.Dispose());
  56. var asyncResult = _sshCommand.BeginExecute();
  57. _sshCommand.EndExecute(asyncResult);
  58. _channelSessionMock.Verify(p => p.Close(), Times.Once);
  59. }
  60. }
  61. }