protected void Arrange()
        {
            var random = new Random();
            _subsystemName = random.Next().ToString(CultureInfo.InvariantCulture);
            _operationTimeout = TimeSpan.FromSeconds(30);
            _encoding = Encoding.UTF8;
            _disconnectedRegister = new List<EventArgs>();
            _errorOccurredRegister = new List<ExceptionEventArgs>();
            _channelDataEventArgs = new ChannelDataEventArgs(
                (uint)random.Next(0, int.MaxValue),
                new[] { (byte)random.Next(byte.MinValue, byte.MaxValue) });

            _sessionMock = new Mock<ISession>(MockBehavior.Strict);
            _channelMock = new Mock<IChannelSession>(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,
                _encoding);
            _subsystemSession.Disconnected += (sender, args) => _disconnectedRegister.Add(args);
            _subsystemSession.ErrorOccurred += (sender, args) => _errorOccurredRegister.Add(args);
            _subsystemSession.Connect();
        }
        private void Arrange()
        {
            var random = new Random();
            _localChannelNumber = (uint)random.Next(0, int.MaxValue);
            _localWindowSize = (uint)random.Next(0, int.MaxValue);
            _localPacketSize = (uint)random.Next(0, int.MaxValue);
            _remoteChannelNumber = (uint)random.Next(0, int.MaxValue);
            _remoteWindowSize = (uint)random.Next(0, int.MaxValue);
            _remotePacketSize = (uint)random.Next(0, int.MaxValue);
            _channelClosedRegister = new List<ChannelEventArgs>();
            _channelExceptionRegister = new List<ExceptionEventArgs>();

            _sessionMock = new Mock<ISession>(MockBehavior.Strict);

            var sequence = new MockSequence();

            _sessionMock.InSequence(sequence).Setup(p => p.IsConnected).Returns(true);
            _sessionMock.InSequence(sequence).Setup(p => p.TrySendMessage(It.Is<ChannelCloseMessage>(c => c.LocalChannelNumber == _remoteChannelNumber))).Returns(true);
            _sessionMock.InSequence(sequence)
                .Setup(s => s.WaitOnHandle(It.IsNotNull<EventWaitHandle>()))
                .Callback<WaitHandle>(w => w.WaitOne());

            _channel = new ChannelStub(_sessionMock.Object, _localChannelNumber, _localWindowSize, _localPacketSize);
            _channel.Closed += (sender, args) => _channelClosedRegister.Add(args);
            _channel.Exception += (sender, args) => _channelExceptionRegister.Add(args);
            _channel.InitializeRemoteChannelInfo(_remoteChannelNumber, _remoteWindowSize, _remotePacketSize);
            _channel.SetIsOpen(true);
        }
        protected void Arrange()
        {
            var random = new Random();
            _fileName = CreateTemporaryFile(new byte[] {1});
            _connectionInfo = new ConnectionInfo("host", 22, "user", new PasswordAuthenticationMethod("user", "pwd"));
            _fileInfo = new FileInfo(_fileName);
            _path = random.Next().ToString(CultureInfo.InvariantCulture);
            _uploadingRegister = new List<ScpUploadEventArgs>();

            _serviceFactoryMock = new Mock<IServiceFactory>(MockBehavior.Strict);
            _sessionMock = new Mock<ISession>(MockBehavior.Strict);
            _channelSessionMock = new Mock<IChannelSession>(MockBehavior.Strict);
            _pipeStreamMock = new Mock<PipeStream>(MockBehavior.Strict);

            var sequence = new MockSequence();
            _serviceFactoryMock.InSequence(sequence)
                .Setup(p => p.CreateSession(_connectionInfo))
                .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());
            _channelSessionMock.InSequence(sequence)
                .Setup(
                    p => p.SendExecRequest(string.Format("scp -t \"{0}\"", _path))).Returns(false);
            _channelSessionMock.InSequence(sequence).Setup(p => p.Dispose());
            _pipeStreamMock.As<IDisposable>().InSequence(sequence).Setup(p => p.Dispose());

            _scpClient = new ScpClient(_connectionInfo, false, _serviceFactoryMock.Object);
            _scpClient.Uploading += (sender, args) => _uploadingRegister.Add(args);
            _scpClient.Connect();
        }
        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<IAuthenticationMethod>
                {
                    PublicKeyAuthenticationMethodMock.Object
                });
            NoneAuthenticationMethodMock.InSequence(seq)
                .Setup(p => p.AllowedAuthentications)
                .Returns(new[] { "password" });

            PublicKeyAuthenticationMethodMock.InSequence(seq).Setup(p => p.Name).Returns("publickey");

            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"));
        }
        private void Arrange()
        {
            var random = new Random();
            _localChannelNumber = (uint)random.Next(0, int.MaxValue);
            _localWindowSize = (uint)random.Next(0, int.MaxValue);
            _localPacketSize = (uint)random.Next(0, int.MaxValue);
            _remoteChannelNumber = (uint)random.Next(0, int.MaxValue);
            _remoteWindowSize = (uint)random.Next(0, int.MaxValue);
            _remotePacketSize = (uint)random.Next(0, int.MaxValue);
            _channelClosedRegister = new List<ChannelEventArgs>();
            _channelExceptionRegister = new List<ExceptionEventArgs>();
            _initialSessionSemaphoreCount = random.Next(10, 20);
            _sessionSemaphore = new SemaphoreLight(_initialSessionSemaphoreCount);

            _sessionMock = new Mock<ISession>(MockBehavior.Strict);
            _connectionInfoMock = new Mock<IConnectionInfo>(MockBehavior.Strict);

            _sequence = new MockSequence();
            _sessionMock.InSequence(_sequence).Setup(p => p.ConnectionInfo).Returns(_connectionInfoMock.Object);
            _connectionInfoMock.InSequence(_sequence).Setup(p => p.RetryAttempts).Returns(1);
            _sessionMock.Setup(p => p.SessionSemaphore).Returns(_sessionSemaphore);
            _sessionMock.InSequence(_sequence)
                .Setup(
                    p =>
                        p.SendMessage(
                            It.Is<ChannelOpenMessage>(
                                m =>
                                    m.LocalChannelNumber == _localChannelNumber &&
                                    m.InitialWindowSize == _localWindowSize && m.MaximumPacketSize == _localPacketSize &&
                                    m.Info is SessionChannelOpenInfo)));
            _sessionMock.InSequence(_sequence)
                .Setup(p => p.WaitOnHandle(It.IsNotNull<WaitHandle>()))
                .Callback<WaitHandle>(
                    w =>
                    {
                        _sessionMock.Raise(
                            s => s.ChannelOpenConfirmationReceived += null,
                            new MessageEventArgs<ChannelOpenConfirmationMessage>(
                                new ChannelOpenConfirmationMessage(
                                    _localChannelNumber,
                                    _remoteWindowSize,
                                    _remotePacketSize,
                                    _remoteChannelNumber)));
                        w.WaitOne();
                    });
            _sessionMock.Setup(p => p.IsConnected).Returns(true);
            _sessionMock.InSequence(_sequence)
                .Setup(
                    p => p.TrySendMessage(It.Is<ChannelCloseMessage>(c => c.LocalChannelNumber == _remoteChannelNumber)))
                .Returns(false);

            _channel = new ChannelSession(_sessionMock.Object, _localChannelNumber, _localWindowSize, _localPacketSize);
            _channel.Closed += (sender, args) => _channelClosedRegister.Add(args);
            _channel.Exception += (sender, args) => _channelExceptionRegister.Add(args);
            _channel.Open();

            _sessionMock.Raise(
                p => p.ChannelCloseReceived += null,
                new MessageEventArgs<ChannelCloseMessage>(new ChannelCloseMessage(_localChannelNumber)));
        }
        protected void Arrange()
        {
            _serviceFactoryMock = new Mock<IServiceFactory>(MockBehavior.Strict);
            _sessionMock = new Mock<ISession>(MockBehavior.Strict);
            _sftpSessionMock = new Mock<ISftpSession>(MockBehavior.Strict);

            _connectionInfo = new ConnectionInfo("host", "user", new NoneAuthenticationMethod("userauth"));
            _operationTimeout = TimeSpan.FromSeconds(new Random().Next(1, 10));
            _sftpClient = new SftpClient(_connectionInfo, false, _serviceFactoryMock.Object);
            _sftpClient.OperationTimeout = _operationTimeout;

            var sequence = new MockSequence();
            _serviceFactoryMock.InSequence(sequence)
                .Setup(p => p.CreateSession(_connectionInfo))
                .Returns(_sessionMock.Object);
            _sessionMock.InSequence(sequence).Setup(p => p.Connect());
            _serviceFactoryMock.InSequence(sequence)
                .Setup(p => p.CreateSftpSession(_sessionMock.Object, _operationTimeout, _connectionInfo.Encoding))
                .Returns(_sftpSessionMock.Object);
            _sftpSessionMock.InSequence(sequence).Setup(p => p.Connect());
            _sessionMock.InSequence(sequence).Setup(p => p.OnDisconnecting());
            _sftpSessionMock.InSequence(sequence).Setup(p => p.Disconnect());
            _sftpSessionMock.InSequence(sequence).Setup(p => p.Dispose());
            _sessionMock.InSequence(sequence).Setup(p => p.Disconnect());
            _sessionMock.InSequence(sequence).Setup(p => p.Dispose());

            _sftpClient.Connect();
            _sftpClient.Disconnect();
        }
        public void AccountRepository()
        {
            Mock<IWebsiteContext> context = new Mock<IWebsiteContext>();
            Mock<IDbSetFactory> factory = new Mock<IDbSetFactory>();
            Mock<DbSet<Account>> dbSet = new Mock<DbSet<Account>>();

            factory.Setup(m => m.CreateDbSet<Account>()).Returns(dbSet.Object);

            AccountRepository repo = new AccountRepository(context.Object, factory.Object);

            var account = new Account
                {
                    Id = "SDF",
                    FullName = "Trevor Slawnyk",
                    PreferredName = "Trevor",
                    Zip = 68456,
                    FacebookId = 4929447011515,
                    Birthdate = new DateTime(1994, 6, 22),
                    Weight = 250,
                    Height = 73,
                    Sex = false
                };
            account.UserName = "******";

            var sequence = new MockSequence();
            dbSet.InSequence(sequence).Setup(e => e.Add(account));
            dbSet.InSequence(sequence).Setup(e => e.Find(account.Id));
            dbSet.InSequence(sequence).Setup(e => e.Find(account.Id));
            dbSet.InSequence(sequence).Setup(e => e.Find(account.Id));
            repo.Create(account);
            repo.Get(account.Id);
            repo.Update(account);
            repo.Delete(account.Id);
        }
Esempio n. 8
0
        public void EvaluateShouldWorkCorrectly()
        {
            const int expectedResult1 = 30;
            const int expectedResult = 90;
            const string token1 = "+";
            const string token2 = "*";

            // Here you can test the internal algorithm and expected behavior
            // up to the way that methods should be called in the expected order
            // on mocks.
            // Though - be very careful. As you can see the test setup may grow
            // very quickly which implies that future maintenance may be very difficult.
            var sequence = new MockSequence();

            var factory = new Mock<IOperationFactory>(MockBehavior.Strict);
            var operation1 = new Mock<IOperation>(MockBehavior.Strict);
            var operation2 = new Mock<IOperation>(MockBehavior.Strict);

            factory.InSequence(sequence).Setup(f => f.Create(token2)).Returns(operation2.Object).Verifiable();
            factory.InSequence(sequence).Setup(f => f.Create(token1)).Returns(operation1.Object).Verifiable();

            operation1.InSequence(sequence).Setup(o => o.Evaluate(10, 10)).Returns(expectedResult1).Verifiable();
            operation2.InSequence(sequence).Setup(o => o.Evaluate(expectedResult1, 30)).Returns(expectedResult).Verifiable();

            var calculator = new Calculator(factory.Object);

            var expression = new[] { "10", token1, "10", token2, "30" };

            Assert.AreEqual(expectedResult, calculator.Evaluate(expression));

            factory.VerifyAll();
            operation1.VerifyAll();
            operation2.VerifyAll();
        }
        protected void Arrange()
        {
            _serviceFactoryMock = new Mock<IServiceFactory>(MockBehavior.Loose);
            _sessionMock = new Mock<ISession>(MockBehavior.Loose);
            _netConfSessionMock = new Mock<INetConfSession>(MockBehavior.Loose);

            _connectionInfo = new ConnectionInfo("host", "user", new NoneAuthenticationMethod("userauth"));
            _netConfClient = new NetConfClient(_connectionInfo, false, _serviceFactoryMock.Object);

            var sequence = new MockSequence();
            _serviceFactoryMock.InSequence(sequence)
                .Setup(p => p.CreateSession(_connectionInfo))
                .Returns(_sessionMock.Object);
            _sessionMock.InSequence(sequence).Setup(p => p.Connect());
            _serviceFactoryMock.InSequence(sequence)
                .Setup(p => p.CreateNetConfSession(_sessionMock.Object, _netConfClient.OperationTimeout))
                .Returns(_netConfSessionMock.Object);
            _netConfSessionMock.InSequence(sequence).Setup(p => p.Connect());

            _netConfClient.Connect();
            _netConfClient = null;

            // we need to dereference all other mocks as they might otherwise hold the target alive
            _sessionMock = null;
            _connectionInfo = null;
            _serviceFactoryMock = null;

        }
        protected void Arrange()
        {
            _serviceFactoryMock = new Mock<IServiceFactory>(MockBehavior.Strict);
            _sessionMock = new Mock<ISession>(MockBehavior.Strict);
            _netConfSessionMock = new Mock<INetConfSession>(MockBehavior.Strict);

            _connectionInfo = new ConnectionInfo("host", "user", new NoneAuthenticationMethod("userauth"));
            _netConfClient = new NetConfClient(_connectionInfo, false, _serviceFactoryMock.Object);

            var sequence = new MockSequence();
            _serviceFactoryMock.InSequence(sequence)
                .Setup(p => p.CreateSession(_connectionInfo))
                .Returns(_sessionMock.Object);
            _sessionMock.InSequence(sequence).Setup(p => p.Connect());
            _serviceFactoryMock.InSequence(sequence)
                .Setup(p => p.CreateNetConfSession(_sessionMock.Object, _netConfClient.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());

            _netConfClient.Connect();
            _netConfClient.Dispose();
        }
        private void Arrange()
        {
            var random = new Random();

            _sessionMock = new Mock<ISession>(MockBehavior.Strict);
            _channelSessionAMock = new Mock<IChannelSession>(MockBehavior.Strict);
            _channelSessionBMock = new Mock<IChannelSession>(MockBehavior.Strict);
            _commandText = random.Next().ToString(CultureInfo.InvariantCulture);
            _encoding = Encoding.UTF8;
            _asyncResultA = null;
            _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)
                .Raises(c => c.Closed += null, new ChannelEventArgs(5));
            _channelSessionAMock.InSequence(seq).Setup(p => p.Dispose());

            _sshCommand = new SshCommand(_sessionMock.Object, _commandText, _encoding);
            _asyncResultA = _sshCommand.BeginExecute();
            _sshCommand.EndExecute(_asyncResultA);

            _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);
        }
        protected void Arrange()
        {
            var random = new Random();
            _path = random.Next().ToString(CultureInfo.InvariantCulture);
            _handle = new[] { (byte)random.Next(byte.MinValue, byte.MaxValue) };
            _fileAttributes = SftpFileAttributes.Empty;
            _bufferSize = (uint)random.Next(0, 1000);
            _readBufferSize = (uint)random.Next(0, 1000);
            _writeBufferSize = (uint)random.Next(0, 1000);

            _sftpSessionMock = new Mock<ISftpSession>(MockBehavior.Strict);

            var sequence = new MockSequence();
            _sftpSessionMock.InSequence(sequence)
                .Setup(p => p.RequestOpen(_path, Flags.Write | Flags.Truncate, true))
                .Returns(_handle);
            _sftpSessionMock.InSequence(sequence).Setup(p => p.RequestFStat(_handle)).Returns(_fileAttributes);
            _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.Create, FileAccess.Write, (int)_bufferSize);
        }
        private IEnumerable<IExperimentUpdate> SetupActualVersion()
        {
            var s = new MockSequence();
            _firstUpdateMock.InSequence(s).Setup(t => t.UpToVersion).Returns(new Version(1, 1, 0));
            _secondUpdateMock.InSequence(s).Setup(t => t.UpToVersion).Returns(new Version(1, 2, 0));

            return new IExperimentUpdate[] { _firstUpdateMock.Object, _secondUpdateMock.Object };
        }
        protected void Arrange()
        {
            var random = new Random();

            _operationTimeout = TimeSpan.FromMilliseconds(random.Next(100, 500));
            _expected = new byte[random.Next(30, 50)];
            _encoding = Encoding.UTF8;
            random.NextBytes(_expected);

            _sessionMock = new Mock<ISession>(MockBehavior.Strict);
            _channelSessionMock = new Mock<IChannelSession>(MockBehavior.Strict);

            var sequence = new MockSequence();

            _sessionMock.InSequence(sequence).Setup(p => p.CreateChannelSession()).Returns(_channelSessionMock.Object);
            _channelSessionMock.InSequence(sequence).Setup(p => p.Open());
            _channelSessionMock.InSequence(sequence).Setup(p => p.SendSubsystemRequest("sftp")).Returns(true);
            _channelSessionMock.InSequence(sequence).Setup(p => p.IsOpen).Returns(true);
            _channelSessionMock.InSequence(sequence).Setup(p => p.SendData(It.IsAny<byte[]>())).Callback(
                () =>
                    {
                        // generate response for SftpInitRequest
                        var versionInfoResponse = SftpVersionResponseBuilder.Create(3)
                                                                            .Build();
                        _channelSessionMock.Raise(
                            c => c.DataReceived += null,
                            new ChannelDataEventArgs(0, versionInfoResponse));
                    });
            _channelSessionMock.InSequence(sequence).Setup(p => p.IsOpen).Returns(true);
            _channelSessionMock.InSequence(sequence).Setup(p => p.SendData(It.IsAny<byte[]>())).Callback(
                () =>
                    {
                        var sftpNameResponse = CreateSftpNameResponse(1, _encoding, "ABC");

                        _channelSessionMock.Raise(
                            c => c.DataReceived += null,
                            new ChannelDataEventArgs(0, sftpNameResponse));
                    }
                );
            _channelSessionMock.InSequence(sequence).Setup(p => p.IsOpen).Returns(true);
            _channelSessionMock.InSequence(sequence).Setup(p => p.SendData(It.IsAny<byte[]>())).Callback(
                () =>
                    {
                        var sftpDataResponse = CreateSftpDataResponse(2, _expected);

                        _channelSessionMock.Raise(
                            c => c.DataReceived += null,
                            new ChannelDataEventArgs(0, sftpDataResponse.Take(0, 20)));
                        _channelSessionMock.Raise(
                            c => c.DataReceived += null,
                            new ChannelDataEventArgs(0, sftpDataResponse.Take(20, sftpDataResponse.Length - 20)));
                    }
                );

            _sftpSession = new SftpSession(_sessionMock.Object, _operationTimeout, _encoding);
            _sftpSession.Connect();
        }
        protected void Arrange()
        {
            var random = new Random();

            _operationTimeout = TimeSpan.FromMilliseconds(random.Next(100, 500));
            _encoding = Encoding.UTF8;

            _bAvail = (ulong) random.Next(0, int.MaxValue);

            _sessionMock = new Mock<ISession>(MockBehavior.Strict);
            _channelSessionMock = new Mock<IChannelSession>(MockBehavior.Strict);

            var sequence = new MockSequence();

            _sessionMock.InSequence(sequence).Setup(p => p.CreateChannelSession()).Returns(_channelSessionMock.Object);
            _channelSessionMock.InSequence(sequence).Setup(p => p.Open());
            _channelSessionMock.InSequence(sequence).Setup(p => p.SendSubsystemRequest("sftp")).Returns(true);
            _channelSessionMock.InSequence(sequence).Setup(p => p.IsOpen).Returns(true);
            _channelSessionMock.InSequence(sequence).Setup(p => p.SendData(It.IsAny<byte[]>())).Callback(
                () =>
                    {
                        // generate response for SftpInitRequest
                        var versionInfoResponse = SftpVersionResponseBuilder.Create(3)
                                                                            .AddExtension("*****@*****.**", "")
                                                                            .Build();
                        _channelSessionMock.Raise(
                            c => c.DataReceived += null,
                            new ChannelDataEventArgs(0, versionInfoResponse));
                    });
            _channelSessionMock.InSequence(sequence).Setup(p => p.IsOpen).Returns(true);
            _channelSessionMock.InSequence(sequence).Setup(p => p.SendData(It.IsAny<byte[]>())).Callback(
                () =>
                    {
                        var sftpNameResponse = CreateSftpNameResponse(1, _encoding, "ABC");

                        _channelSessionMock.Raise(
                            c => c.DataReceived += null,
                            new ChannelDataEventArgs(0, sftpNameResponse));
                    }
                );
            _channelSessionMock.InSequence(sequence).Setup(p => p.IsOpen).Returns(true);
            _channelSessionMock.InSequence(sequence).Setup(p => p.SendData(It.IsAny<byte[]>())).Callback(
                () =>
                    {
                        var statVfsReplyBuilder = StatVfsReplyBuilder.Create(2);
                        statVfsReplyBuilder.WithBAvail(_bAvail);
                        var statVfsReply = statVfsReplyBuilder.Build();

                        _channelSessionMock.Raise(
                            c => c.DataReceived += null,
                            new ChannelDataEventArgs(0, statVfsReply));
                    }
                );

            _sftpSession = new SftpSession(_sessionMock.Object, _operationTimeout, _encoding);
            _sftpSession.Connect();
        }
        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());
        }
        private IEnumerable<IExperimentUpdate> SetupPrevVersion()
        {
            var s = new MockSequence();
            _firstUpdateMock.InSequence(s).Setup(t => t.UpToVersion).Returns(new Version(1, 1, 0));
            _secondUpdateMock.InSequence(s).Setup(t => t.UpToVersion).Returns(new Version(1, 2, 0));

            _secondUpdateMock.InSequence(s).Setup(t => t.Update(It.IsAny<XmlDocument>())).Returns(new XmlDocument());

            return new IExperimentUpdate[] { _firstUpdateMock.Object, _secondUpdateMock.Object };
        }
		async public void ItShouldRetrieveJwksAndCacheKeysWhenKeyIsNotInCache() {
			var seq = new MockSequence();

			m_keyCache
				.InSequence( seq )
				.Setup( x => x.Get( SRC_NAMESPACE, KEY_ID ) )
				.Returns<D2LSecurityToken>( null );

			var otherKeyId = Guid.NewGuid();
			var jwks = new JsonWebKeySet(
				new JavaScriptSerializer().Serialize(
					new {
						keys = new object[] {
							D2LSecurityTokenUtility
								.CreateActiveToken( KEY_ID )
								.ToJsonWebKey()
								.ToJwkDto(),
							D2LSecurityTokenUtility
								.CreateActiveToken( otherKeyId )
								.ToJsonWebKey()
								.ToJwkDto()
						}
					}
				),
				new Uri( "http://localhost/dummy" )
			);
			m_jwksProvider
				.InSequence( seq )
				.Setup( x => x.RequestJwksAsync() )
				.ReturnsAsync( jwks );

			m_keyCache
				.Setup( x => x.Set( SRC_NAMESPACE, It.Is<D2LSecurityToken>( k => k.KeyId == KEY_ID ) ) );
			m_keyCache
				.Setup( x => x.Set( SRC_NAMESPACE, It.Is<D2LSecurityToken>( k => k.KeyId == otherKeyId ) ) );

			var cachedKey = new D2LSecurityToken(
				KEY_ID,
				DateTime.UtcNow,
				DateTime.UtcNow + TimeSpan.FromHours( 1 ),
				() => null as Tuple<AsymmetricSecurityKey, IDisposable>
			);
			m_keyCache
				.InSequence( seq )
				.Setup( x => x.Get( SRC_NAMESPACE, KEY_ID ) )
				.Returns( cachedKey );

			D2LSecurityToken result = await m_publicKeyProvider
				.GetByIdAsync( KEY_ID )
				.SafeAsync();

			m_keyCache.VerifyAll();

			Assert.AreEqual( cachedKey, result );
		}
        private void Arrange()
        {
            var random = new Random();
            _localChannelNumber = (uint) random.Next(0, int.MaxValue);
            _localWindowSize = (uint) random.Next(2000, 3000);
            _localPacketSize = (uint) random.Next(1000, 2000);
            _initialSessionSemaphoreCount = random.Next(10, 20);
            _sessionSemaphore = new SemaphoreLight(_initialSessionSemaphoreCount);
            _channelClosedRegister = new List<ChannelEventArgs>();
            _channelExceptionRegister = new List<ExceptionEventArgs>();
            _actualException = null;

            _failureReasonCode = (uint)random.Next(0, int.MaxValue);
            _failureDescription = random.Next().ToString(CultureInfo.InvariantCulture);
            _failureLanguage = random.Next().ToString(CultureInfo.InvariantCulture);

            _sessionMock = new Mock<ISession>(MockBehavior.Strict);
            _connectionInfoMock = new Mock<IConnectionInfo>(MockBehavior.Strict);

            var sequence = new MockSequence();
            _sessionMock.InSequence(sequence).Setup(p => p.ConnectionInfo).Returns(_connectionInfoMock.Object);
            _connectionInfoMock.InSequence(sequence).Setup(p => p.RetryAttempts).Returns(1);
            _sessionMock.Setup(p => p.SessionSemaphore).Returns(_sessionSemaphore);
            _sessionMock.InSequence(sequence)
                .Setup(
                    p =>
                        p.SendMessage(
                            It.Is<ChannelOpenMessage>(
                                m =>
                                    m.LocalChannelNumber == _localChannelNumber &&
                                    m.InitialWindowSize == _localWindowSize && m.MaximumPacketSize == _localPacketSize &&
                                    m.Info is SessionChannelOpenInfo)));
            _sessionMock.InSequence(sequence)
                .Setup(p => p.WaitOnHandle(It.IsNotNull<WaitHandle>()))
                .Callback<WaitHandle>(
                    w =>
                        {
                            _sessionMock.Raise(
                                s => s.ChannelOpenFailureReceived += null,
                                new MessageEventArgs<ChannelOpenFailureMessage>(
                                    new ChannelOpenFailureMessage(
                                        _localChannelNumber,
                                        _failureDescription,
                                        _failureReasonCode,
                                        _failureLanguage
                                        )));
                        w.WaitOne();
                    });
            _sessionMock.InSequence(sequence).Setup(p => p.ConnectionInfo).Returns(_connectionInfoMock.Object);
            _connectionInfoMock.InSequence(sequence).Setup(p => p.RetryAttempts).Returns(1);

            _channel = new ChannelSession(_sessionMock.Object, _localChannelNumber, _localWindowSize, _localPacketSize);
            _channel.Closed += (sender, args) => _channelClosedRegister.Add(args);
            _channel.Exception += (sender, args) => _channelExceptionRegister.Add(args);
        }
Esempio n. 20
0
        public void InvalidSequenceFail()
        {
            var a = new Mock<IFoo>(MockBehavior.Strict);
            var b = new Mock<IFoo>(MockBehavior.Strict);

            var sequence = new MockSequence();
            a.InSequence(sequence).Setup(x => x.Do(100)).Returns(101);
            b.InSequence(sequence).Setup(x => x.Do(200)).Returns(201);

            Assert.Throws<MockException>(() => b.Object.Do(200));
        }
Esempio n. 21
0
        public void RightSequenceSuccess()
        {
            var a = new Mock<IFoo>(MockBehavior.Strict);
            var b = new Mock<IFoo>(MockBehavior.Strict);

            var sequence = new MockSequence();
            a.InSequence(sequence).Setup(x => x.Do(100)).Returns(101);
            b.InSequence(sequence).Setup(x => x.Do(200)).Returns(201);

            a.Object.Do(100);
            b.Object.Do(200);
        }
        private void Arrange()
        {
            var random = new Random();
            _localChannelNumber = (uint)random.Next(0, int.MaxValue);
            _localWindowSize = (uint)random.Next(0, int.MaxValue);
            _localPacketSize = (uint)random.Next(0, int.MaxValue);
            _remoteChannelNumber = (uint)random.Next(0, int.MaxValue);
            _remoteWindowSize = (uint)random.Next(0, int.MaxValue);
            _remotePacketSize = (uint)random.Next(0, int.MaxValue);
            _closeTimer = new Stopwatch();
            _channelClosedRegister = new List<ChannelEventArgs>();
            _channelExceptionRegister = new List<ExceptionEventArgs>();

            _sessionMock = new Mock<ISession>(MockBehavior.Strict);

            var sequence = new MockSequence();
            _sessionMock.InSequence(sequence).Setup(p => p.IsConnected).Returns(true);
            _sessionMock.InSequence(sequence).Setup(p => p.TrySendMessage(It.Is<ChannelCloseMessage>(c => c.LocalChannelNumber == _remoteChannelNumber))).Returns(true);
            _sessionMock.InSequence(sequence).Setup(p => p.WaitOnHandle(It.IsAny<EventWaitHandle>()))
                .Callback<WaitHandle>(w =>
                    {
                        new Thread(() =>
                            {
                                Thread.Sleep(100);
                                // raise ChannelCloseReceived event to set waithandle for receiving
                                // SSH_MSG_CHANNEL_CLOSE message from server which is waited on after
                                // sending the SSH_MSG_CHANNEL_CLOSE message to the server
                                _sessionMock.Raise(s => s.ChannelCloseReceived += null,
                                    new MessageEventArgs<ChannelCloseMessage>(
                                        new ChannelCloseMessage(_localChannelNumber)));
                            }).Start();
                        _closeTimer.Start();
                        try
                        {
                            w.WaitOne();
                        }
                        finally
                        {
                            _closeTimer.Stop();
                        }
                    });

            _channel = new ChannelStub(_sessionMock.Object, _localChannelNumber, _localWindowSize, _localPacketSize);
            _channel.Closed += (sender, args) => _channelClosedRegister.Add(args);
            _channel.Exception += (sender, args) => _channelExceptionRegister.Add(args);
            _channel.InitializeRemoteChannelInfo(_remoteChannelNumber, _remoteWindowSize, _remotePacketSize);
            _channel.SetIsOpen(true);

            _sessionMock.Raise(
                s => s.ChannelEofReceived += null,
                new MessageEventArgs<ChannelEofMessage>(new ChannelEofMessage(_localChannelNumber)));
        }
        private void Arrange()
        {
            var random = new Random();
            _localChannelNumber = (uint)random.Next(0, int.MaxValue);
            _localWindowSize = (uint)random.Next(0, int.MaxValue);
            _localPacketSize = (uint)random.Next(0, int.MaxValue);
            _remoteChannelNumber = (uint)random.Next(0, int.MaxValue);
            _remoteWindowSize = (uint)random.Next(0, int.MaxValue);
            _remotePacketSize = (uint)random.Next(0, int.MaxValue);
            _channelClosedRegister = new List<ChannelEventArgs>();
            _channelExceptionRegister = new List<ExceptionEventArgs>();
            _channelClosedReceived = new ManualResetEvent(false);

            _sessionMock = new Mock<ISession>(MockBehavior.Strict);

            var sequence = new MockSequence();
            _sessionMock.InSequence(sequence).Setup(p => p.IsConnected).Returns(true);
            _sessionMock.InSequence(sequence).Setup(p => p.TrySendMessage(It.Is<ChannelCloseMessage>(c => c.LocalChannelNumber == _remoteChannelNumber))).Returns(true);
            _sessionMock.InSequence(sequence).Setup(p => p.WaitOnHandle(It.IsAny<EventWaitHandle>()))
                .Callback<WaitHandle>(w =>
                    {
                        new Thread(() =>
                            {
                                Thread.Sleep(100);
                                // signal that the ChannelCloseMessage was received; we use this to verify whether we've actually
                                // waited on the EventWaitHandle to be set
                                _channelClosedReceived.Set();
                                // raise ChannelCloseReceived event to set waithandle for receiving
                                // SSH_MSG_CHANNEL_CLOSE message from server which is waited on after
                                // sending the SSH_MSG_CHANNEL_CLOSE message to the server
                                // 
                                // we're mocking the wait on the ChannelCloseMessage, but we still want
                                // to get the channel in the state that it would have after actually receiving
                                // the ChannelCloseMessage
                                _sessionMock.Raise(s => s.ChannelCloseReceived += null, new MessageEventArgs<ChannelCloseMessage>(new ChannelCloseMessage(_localChannelNumber)));
                            }).Start();
                        w.WaitOne();
                    });

            _channel = new ChannelStub(_sessionMock.Object, _localChannelNumber, _localWindowSize, _localPacketSize);
            _channel.Closed += (sender, args) => _channelClosedRegister.Add(args);
            _channel.Exception += (sender, args) => _channelExceptionRegister.Add(args);
            _channel.InitializeRemoteChannelInfo(_remoteChannelNumber, _remoteWindowSize, _remotePacketSize);
            _channel.SetIsOpen(true);

            _sessionMock.Raise(
                s => s.ChannelEofReceived += null,
                new MessageEventArgs<ChannelEofMessage>(new ChannelEofMessage(_localChannelNumber)));
        }
Esempio n. 24
0
		public void SameMockRightSequenceConsecutiveInvocationsWithSameArguments()
		{
			var a = new Mock<IFoo>(MockBehavior.Strict);

			var sequence = new MockSequence();
			a.InSequence(sequence).Setup(x => x.Do(100)).Returns(101);
			a.InSequence(sequence).Setup(x => x.Do(100)).Returns(102);
			a.InSequence(sequence).Setup(x => x.Do(200)).Returns(201);
			a.InSequence(sequence).Setup(x => x.Do(100)).Returns(103);

			Assert.Equal(101, a.Object.Do(100));
			Assert.Equal(102, a.Object.Do(100));
			Assert.Equal(201, a.Object.Do(200));
			Assert.Equal(103, a.Object.Do(100));
		}
		public void NoCyclicSequenceFail()
		{
			var a = new Mock<IFoo>(MockBehavior.Strict);
			var b = new Mock<IFoo>(MockBehavior.Strict);

			var sequence = new MockSequence();
			a.InSequence(sequence).Setup(x => x.Do(100)).Returns(101);
			b.InSequence(sequence).Setup(x => x.Do(200)).Returns(201);

			Assert.AreEqual(101, a.Object.Do(100));
			Assert.AreEqual(201, b.Object.Do(200));

			AssertHelper.Throws<MockException>(() => a.Object.Do(100));
			AssertHelper.Throws<MockException>(() => b.Object.Do(200));
		}
Esempio n. 26
0
        public void EndExecute_ChannelOpen_ShouldSendEofAndCloseAndDisposeChannelSession()
        {
            var seq = new MockSequence();

            _sessionMock.InSequence(seq).Setup(p => p.CreateChannelSession()).Returns(_channelSessionMock.Object);
            _channelSessionMock.InSequence(seq).Setup(p => p.Open());
            _channelSessionMock.InSequence(seq).Setup(p => p.SendExecRequest(_commandText))
                .Returns(true)
                .Raises(c => c.Closed += null, new ChannelEventArgs(5));
            _channelSessionMock.InSequence(seq).Setup(p => p.Dispose());

            var asyncResult = _sshCommand.BeginExecute();
            _sshCommand.EndExecute(asyncResult);

            _channelSessionMock.Verify(p => p.Dispose(), Times.Once);
        }
Esempio n. 27
0
            public void LogsErrorsAndThenSuccess()
            {
                var sequence = new MockSequence();
                logger.InSequence(sequence).Setup(it => it.Error((It.Is<Exception>(e => e.Message == "1")))).Verifiable();
                logger.InSequence(sequence).Setup(it => it.Error((It.Is<Exception>(e => e.Message == "2")))).Verifiable();
                logger.InSequence(sequence).Setup(it => it.Error((It.Is<Exception>(e => e.Message == "3")))).Verifiable();
                logger.InSequence(sequence).Setup(it => it.Debug("Success")).Verifiable();

                sut.Attempt(
                  () => { throw new Exception("1"); },
                  () => { throw new Exception("2"); },
                  () => { throw new Exception("3"); },
                  () => { });

                logger.Verify();
            }
        private void Arrange()
        {
            var random = new Random();

            _sessionMock = new Mock<ISession>(MockBehavior.Strict);
            _channelSessionMock = new Mock<IChannelSession>(MockBehavior.Strict);
            _commandText = random.Next().ToString(CultureInfo.InvariantCulture);
            _encoding = Encoding.UTF8;

            var seq = new MockSequence();
            _sessionMock.InSequence(seq).Setup(p => p.CreateChannelSession()).Returns(_channelSessionMock.Object);
            _channelSessionMock.InSequence(seq).Setup(p => p.Open());
            _channelSessionMock.InSequence(seq).Setup(p => p.SendExecRequest(_commandText)).Returns(true);

            _sshCommand = new SshCommand(_sessionMock.Object, _commandText, _encoding);
            _sshCommand.BeginExecute();
        }
        protected void Arrange()
        {
            _random = new Random();
            _path = _random.Next().ToString(CultureInfo.InvariantCulture);
            _handle = new[] {(byte) _random.Next(byte.MinValue, byte.MaxValue)};
            _fileAttributes = SftpFileAttributes.Empty;
            _bufferSize = (uint) _random.Next(1, 1000);
            _readBufferSize = (uint) _random.Next(0, 1000);
            _writeBufferSize = (uint) _random.Next(500, 1000);
            _data = new byte[(_writeBufferSize  * 2) + 15];
            _random.NextBytes(_data);
            _offset = _random.Next(1, 5);
            // to get multiple SSH_FXP_WRITE messages (and verify the offset is updated correctly), we make sure
            // the number of bytes to write is at least two times the write buffer size; we write a few extra bytes to
            // ensure the buffer is not empty after the writes so we can verify whether Length, Dispose and Flush
            // flush the buffer
            _count = ((int) _writeBufferSize*2) + _random.Next(1, 5);

            _expectedWrittenByteCount = (2 * _writeBufferSize);
            _expectedBufferedByteCount = (int)(_count - _expectedWrittenByteCount);
            _expectedBufferedBytes = _data.Take(_offset + (int)_expectedWrittenByteCount, _expectedBufferedByteCount);

            _sftpSessionMock = new Mock<ISftpSession>(MockBehavior.Strict);

            _sequence = new MockSequence();
            _sftpSessionMock.InSequence(_sequence)
                .Setup(p => p.RequestOpen(_path, Flags.Write | Flags.Truncate, true))
                .Returns(_handle);
            _sftpSessionMock.InSequence(_sequence).Setup(p => p.RequestFStat(_handle)).Returns(_fileAttributes);
            _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.RequestWrite(_handle, 0, _data, _offset, (int) _writeBufferSize, It.IsAny<AutoResetEvent>(), null));
            _sftpSessionMock.InSequence(_sequence)
                .Setup(p => p.RequestWrite(_handle, _writeBufferSize, _data, _offset + (int) _writeBufferSize, (int)_writeBufferSize, It.IsAny<AutoResetEvent>(), null));

            _sftpFileStream = new SftpFileStream(_sftpSessionMock.Object, _path, FileMode.Create, FileAccess.Write, (int) _bufferSize);
        }
Esempio n. 30
0
        public void CyclicSequenceSuccesss()
        {
            var a = new Mock<IFoo>(MockBehavior.Strict);
            var b = new Mock<IFoo>(MockBehavior.Strict);

            var sequence = new MockSequence { Cyclic = true };
            a.InSequence(sequence).Setup(x => x.Do(100)).Returns(101);
            b.InSequence(sequence).Setup(x => x.Do(200)).Returns(201);

            Assert.Equal(101, a.Object.Do(100));
            Assert.Equal(201, b.Object.Do(200));

            Assert.Equal(101, a.Object.Do(100));
            Assert.Equal(201, b.Object.Do(200));

            Assert.Equal(101, a.Object.Do(100));
            Assert.Equal(201, b.Object.Do(200));
        }
Esempio n. 31
0
        public void SmartSqlBuilder_ShouldWorkWithComplexViews()
        {
            Config.Use(new SpecifiedDataTables(typeof(Start_Node), typeof(Goal_Node), typeof(Node2), typeof(Node4), typeof(Node5), typeof(Node6), typeof(Node7), typeof(Node8)));

            var mockSqlBuilder = new Mock <ISqlQuery>(MockBehavior.Strict);
            var seq            = new MockSequence();

            mockSqlBuilder
            .InSequence(seq)
            .Setup(x => x.InnerJoin(
                       It.Is <PropertyInfo>(y => y == typeof(Start_Node).GetProperty(nameof(Start_Node.Id))),
                       It.Is <PropertyInfo>(y => y == typeof(Node2).GetProperty(nameof(Node2.Reference)))));
            mockSqlBuilder
            .InSequence(seq)
            .Setup(x => x.InnerJoin(
                       It.Is <PropertyInfo>(y => y == typeof(Node2).GetProperty(nameof(Node2.Reference2))),
                       It.Is <PropertyInfo>(y => y == typeof(Goal_Node).GetProperty(nameof(Goal_Node.Id)))));

            mockSqlBuilder
            .InSequence(seq)
            .Setup(x => x.Select(
                       It.Is <PropertyInfo>(y => y == typeof(Goal_Node).GetProperty(nameof(Goal_Node.Id))),
                       It.Is <PropertyInfo>(y => y == UnwrappedView <Extension1> .Type.GetProperty(nameof(Extension1.IdSelection)))));
            mockSqlBuilder
            .InSequence(seq)
            .Setup(x => x.Select(
                       It.Is <PropertyInfo>(y => y == typeof(Start_Node).GetProperty(nameof(Start_Node.Id))),
                       It.Is <PropertyInfo>(y => y == UnwrappedView <Extension1> .Type.GetProperty(nameof(Extension1.Id)))));
            mockSqlBuilder
            .InSequence(seq)
            .Setup(x => x.Select(
                       It.Is <PropertyInfo>(y => y == typeof(Start_Node).GetProperty(nameof(Start_Node.ReferenceWithoutAttribute))),
                       It.Is <PropertyInfo>(y => y == UnwrappedView <Extension1> .Type.GetProperty(nameof(Extension1.ReferenceWithoutAttribute)))));

            SmartSqlBuilder <Extension1> .Build(_ => mockSqlBuilder.Object);

            mockSqlBuilder.Verify(x => x.InnerJoin(It.IsAny <PropertyInfo>(), It.IsAny <PropertyInfo>()), Times.Exactly(2));
            mockSqlBuilder.Verify(x => x.Select(It.IsAny <PropertyInfo>(), It.IsAny <PropertyInfo>()), Times.Exactly(3));
        }
 protected override void SetupMocks()
 {
     _sequence = new MockSequence();
     SftpSessionMock.InSequence(_sequence)
     .Setup(p => p.RequestOpen(_path, Flags.Read | Flags.Write, 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.RequestRead(_handle, 0, _readBufferSize))
     .Returns(_actualReadBytes);
     SftpSessionMock.InSequence(_sequence)
     .Setup(p => p.IsOpen)
     .Returns(true);
     SftpSessionMock.InSequence(_sequence)
     .Setup(p => p.IsOpen)
     .Returns(true);
     SftpSessionMock.InSequence(_sequence)
     .Setup(p => p.RequestWrite(_handle, (uint)_readBytes.Length, It.IsAny <byte[]>(), 0, _writeBytes.Length, It.IsAny <AutoResetEvent>(), null))
     .Callback <byte[], ulong, byte[], int, int, AutoResetEvent, Action <SftpStatusResponse> >((handle, serverOffset, data, offset, length, wait, writeCompleted)
                                                                                               =>
     {
         _actualWrittenBytes = data.Take(offset, length);
         wait.Set();
     });
     SftpSessionMock.InSequence(_sequence)
     .Setup(p => p.RequestFStat(_handle, false))
     .Returns(_fileAttributes);
     SftpSessionMock.InSequence(_sequence)
     .Setup(p => p.RequestFSetStat(_handle, _fileAttributes))
     .Callback <byte[], SftpFileAttributes>((bytes, attributes) => _newFileAttributes = attributes.Clone());
 }
Esempio n. 33
0
        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 <IAuthenticationMethod>
            {
                PasswordAuthenticationMethodMock.Object,
                PublicKeyAuthenticationMethodMock.Object,
            });
            NoneAuthenticationMethodMock.InSequence(seq)
            .Setup(p => p.AllowedAuthentications)
            .Returns(new[] { "publickey", "password" });

            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.Failure);
            // obtain name for inclusion in SshAuthenticationException
            PasswordAuthenticationMethodMock.InSequence(seq).Setup(p => p.Name).Returns("password");

            PublicKeyAuthenticationMethodMock.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"));
        }
Esempio n. 34
0
        public void Setup_InSequence_NotAllSetupAreUsed_Loose_FailsDuringVerifyNoOtherCalls()
        {
            var myMock   = new Mock <IMyInterface> (MockBehavior.Loose);
            var sequence = new MockSequence();

            myMock.InSequence(sequence).Setup(x => x.DoTheThing("A")).Returns("1");
            myMock.InSequence(sequence).Setup(x => x.DoTheThing("A")).Returns("2");

            // Act
            Assert.That(myMock.Object.DoTheThing("A"), Is.EqualTo("1"));

            myMock.Verify();
            // Verify does not affect VerifyNoOtherCalls

            Assert.That(
                () => myMock.VerifyNoOtherCalls(),
                Throws.TypeOf <MockException>().With.Message.StartWith(
                    "Mock<IMyInterface:").And.Message.EndWith(">:\n"
                                                              + "This mock failed verification due to the following unverified invocations:\r\n"
                                                              + "\r\n"
                                                              + "   IMyInterface.DoTheThing(\"A\")"));
        }
Esempio n. 35
0
        public void Setup_InSequence_UnexpectedCall_Loose_DoesNotMatch_FailsDuringVerifyNoOtherCalls()
        {
            var myMock   = new Mock <IMyInterface> (MockBehavior.Loose);
            var sequence = new MockSequence();

            myMock.InSequence(sequence).Setup(x => x.DoTheThing("A")).Returns("1");
            myMock.InSequence(sequence).Setup(x => x.DoTheThing("A")).Returns("2");

            // Act
            Assert.That(myMock.Object.DoTheThing("A"), Is.EqualTo("1"));
            Assert.That(myMock.Object.DoTheThing("B"), Is.Null);
            // Unknown call, DoTheThing("B") is not matched.

            Assert.That(
                () => myMock.VerifyNoOtherCalls(),
                Throws.TypeOf <MockException>().With.Message.StartWith(
                    "Mock<IMyInterface:").And.Message.EndWith(">:\n"
                                                              + "This mock failed verification due to the following unverified invocations:\r\n"
                                                              + "\r\n"
                                                              + "   IMyInterface.DoTheThing(\"A\")\r\n"
                                                              + "   IMyInterface.DoTheThing(\"B\")"));
        }
Esempio n. 36
0
        public void RemoveUnusedNodesRemoveCorrectNodes()
        {
            var stat          = new StatStub();
            var statGraphMock = new Mock <IStatGraph>(MockBehavior.Strict);

            statGraphMock.SetupGet(g => g.ModifierCount).Returns(0);
            var nodeSelectors = new[] { Selector(NodeType.Base), Selector(NodeType.More), Selector(NodeType.Total) };
            var nodes         = new Dictionary <NodeSelector, IBufferingEventViewProvider <ICalculationNode> >
            {
                { nodeSelectors[0], MockProvider <ICalculationNode>() },
                { nodeSelectors[1], MockProvider <ICalculationNode>(5) },
                { nodeSelectors[2], MockProvider <ICalculationNode>() },
            };

            statGraphMock.SetupGet(g => g.Nodes).Returns(nodes);
            var formNodeSelectors  = new[] { Selector(Form.Increase), Selector(Form.More) };
            var formNodeCollection = new Dictionary <FormNodeSelector, IBufferingEventViewProvider <INodeCollection <Modifier> > >
            {
                { formNodeSelectors[0], MockProvider <INodeCollection <Modifier> >(2) },
                { formNodeSelectors[1], MockProvider <INodeCollection <Modifier> >() },
            };

            statGraphMock.SetupGet(g => g.FormNodeCollections).Returns(formNodeCollection);
            var graphMock = MockGraph(stat, statGraphMock.Object);
            var sut       = CreateSut(graphMock.Object);

            sut.StatAdded(stat);

            var seq = new MockSequence();

            statGraphMock.InSequence(seq).Setup(g => g.RemoveNode(nodeSelectors[2])).Verifiable();
            statGraphMock.InSequence(seq).Setup(g => g.RemoveNode(nodeSelectors[0])).Verifiable();
            statGraphMock.InSequence(seq).Setup(g => g.RemoveFormNodeCollection(formNodeSelectors[1])).Verifiable();

            sut.RemoveUnusedNodes();

            // Verify last step of sequence to force previous calls in sequence
            statGraphMock.Verify(g => g.RemoveFormNodeCollection(formNodeSelectors[1]));
        }
Esempio n. 37
0
        public void GivenHistoryAccountServicePrintsStatement()
        {
            // Arrange
            var printer          = new Mock <IPrinter>();
            var statementPrinter = new StatementPrinter(printer.Object);
            var dateTimeHandler  = new Mock <IDateTimeHandler>();

            var dateTimeQueue = new Queue <DateTime>(new[]
            {
                new DateTime(2012, 01, 10),
                new DateTime(2012, 01, 13),
                new DateTime(2012, 01, 14)
            });

            dateTimeHandler
            .Setup(dth => dth.Now())
            .Returns(dateTimeQueue.Dequeue);

            var repo     = new TransactionRepository(dateTimeHandler.Object);
            var sequence = new MockSequence();
            var account  = new AccountService(statementPrinter, repo);

            printer.InSequence(sequence).Setup(c => c.Print(StatementHeader));
            printer.InSequence(sequence).Setup(c => c.Print(Line1));
            printer.InSequence(sequence).Setup(c => c.Print(Line2));
            printer.InSequence(sequence).Setup(c => c.Print(Line3));

            // Act
            account.Deposit(1000);
            account.Deposit(2000);
            account.Withdraw(500);
            account.PrintStatement();

            // Assert
            printer.Verify(c => c.Print(StatementHeader));
            printer.Verify(c => c.Print(Line1));
            printer.Verify(c => c.Print(Line2));
            printer.Verify(c => c.Print(Line3));
        }
Esempio n. 38
0
        public void DoNotCallApplicationBindingValidatorTwice()
        {
            var applicationBindingMock          = new Mock <IApplicationBinding <string> >(MockBehavior.Strict);
            var visitableApplicationBindingMock = applicationBindingMock.As <IVisitable <IApplicationBindingVisitor> >();

            var sequence = new MockSequence();

            visitableApplicationBindingMock.InSequence(sequence)
            .Setup(m => m.Accept(It.IsAny <EnvironmentOverrideApplicator>()))
            .Returns(It.IsAny <EnvironmentOverrideApplicator>());
            visitableApplicationBindingMock.InSequence(sequence)
            .Setup(m => m.Accept(It.IsAny <ApplicationBindingValidator>()))
            .Returns(It.IsAny <ApplicationBindingValidator>());

            var pipelineMock = new Mock <VisitorPipeline <string> >(applicationBindingMock.Object);
            var sut          = new PreprocessingStage <string>(pipelineMock.Object);

            sut.Accept(new Mock <ApplicationBindingValidator>().Object);

            visitableApplicationBindingMock.Verify(m => m.Accept(It.IsAny <EnvironmentOverrideApplicator>()), Times.Once);
            visitableApplicationBindingMock.Verify(m => m.Accept(It.IsAny <ApplicationBindingValidator>()), Times.Once);
        }
Esempio n. 39
0
        public async Task Queue_AddTasks_MustRunInQueue()
        {
            var key   = "kitty";
            var queue = new BackgroundTaskQueue <string>();
            var cat   = new Mock <ICat>(MockBehavior.Strict);

            var sequence = new MockSequence();

            cat.InSequence(sequence).Setup(x => x.Purrr(2));
            cat.InSequence(sequence).Setup(x => x.Purrr(1));
            cat.InSequence(sequence).Setup(x => x.Purrr(3));

            var task1 = queue.QueueTask(key, async token => { await Task.Delay(1000, token); cat.Object.Purrr(2); });
            var task2 = queue.QueueTask(key, async token => { await Task.Delay(100, token); cat.Object.Purrr(1); });
            var task3 = queue.QueueTask(key, async token => { await Task.Delay(10, token); cat.Object.Purrr(3); });

            await Task.WhenAll(task1, task2, task3);

            cat.Verify(x => x.Purrr(1), Times.Once);
            cat.Verify(x => x.Purrr(2), Times.Once);
            cat.Verify(x => x.Purrr(3), Times.Once);
        }
        public void SetUpTests()
        {
            _blaiseSurveyApiMock = new Mock <IBlaiseSurveyApi>(MockBehavior.Strict);
            _fileServiceMock     = new Mock <IFileService>(MockBehavior.Strict);
            _storageServiceMock  = new Mock <ICloudStorageService>(MockBehavior.Strict);
            _mockSequence        = new MockSequence();

            _instrumentFile = "OPN2010A.zip";
            _serverParkName = "ServerParkA";
            _instrumentName = "OPN2010A";
            _tempPath       = @"c:\temp\GUID";

            _instrumentPackageDto = new InstrumentPackageDto
            {
                InstrumentFile = _instrumentFile
            };

            _sut = new InstrumentInstallerService(
                _blaiseSurveyApiMock.Object,
                _fileServiceMock.Object,
                _storageServiceMock.Object);
        }
        public async Task RemovePayeeAsync_removes_payee_then_saves()
        {
            // Arrange
            var payee = new Payee {
                ID = 1
            };
            var payees = new List <Payee> {
                payee
            }.AsQueryable();
            var sequence = new MockSequence();

            _mockRepo.Setup(m => m.GetPayees(It.IsAny <bool>(), It.IsAny <bool>(), It.IsAny <bool>())).Returns(payees);
            _mockRepo.InSequence(sequence).Setup(m => m.DeletePayee(It.IsAny <Payee>()));
            _mockRepo.InSequence(sequence).Setup(m => m.SaveChangesAsync()).ReturnsAsync(1);

            // Act
            await _testService.RemovePayeeAsync(1);

            // Assert
            _mockRepo.Verify(m => m.DeletePayee(payee), Times.Once());
            _mockRepo.Verify(m => m.SaveChangesAsync(), Times.Once());
        }
Esempio n. 42
0
        protected override void SetupMocks()
        {
            var sequence = new MockSequence();

            _serviceFactoryMock.InSequence(sequence)
            .Setup(p => p.CreateRemotePathDoubleQuoteTransformation())
            .Returns(_remotePathTransformationMock.Object);
            _serviceFactoryMock.InSequence(sequence)
            .Setup(p => p.CreateSession(_connectionInfo))
            .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 -pf {0}", _transformedPath))).Returns(false);
            _channelSessionMock.InSequence(sequence).Setup(p => p.Dispose());
            _pipeStreamMock.As <IDisposable>().InSequence(sequence).Setup(p => p.Dispose());
        }
        public async Task UpdatePayeeAsync_edits_payee_then_saves()
        {
            // Arrange
            var testID = 1;
            var payee  = new Payee {
                ID            = testID,
                Name          = "test",
                EffectiveFrom = DateTime.Parse("1/1/2017")
            };
            var sequence = new MockSequence();

            _mockRepo.Setup(m => m.GetPayees(It.IsAny <bool>(), It.IsAny <bool>(), It.IsAny <bool>())).Returns(new List <Payee>().AsQueryable());
            _mockRepo.InSequence(sequence).Setup(m => m.EditPayee(It.IsAny <Payee>()));
            _mockRepo.InSequence(sequence).Setup(m => m.SaveChangesAsync()).ReturnsAsync(1);

            // Act
            await _testService.UpdatePayeeAsync(testID, payee);

            // Assert
            _mockRepo.Verify(m => m.EditPayee(payee), Times.Once());
            _mockRepo.Verify(m => m.SaveChangesAsync(), Times.Once());
        }
Esempio n. 44
0
        public void AccountLogic()
        {
            Mock <IUnitOfWork>           uow            = new Mock <IUnitOfWork>();
            Mock <IAccountRepository>    repo           = new Mock <IAccountRepository>();
            Mock <ITeamRepository>       teamRepo       = new Mock <ITeamRepository>();
            Mock <IAttainmentRepository> attainmentRepo = new Mock <IAttainmentRepository>();
            Mock <IMembershipRepository> membershipRepo = new Mock <IMembershipRepository>();

            AccountLogic logic = new AccountLogic(uow.Object, repo.Object, teamRepo.Object, attainmentRepo.Object, membershipRepo.Object);

            var account  = new Account();
            var sequence = new MockSequence();

            repo.InSequence(sequence).Setup(r => r.Create(account));
            repo.InSequence(sequence).Setup(r => r.Update(account));
            repo.InSequence(sequence).Setup(r => r.Get(account.Id));
            repo.InSequence(sequence).Setup(r => r.Delete(account.Id));
            logic.Create(account);
            logic.Update(account);
            logic.Get(account.Id);
            logic.Delete(account.Id);
        }
Esempio n. 45
0
        public void Create_ShouldThrowActivationExceptionWhenThereIsMoreThanOneConstructorInjectionDirectiveWithTheBestScore()
        {
            var seq = new MockSequence();
            var constructorInjectorMock = new Mock <ConstructorInjector>(MockBehavior.Strict);

            var directiveOne   = new ConstructorInjectionDirective(GetMyServiceWeaponAndWarriorConstructor(), constructorInjectorMock.Object);
            var directiveTwo   = new ConstructorInjectionDirective(GetMyServiceDefaultConstructor(), constructorInjectorMock.Object);
            var directiveThree = new ConstructorInjectionDirective(GetMyServiceClericAndName(), constructorInjectorMock.Object);
            var directives     = new ConstructorInjectionDirective[]
            {
                directiveOne,
                directiveTwo,
                directiveThree
            };
            var parameters = new List <IParameter>
            {
                new ConstructorArgument("location", "Biutiful"),
                new ConstructorArgument("warrior", new Monk()),
                new ConstructorArgument("weapon", new Dagger())
            };

            var kernelConfiguration = new KernelConfiguration(_ninjectSettings);
            var context             = CreateContext(kernelConfiguration, kernelConfiguration.BuildReadOnlyKernel(), parameters, typeof(NinjaBarracks), _providerCallbackMock.Object, _ninjectSettings);

            context.Plan = new Plan(typeof(MyService));
            context.Plan.Add(directiveOne);
            context.Plan.Add(directiveTwo);
            context.Plan.Add(directiveThree);

            _constructorScorerMock.InSequence(seq).Setup(p => p.Score(context, directiveOne)).Returns(3);
            _constructorScorerMock.InSequence(seq).Setup(p => p.Score(context, directiveTwo)).Returns(2);
            _constructorScorerMock.InSequence(seq).Setup(p => p.Score(context, directiveThree)).Returns(3);
            _providerCallbackMock.InSequence(seq).Setup(p => p(context)).Returns(_providerMock.Object);

            var actualException = Assert.Throws <ActivationException>(() => _standardProvider.Create(context));

            Assert.Null(actualException.InnerException);
            Assert.Equal(CreateAmbiguousConstructorExceptionMessage(actualException.GetType()), actualException.Message);
        }
Esempio n. 46
0
        private void SetupMocks()
        {
            var sequence = new MockSequence();

            _serviceFactoryMock.InSequence(sequence)
            .Setup(p => p.CreateSession(_connectionInfo))
            .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());
            _channelSessionMock.InSequence(sequence)
            .Setup(
                p => p.SendExecRequest(string.Format("scp -t \"{0}\"", _path))).Returns(true);
            _pipeStreamMock.InSequence(sequence).Setup(p => p.ReadByte()).Returns(0);
            _channelSessionMock.InSequence(sequence).Setup(p => p.SendData(It.IsAny <byte[]>()));
            _pipeStreamMock.InSequence(sequence).Setup(p => p.ReadByte()).Returns(0);
            _channelSessionMock.InSequence(sequence)
            .Setup(p => p.SendData(It.Is <byte[]>(b => b.SequenceEqual(CreateData(
                                                                           string.Format("C0644 {0} {1}\n",
                                                                                         _fileInfo.Length,
                                                                                         Path.GetFileName(_fileName)
                                                                                         )
                                                                           )))));
            _pipeStreamMock.InSequence(sequence).Setup(p => p.ReadByte()).Returns(0);
            _channelSessionMock.InSequence(sequence)
            .Setup(
                p => p.SendData(It.Is <byte[]>(b => b.SequenceEqual(_fileContent.Take(_bufferSize))), 0, _bufferSize));
            _channelSessionMock.InSequence(sequence)
            .Setup(
                p => p.SendData(It.Is <byte[]>(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 <byte[]>(b => b.SequenceEqual(new byte[] { 0 }))));
            _pipeStreamMock.InSequence(sequence).Setup(p => p.ReadByte()).Returns(0);
            _channelSessionMock.InSequence(sequence).Setup(p => p.Dispose());
            _pipeStreamMock.As <IDisposable>().InSequence(sequence).Setup(p => p.Dispose());
        }
Esempio n. 47
0
        public void InteractorTests_Loop_While_Enter_Text_Expect_2_Calls_of_GetInputText()
        {
            MockSequence sequence = new MockSequence();

            _mockTextInput
            .InSequence(sequence: sequence)
            .Setup(expression: m => m.GetInputText())
            .Returns(value: new InputTextResult()
            {
                HasEnteredConsoleText = true, Text = "Bla bla"
            });

            WordCountAnalyzerResult wordCountAnalyzerResult = new WordCountAnalyzerResult();

            _mockWordCountAnalyzer
            .InSequence(sequence: sequence)
            .Setup(m => m.Analyze("Bla bla"))
            .Returns(value: wordCountAnalyzerResult);

            _mockTextInput
            .InSequence(sequence: sequence)
            .Setup(m => m.GetInputText())
            .Returns(value: new InputTextResult()
            {
                HasEnteredConsoleText = false, Text = ""
            });

            int actual = _systemUnderTest.Execute();

            Assert.Equal(
                expected: 0,
                actual: actual);

            _mockTextInput
            .Verify(
                expression: v => v.GetInputText(),
                times: Times.Exactly(callCount: 2));
        }
        public void CacheMiss_AndExceptionDuringAssembleType_DoesNotCacheException()
        {
            var expectedException = new Exception();
            var additionalTypeID  = new object();
            var additionalType    = ReflectionObjectMother.GetSomeType();
            var assemblyContext   = CreateAssemblyContext();

            var sequence = new MockSequence();

            _assemblyContextPoolMock
            .InSequence(sequence)
            .Setup(mock => mock.Dequeue())
            .Returns(assemblyContext);
            _typeAssemblerMock
            .InSequence(sequence)
            .Setup(mock => mock.AssembleAdditionalType(It.IsAny <object>(), It.IsAny <IParticipantState>(), It.IsAny <IMutableTypeBatchCodeGenerator>()))
            .Throws(expectedException);
            _assemblyContextPoolMock
            .InSequence(sequence)
            .Setup(mock => mock.Enqueue(assemblyContext));
            _assemblyContextPoolMock
            .InSequence(sequence)
            .Setup(mock => mock.Dequeue())
            .Returns(assemblyContext);
            _typeAssemblerMock
            .InSequence(sequence)
            .Setup(mock => mock.AssembleAdditionalType(It.IsAny <object>(), It.IsAny <IParticipantState>(), It.IsAny <IMutableTypeBatchCodeGenerator>()))
            .Returns(new TypeAssemblyResult(additionalType));
            _assemblyContextPoolMock
            .InSequence(sequence)
            .Setup(mock => mock.Enqueue(assemblyContext));

            Assert.That(() => _cache.GetOrCreateAdditionalType(additionalTypeID), Throws.Exception.SameAs(expectedException));
            Assert.That(_cache.GetOrCreateAdditionalType(additionalTypeID), Is.SameAs(additionalType));

            _typeAssemblerMock.Verify();
            _assemblyContextPoolMock.Verify();
        }
        private void Arrange()
        {
            var random = new Random();

            _sessionMock        = new Mock <ISession>(MockBehavior.Strict);
            _channelSessionMock = new Mock <IChannelSession>(MockBehavior.Strict);
            _commandText        = random.Next().ToString(CultureInfo.InvariantCulture);
            _encoding           = Encoding.UTF8;
            _expectedExitStatus = random.Next();
            _dataA         = random.Next().ToString(CultureInfo.InvariantCulture);
            _dataB         = random.Next().ToString(CultureInfo.InvariantCulture);
            _extendedDataA = random.Next().ToString(CultureInfo.InvariantCulture);
            _extendedDataB = random.Next().ToString(CultureInfo.InvariantCulture);
            _asyncResult   = null;

            var seq = new MockSequence();

            _sessionMock.InSequence(seq).Setup(p => p.CreateChannelSession()).Returns(_channelSessionMock.Object);
            _channelSessionMock.InSequence(seq).Setup(p => p.Open());
            _channelSessionMock.InSequence(seq).Setup(p => p.SendExecRequest(_commandText))
            .Returns(true)
            .Raises(c => c.Closed += null, new ChannelEventArgs(5));
            _channelSessionMock.InSequence(seq).Setup(p => p.Dispose());

            _sshCommand  = new SshCommand(_sessionMock.Object, _commandText, _encoding);
            _asyncResult = _sshCommand.BeginExecute();

            _channelSessionMock.Raise(c => c.DataReceived += null,
                                      new ChannelDataEventArgs(0, _encoding.GetBytes(_dataA)));
            _channelSessionMock.Raise(c => c.ExtendedDataReceived += null,
                                      new ChannelExtendedDataEventArgs(0, _encoding.GetBytes(_extendedDataA), 0));
            _channelSessionMock.Raise(c => c.DataReceived += null,
                                      new ChannelDataEventArgs(0, _encoding.GetBytes(_dataB)));
            _channelSessionMock.Raise(c => c.ExtendedDataReceived += null,
                                      new ChannelExtendedDataEventArgs(0, _encoding.GetBytes(_extendedDataB), 0));
            _channelSessionMock.Raise(c => c.RequestReceived += null,
                                      new ChannelRequestEventArgs(new ExitStatusRequestInfo((uint)_expectedExitStatus)));
        }
Esempio n. 50
0
        protected override void SetupMocks()
        {
            _seq = new MockSequence();

            SftpSessionMock.InSequence(_seq)
            .Setup(p => p.CreateWaitHandleArray(It.IsNotNull <WaitHandle>(), It.IsNotNull <WaitHandle>()))
            .Returns <WaitHandle, WaitHandle>((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 <AsyncCallback>(), It.IsAny <BufferedRead>()))
            .Returns <byte[], ulong, uint, AsyncCallback, object>((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));
        }
Esempio n. 51
0
        private void Arrange()
        {
            var random = new Random();

            _localChannelNumber           = (uint)random.Next(0, int.MaxValue);
            _localWindowSize              = (uint)random.Next(2000, 3000);
            _localPacketSize              = (uint)random.Next(1000, 2000);
            _initialSessionSemaphoreCount = random.Next(10, 20);
            _sessionSemaphore             = new SemaphoreLight(_initialSessionSemaphoreCount);
            _channelClosedRegister        = new List <ChannelEventArgs>();
            _channelExceptionRegister     = new List <ExceptionEventArgs>();
            _waitOnConfirmationException  = new SystemException();

            _sessionMock        = new Mock <ISession>(MockBehavior.Strict);
            _connectionInfoMock = new Mock <IConnectionInfo>(MockBehavior.Strict);

            var sequence = new MockSequence();

            _sessionMock.InSequence(sequence).Setup(p => p.ConnectionInfo).Returns(_connectionInfoMock.Object);
            _connectionInfoMock.InSequence(sequence).Setup(p => p.RetryAttempts).Returns(2);
            _sessionMock.Setup(p => p.SessionSemaphore).Returns(_sessionSemaphore);
            _sessionMock.InSequence(sequence)
            .Setup(
                p =>
                p.SendMessage(
                    It.Is <ChannelOpenMessage>(
                        m =>
                        m.LocalChannelNumber == _localChannelNumber &&
                        m.InitialWindowSize == _localWindowSize && m.MaximumPacketSize == _localPacketSize &&
                        m.Info is SessionChannelOpenInfo)));
            _sessionMock.InSequence(sequence)
            .Setup(p => p.WaitOnHandle(It.IsNotNull <WaitHandle>()))
            .Throws(_waitOnConfirmationException);

            _channel            = new ChannelSession(_sessionMock.Object, _localChannelNumber, _localWindowSize, _localPacketSize);
            _channel.Closed    += (sender, args) => _channelClosedRegister.Add(args);
            _channel.Exception += (sender, args) => _channelExceptionRegister.Add(args);
        }
Esempio n. 52
0
        public async Task When_TransitionEventCommand_Than_Transitions_To_TestState_And_GeneratedEventIsRaisedWhenNecessary(bool generateEvent)
        {
            // Arrange
            var eventSut = CreateEventSut();

            this.sut = eventSut;

            var seq = new MockSequence();

            this.transitionsTester.InSequence(seq).Setup(m => m.OnLeaveInitial(It.IsAny <InitialState>()));
            this.transitionsTester.InSequence(seq).Setup(m => m.OnEnterTest(It.IsAny <TestState>()));

            var transition = NextStateChanged().Timeout(TimeoutDuration);

            EventGeneratedEventArgs <GeneratedEventBase> generatedEvent = null;

            eventSut.EventGenerated += (s, e) => { generatedEvent = e; };

            // Act
            this.sut.Process(new TransitionEventCommand(generateEvent));
            var e = await transition;

            // Assert
            Assert.IsType <TestState>(this.sut.CurrentState);
            Assert.IsType <TestState>(e.CurrentState);
            Assert.IsType <InitialState>(e.PreviousState);
            if (generateEvent)
            {
                Assert.IsType <FirstEvent>(generatedEvent.Event);
            }
            else
            {
                Assert.Null(generatedEvent);
            }

            this.transitionsTester.Verify(m => m.OnLeaveInitial(It.IsAny <InitialState>()), Times.Once);
            this.transitionsTester.Verify(m => m.OnEnterTest(It.IsAny <TestState>()), Times.Once);
        }
Esempio n. 53
0
        public void Should_CallSaveMethodAfterDeletemethod_When_InputParametersAreValid()
        {
            //Arrange
            var allItems = BuildItemsCollection();

            ItemsRepositoryMock.Setup(x => x.All()).Returns(allItems);

            var sequence = new MockSequence();

            ItemsRepositoryMock.InSequence(sequence).Setup(x => x.Delete(It.IsAny <Item>()));
            ItemsRepositoryMock.InSequence(sequence).Setup(x => x.SaveChanges());


            //Act
            var response = ItemsDataService.DeleteItem(1, "ab70793b-cec8-4eba-99f3-cbad0b1649d0");


            //Assert
            AssertHelper.AssertAll(
                () => response.IsSuccess.Should().BeTrue(),
                () => response.ErrorMessage.Should().BeNull()
                );
        }
Esempio n. 54
0
        public void Create_ShouldCreatePlanWhenNull()
        {
            var seq = new MockSequence();
            var constructorInjectorMock = new Mock <ConstructorInjector>(MockBehavior.Strict);
            var createdObject           = new object();
            var directives = new[]
            {
                new ConstructorInjectionDirective(GetMyServiceDefaultConstructor(), constructorInjectorMock.Object)
            };

            _contextMock.InSequence(seq).Setup(p => p.Plan).Returns((IPlan)null);
            _contextMock.InSequence(seq).Setup(p => p.Request).Returns(_requestMock.Object);
            _requestMock.InSequence(seq).Setup(p => p.Service).Returns(typeof(Dagger));
            _plannerMock.InSequence(seq).Setup(p => p.GetPlan(typeof(Monk))).Returns(_planMock.Object);
            _contextMock.InSequence(seq).SetupSet(p => p.Plan = _planMock.Object);
            _contextMock.InSequence(seq).Setup(p => p.Plan).Returns(_planMock.Object);
            _planMock.InSequence(seq).Setup(p => p.GetAll <ConstructorInjectionDirective>()).Returns(directives);
            constructorInjectorMock.InSequence(seq).Setup(p => p(new object[0])).Returns(createdObject);

            var actual = _standardProvider.Create(_contextMock.Object);

            Assert.Same(createdObject, actual);
        }
        protected void Arrange()
        {
            _connectionInfo = new ConnectionInfo("host", "user", new NoneAuthenticationMethod("userauth"));

            var sequence = new MockSequence();

            _serviceFactoryMock = new Mock <IServiceFactory>(MockBehavior.Strict);
            _sessionMock        = new Mock <ISession>(MockBehavior.Strict);
            _forwardedPortMock  = new Mock <ForwardedPort>(MockBehavior.Strict);

            _serviceFactoryMock.InSequence(sequence).Setup(p => p.CreateSession(_connectionInfo)).Returns(_sessionMock.Object);
            _sessionMock.InSequence(sequence).Setup(p => p.Connect());
            _forwardedPortMock.InSequence(sequence).Setup(p => p.Start());
            _sessionMock.InSequence(sequence).Setup(p => p.OnDisconnecting());
            _forwardedPortMock.InSequence(sequence).Setup(p => p.Stop());
            _sessionMock.InSequence(sequence).Setup(p => p.Dispose());

            _sshClient = new SshClient(_connectionInfo, false, _serviceFactoryMock.Object);
            _sshClient.Connect();
            _sshClient.AddForwardedPort(_forwardedPortMock.Object);

            _forwardedPortMock.Object.Start();
        }
        private void SetupMocks()
        {
            var seq = new MockSequence();

            _sftpSessionMock.InSequence(seq)
            .Setup(p => p.BeginOpen(_fileName, Flags.Read, null, null))
            .Returns(_openAsyncResult);
            _sftpSessionMock.InSequence(seq)
            .Setup(p => p.EndOpen(_openAsyncResult))
            .Returns(_handle);
            _sftpSessionMock.InSequence(seq)
            .Setup(p => p.BeginLStat(_fileName, null, null))
            .Returns(_statAsyncResult);
            _sftpSessionMock.InSequence(seq)
            .Setup(p => p.CalculateOptimalReadLength(_bufferSize))
            .Returns(_chunkSize);
            _sftpSessionMock.InSequence(seq)
            .Setup(p => p.EndLStat(_statAsyncResult))
            .Returns(_fileAttributes);
            _sftpSessionMock.InSequence(seq)
            .Setup(p => p.CreateFileReader(_handle, _sftpSessionMock.Object, _chunkSize, 7, _fileSize))
            .Returns(_sftpFileReaderMock.Object);
        }
        private void SetupMocks()
        {
            var sequence = new MockSequence();

            _serviceFactoryMock.InSequence(sequence)
            .Setup(p => p.CreateSession(_connectionInfo))
            .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());
        }
        public void ExecuteFailsIfContentFileIsInvalid()
        {
            var          workingDir = System.IO.Path.Combine("workingDir", "NDependResults");
            var          result     = GenerateResultMock();
            var          executor   = GenerateExecutorMock(System.IO.Path.Combine("workingDir", "NDepend.Console"), workingDir + " /OutDir " + workingDir, "workingDir", 600000);
            var          fileSystem = mocks.Create <IFileSystem>(MockBehavior.Strict).Object;
            MockSequence sequence   = new MockSequence();

            Mock.Get(fileSystem).InSequence(sequence).Setup(_fileSystem => _fileSystem.DirectoryExists(workingDir)).Returns(true).Verifiable();
            Mock.Get(fileSystem).InSequence(sequence).Setup(_fileSystem => _fileSystem.GetFilesInDirectory(workingDir)).Returns(new string[0]).Verifiable();
            Mock.Get(fileSystem).InSequence(sequence).Setup(_fileSystem => _fileSystem.FileExists(System.IO.Path.Combine("workingDir", "NDependResults", "ReportResources.xml"))).Returns(true).Verifiable();
            using (var reader = new StringReader("garbage"))
            {
                Mock.Get(fileSystem).InSequence(sequence).Setup(_fileSystem => _fileSystem.Load(System.IO.Path.Combine("workingDir", "NDependResults", "ReportResources.xml"))).Returns(reader).Verifiable();
                var logger = mocks.Create <ILogger>().Object;
                var task   = new NDependTask(executor, fileSystem, logger);

                Mock.Get(result).SetupProperty(_result => _result.Status);
                result.Status = IntegrationStatus.Unknown;
                Assert.Throws <CruiseControlException>(() => task.Run(result));
                mocks.Verify();
            }
        }
        public void SetUpTests()
        {
            _fileServiceMock    = new Mock <IFileService>(MockBehavior.Strict);
            _nisraServiceMock   = new Mock <INisraFileImportService>(MockBehavior.Strict);
            _storageServiceMock = new Mock <ICloudStorageService>(MockBehavior.Strict);
            _loggingMock        = new Mock <ILoggingService>();
            _mockSequence       = new MockSequence();

            _serverParkName = "ServerParkA";
            _instrumentName = "OPN2010A";
            _bucketPath     = "OPN2010A";
            _tempPath       = @"c:\temp\GUID";

            _instrumentDataDto = new InstrumentDataDto {
                InstrumentDataPath = _bucketPath
            };

            _sut = new InstrumentDataService(
                _fileServiceMock.Object,
                _nisraServiceMock.Object,
                _storageServiceMock.Object,
                _loggingMock.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)
            .Setup(p => p.Dispose());
            _sessionMock.InSequence(sequence)
            .Setup(p => p.Dispose());
        }