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();
        }
        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 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();
            _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()
        {
            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(1, 1000);
            _readBufferSize = (uint) random.Next(0, 1000);
            _writeBufferSize = (uint) random.Next(0, 1000);
            _length = random.Next();

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

            _sequence = new MockSequence();
            _sftpSessionMock.InSequence(_sequence)
                .Setup(p => p.RequestOpen(_path, Flags.Read | 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);

            _sftpFileStream = new SftpFileStream(
                _sftpSessionMock.Object,
                _path,
                FileMode.Create,
                FileAccess.Read,
                (int) _bufferSize);
        }
        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;

        }
        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);
        }
        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();
        }
        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);
        }
        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);
        }
        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);
        }
        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)));
        }
Пример #14
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));
		}
Пример #15
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()
        {
            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 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);
        }
        public void ActivityLogic()
        {
            Mock<IUnitOfWork> uow = new Mock<IUnitOfWork>();
            Mock<IActivityRepository> repo = new Mock<IActivityRepository>();
            Mock<ITeamLogic> teamLogic = new Mock<ITeamLogic>();

            ActivityLogic logic = new ActivityLogic(uow.Object, repo.Object, teamLogic.Object);

            var activity = new Activity();
            var sequence = new MockSequence();
            repo.InSequence(sequence).Setup(r => r.Create(activity));
            repo.InSequence(sequence).Setup(r => r.Update(activity));
            repo.InSequence(sequence).Setup(r => r.Get(activity.Id));
            repo.InSequence(sequence).Setup(r => r.Delete(activity.Id));
            logic.Create(activity);
            logic.Update(activity);
            logic.Get(activity.Id);
            logic.Delete(activity.Id);
        }
Пример #21
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));
        }
        protected void Arrange()
        {
            _closingRegister = new List<EventArgs>();
            _exceptionRegister = new List<ExceptionEventArgs>();

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

            var sequence = new MockSequence();
            _sessionMock.InSequence(sequence).Setup(p => p.IsConnected).Returns(true);
            _sessionMock.InSequence(sequence).Setup(p => p.ConnectionInfo).Returns(_connectionInfoMock.Object);
            _connectionInfoMock.InSequence(sequence).Setup(p => p.Timeout).Returns(TimeSpan.FromSeconds(30));

            _forwardedPort = new ForwardedPortLocal(IPAddress.Loopback.ToString(), "host", 22);
            _forwardedPort.Closing += (sender, args) => _closingRegister.Add(args);
            _forwardedPort.Exception += (sender, args) => _exceptionRegister.Add(args);
            _forwardedPort.Session = _sessionMock.Object;
            _forwardedPort.Start();
            _forwardedPort.Dispose();
        }
Пример #23
0
    public async Task InitializeAsync_InvokesHandlers()
    {
        // Arrange
        var cancellationToken = new CancellationToken();
        var handler1          = new Mock <CircuitHandler>(MockBehavior.Strict);
        var handler2          = new Mock <CircuitHandler>(MockBehavior.Strict);
        var sequence          = new MockSequence();

        handler1
        .InSequence(sequence)
        .Setup(h => h.OnCircuitOpenedAsync(It.IsAny <Circuit>(), cancellationToken))
        .Returns(Task.CompletedTask)
        .Verifiable();

        handler2
        .InSequence(sequence)
        .Setup(h => h.OnCircuitOpenedAsync(It.IsAny <Circuit>(), cancellationToken))
        .Returns(Task.CompletedTask)
        .Verifiable();

        handler1
        .InSequence(sequence)
        .Setup(h => h.OnConnectionUpAsync(It.IsAny <Circuit>(), cancellationToken))
        .Returns(Task.CompletedTask)
        .Verifiable();

        handler2
        .InSequence(sequence)
        .Setup(h => h.OnConnectionUpAsync(It.IsAny <Circuit>(), cancellationToken))
        .Returns(Task.CompletedTask)
        .Verifiable();

        var circuitHost = TestCircuitHost.Create(handlers: new[] { handler1.Object, handler2.Object });

        // Act
        await circuitHost.InitializeAsync(new ProtectedPrerenderComponentApplicationStore(Mock.Of <IDataProtectionProvider>()), cancellationToken);

        // Assert
        handler1.VerifyAll();
        handler2.VerifyAll();
    }
Пример #24
0
    public async Task DisposeAsync_InvokesCircuitHandler()
    {
        // Arrange
        var cancellationToken = new CancellationToken();
        var handler1          = new Mock <CircuitHandler>(MockBehavior.Strict);
        var handler2          = new Mock <CircuitHandler>(MockBehavior.Strict);
        var sequence          = new MockSequence();

        handler1
        .InSequence(sequence)
        .Setup(h => h.OnConnectionDownAsync(It.IsAny <Circuit>(), cancellationToken))
        .Returns(Task.CompletedTask)
        .Verifiable();

        handler2
        .InSequence(sequence)
        .Setup(h => h.OnConnectionDownAsync(It.IsAny <Circuit>(), cancellationToken))
        .Returns(Task.CompletedTask)
        .Verifiable();

        handler1
        .InSequence(sequence)
        .Setup(h => h.OnCircuitClosedAsync(It.IsAny <Circuit>(), cancellationToken))
        .Returns(Task.CompletedTask)
        .Verifiable();

        handler2
        .InSequence(sequence)
        .Setup(h => h.OnCircuitClosedAsync(It.IsAny <Circuit>(), cancellationToken))
        .Returns(Task.CompletedTask)
        .Verifiable();

        var circuitHost = TestCircuitHost.Create(handlers: new[] { handler1.Object, handler2.Object });

        // Act
        await circuitHost.DisposeAsync();

        // Assert
        handler1.VerifyAll();
        handler2.VerifyAll();
    }
Пример #25
0
        public async Task InitializeAsync_InvokesHandlers()
        {
            // Arrange
            var cancellationToken = new CancellationToken();
            var handler1          = new Mock <CircuitHandler>(MockBehavior.Strict);
            var handler2          = new Mock <CircuitHandler>(MockBehavior.Strict);
            var sequence          = new MockSequence();

            handler1
            .InSequence(sequence)
            .Setup(h => h.OnCircuitOpenedAsync(It.IsAny <Circuit>(), cancellationToken))
            .Returns(Task.CompletedTask)
            .Verifiable();

            handler2
            .InSequence(sequence)
            .Setup(h => h.OnCircuitOpenedAsync(It.IsAny <Circuit>(), cancellationToken))
            .Returns(Task.CompletedTask)
            .Verifiable();

            handler1
            .InSequence(sequence)
            .Setup(h => h.OnConnectionUpAsync(It.IsAny <Circuit>(), cancellationToken))
            .Returns(Task.CompletedTask)
            .Verifiable();

            handler2
            .InSequence(sequence)
            .Setup(h => h.OnConnectionUpAsync(It.IsAny <Circuit>(), cancellationToken))
            .Returns(Task.CompletedTask)
            .Verifiable();

            var circuitHost = GetCircuitHost(handlers: new[] { handler1.Object, handler2.Object });

            // Act
            await circuitHost.InitializeAsync(cancellationToken);

            // Assert
            handler1.VerifyAll();
            handler2.VerifyAll();
        }
Пример #26
0
        public void Conversation_Follows_Correct_Sequence()
        {
            string expectedName = _fixture.Create <string>();

            var converser = new Mock <IConverser>(MockBehavior.Strict);

            var sequence = new MockSequence();

            converser.InSequence(sequence).Setup(c => c.AskName()).Returns(expectedName);
            converser.InSequence(sequence).Setup(c => c.LineFeed());
            converser.InSequence(sequence).Setup(c => c.SayHello(expectedName));
            converser.InSequence(sequence).Setup(c => c.LineFeed());

            var script = new QuestionScript(converser.Object);

            script.Go();

            converser.Verify(c => c.AskName(), Times.Once);
            converser.Verify(c => c.SayHello(expectedName), Times.Once);
            converser.Verify(c => c.LineFeed(), Times.Exactly(2));
        }
        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);
        }
Пример #28
0
        public void GoalLogic()
        {
            Mock <IUnitOfWork>         uow          = new Mock <IUnitOfWork>();
            Mock <IGoalRepository>     repo         = new Mock <IGoalRepository>();
            Mock <ITargetRepository>   targetRepo   = new Mock <ITargetRepository>();
            Mock <IActivityRepository> activityRepo = new Mock <IActivityRepository>();

            GoalLogic logic = new GoalLogic(uow.Object, repo.Object, targetRepo.Object, activityRepo.Object);

            var goal     = new Goal();
            var sequence = new MockSequence();

            repo.InSequence(sequence).Setup(r => r.Create(goal));
            repo.InSequence(sequence).Setup(r => r.Update(goal));
            repo.InSequence(sequence).Setup(r => r.Get(goal.Id));
            repo.InSequence(sequence).Setup(r => r.Delete(goal.Id));
            logic.Create(goal);
            logic.Update(goal);
            logic.Get(goal.Id);
            logic.Delete(goal.Id);
        }
Пример #29
0
        public void ReportLogic()
        {
            Mock <IUnitOfWork>         uow          = new Mock <IUnitOfWork>();
            Mock <IReportRepository>   repo         = new Mock <IReportRepository>();
            Mock <IActivityRepository> activityRepo = new Mock <IActivityRepository>();
            Mock <IAccountRepository>  accountRepo  = new Mock <IAccountRepository>();

            ReportLogic logic = new ReportLogic(uow.Object, repo.Object, activityRepo.Object, accountRepo.Object);

            var report   = new Report();
            var sequence = new MockSequence();

            repo.InSequence(sequence).Setup(r => r.Create(report));
            repo.InSequence(sequence).Setup(r => r.Update(report));
            repo.InSequence(sequence).Setup(r => r.Get(report.Id));
            repo.InSequence(sequence).Setup(r => r.Delete(report.Id));
            logic.Create();
            logic.Update(report);
            logic.Get(report.Id);
            logic.Delete(report.Id);
        }
        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(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();
        }
Пример #31
0
        public void It_executes_filters_and_handler()
        {
            var command       = new TestCommand();
            var commandResult = new object();
            var sequence      = new MockSequence();

            var handlerMock = new Mock <IHandler <TestCommand> >(MockBehavior.Strict);
            var filterMock  = new Mock <IFilter <TestCommand> >(MockBehavior.Strict);

            filterMock.InSequence(sequence).Setup(x => x.OnHandling(command));
            handlerMock.InSequence(sequence).Setup(x => x.Handle(command)).Returns(commandResult);
            filterMock.InSequence(sequence).Setup(x => x.OnHandled(command, commandResult));

            var pipeline = new Pipeline(command, new FilterCollection(new object[] { filterMock.Object }),
                                        handlerMock.Object);

            pipeline.Process();

            filterMock.VerifyAll();
            handlerMock.VerifyAll();
        }
Пример #32
0
        public void GetBaseDefinition_ForCustomMethodInfo_NotCached()
        {
            var customMethodInfoMock = new Mock <CustomMethodInfo> (
                MockBehavior.Strict, ReflectionObjectMother.GetSomeType(), "method", MethodAttributes.Public, null, Type.EmptyTypes);

            var fakeMethodDefinition1 = ReflectionObjectMother.GetSomeMethod();
            var fakeMethodDefinition2 = ReflectionObjectMother.GetSomeMethod();

            var sequence = new MockSequence();

            customMethodInfoMock.InSequence(sequence).Setup(mock => mock.GetBaseDefinition()).Returns(fakeMethodDefinition1);
            customMethodInfoMock.InSequence(sequence).Setup(mock => mock.GetBaseDefinition()).Returns(fakeMethodDefinition2);

            var result1 = MethodBaseDefinitionCache.GetBaseDefinition(customMethodInfoMock.Object);
            var result2 = MethodBaseDefinitionCache.GetBaseDefinition(customMethodInfoMock.Object);

            customMethodInfoMock.Verify();

            Assert.That(result1, Is.SameAs(fakeMethodDefinition1));
            Assert.That(result2, Is.SameAs(fakeMethodDefinition2));
        }
        protected void Arrange()
        {
            _closingRegister   = new List <EventArgs>();
            _exceptionRegister = new List <ExceptionEventArgs>();

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

            var sequence = new MockSequence();

            _sessionMock.InSequence(sequence).Setup(p => p.IsConnected).Returns(true);
            _sessionMock.InSequence(sequence).Setup(p => p.ConnectionInfo).Returns(_connectionInfoMock.Object);
            _connectionInfoMock.InSequence(sequence).Setup(p => p.Timeout).Returns(TimeSpan.FromSeconds(30));

            _forwardedPort            = new ForwardedPortLocal(IPAddress.Loopback.ToString(), "host", 22);
            _forwardedPort.Closing   += (sender, args) => _closingRegister.Add(args);
            _forwardedPort.Exception += (sender, args) => _exceptionRegister.Add(args);
            _forwardedPort.Session    = _sessionMock.Object;
            _forwardedPort.Start();
            _forwardedPort.Dispose();
        }
        public void It_executes_filters_and_handler()
        {
            var command = new TestCommand();
            var commandResult = new object();
            var sequence = new MockSequence();

            var handlerMock = new Mock<IHandler<TestCommand>>(MockBehavior.Strict);
            var filterMock = new Mock<IFilter<TestCommand>>(MockBehavior.Strict);

            filterMock.InSequence(sequence).Setup(x => x.OnHandling(command));
            handlerMock.InSequence(sequence).Setup(x => x.Handle(command)).Returns(commandResult);
            filterMock.InSequence(sequence).Setup(x => x.OnHandled(command, commandResult));

            var pipeline = new Pipeline(command, new FilterCollection(new object[] {filterMock.Object}),
                                        handlerMock.Object);

            pipeline.Process();

            filterMock.VerifyAll();
            handlerMock.VerifyAll();
        }
        private void SetupMocks()
        {
            var sequence = new MockSequence();

            _sessionMock.InSequence(sequence)
            .Setup(p => p.ConnectionInfo)
            .Returns(_connectionInfoMock.Object);
            _connectionInfoMock.InSequence(sequence)
            .Setup(p => p.Encoding)
            .Returns(new UTF8Encoding());
            _sessionMock.InSequence(sequence)
            .Setup(p => p.CreateChannelSession())
            .Returns(_channelSessionMock.Object);
            _channelSessionMock.InSequence(sequence)
            .Setup(p => p.Open());
            _channelSessionMock.InSequence(sequence)
            .Setup(p => p.SendPseudoTerminalRequest(_terminalName, _columns, _rows, _width, _height, _terminalModeValues))
            .Throws(_sendPseudoTerminalRequestException);
            _channelSessionMock.InSequence(sequence)
            .Setup(p => p.Dispose());
        }
Пример #36
0
        public static ITransactionController CreateMockTransactionController(
            ITransactionRequest txnReq,
            ICreditCard creditCard)
        {
            var response = TransactionResponseType.DECLINED;

            if (creditCard.ExpiryDate.CompareTo(DateTime.Today) > 0 &&
                txnReq.Amount > 0.0M)
            {
                response = TransactionResponseType.OK;
            }
            // We use a mock here rather than linq to moq because we need to setup execute for a strict mock behavior.
            var mockTxnCtrl = new Mock <ITransactionController>(MockBehavior.Strict);
            var seq         = new MockSequence();

            mockTxnCtrl.InSequence(seq).Setup(ex => ex.Execute());
            mockTxnCtrl.InSequence(seq).Setup(ar => ar.GetApiResponse()).Returns(response);
            mockTxnCtrl.InSequence(seq).SetupGet(r => r.TransactionRequest).Returns(txnReq);

            return(mockTxnCtrl.Object);
        }
        public void ActivityRepository()
        {
            Mock<IDbSetFactory> factory = new Mock<IDbSetFactory>();
            Mock<DbSet<Activity>> dbSet = new Mock<DbSet<Activity>>();

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

            ActivityRepository repo = new ActivityRepository(factory.Object);

            var activity = new Activity();

            var sequence = new MockSequence();
            dbSet.InSequence(sequence).Setup(e => e.Add(activity));
            dbSet.InSequence(sequence).Setup(e => e.Find(activity.Id));
            dbSet.InSequence(sequence).Setup(e => e.Find(activity.Id));
            dbSet.InSequence(sequence).Setup(e => e.Find(activity.Id));
            repo.Create(activity);
            repo.Get(activity.Id);
            repo.Update(activity);
            repo.Delete(activity.Id);
        }
        public void AttainmentRepository()
        {
            Mock<IDbSetFactory> factory = new Mock<IDbSetFactory>();
            Mock<DbSet<Attainment>> dbSet = new Mock<DbSet<Attainment>>();

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

            AttainmentRepository repo = new AttainmentRepository(factory.Object);

            var attainment = new Attainment();

            var sequence = new MockSequence();
            dbSet.InSequence(sequence).Setup(e => e.Add(attainment));
            dbSet.InSequence(sequence).Setup(e => e.Find(attainment.Id));
            dbSet.InSequence(sequence).Setup(e => e.Find(attainment.Id));
            dbSet.InSequence(sequence).Setup(e => e.Find(attainment.Id));
            repo.Create(attainment);
            repo.Get(attainment.Id);
            repo.Update(attainment);
            repo.Delete(attainment.Id);
        }
        public void Test_Server_Interaction_with_Cache_for_Cacheables()
        {
            Request  request   = new Request("foo");
            Response response  = Response.of("foobar");
            var      cacheMock = new Mock <Cache <Request, Response> >(MockBehavior.Strict);
            var      callseq   = new MockSequence();

            cacheMock.InSequence(callseq).Setup(c => c.cached(request)).Returns(false);
            cacheMock.InSequence(callseq).Setup(c => c.put(request, response));
            cacheMock.InSequence(callseq).Setup(c => c.cached(request)).Returns(true);
            cacheMock.InSequence(callseq).Setup(c => c.get(request)).Returns(response);

            Server sut = new BasicServerWithCache(
                cacheMock.Object, // MOCK
                req => true,      // STUB
                req => response   // DUMMY
                );

            sut.serve(request);
            sut.serve(request);
        }
Пример #40
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();

            _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.IsOpen).Returns(true);
            _channelSessionMock.InSequence(seq).Setup(p => p.Close());
            _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)));
        }
Пример #42
0
        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(1, 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.Read | 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.Read, (int)_bufferSize);
        }
Пример #43
0
        private void SetupMocks()
        {
            _mockSequence = new MockSequence();

            _sessionMock.InSequence(_mockSequence)
            .Setup(p => p.ConnectionInfo)
            .Returns(_connectionInfoMock.Object);
            _connectionInfoMock.InSequence(_mockSequence)
            .Setup(p => p.Encoding)
            .Returns(new UTF8Encoding());
            _sessionMock.InSequence(_mockSequence)
            .Setup(p => p.CreateChannelSession())
            .Returns(_channelSessionMock.Object);
            _channelSessionMock.InSequence(_mockSequence)
            .Setup(p => p.Open());
            _channelSessionMock.InSequence(_mockSequence)
            .Setup(p => p.SendPseudoTerminalRequest(_terminalName,
                                                    _widthColumns,
                                                    _heightRows,
                                                    _widthPixels,
                                                    _heightPixels,
                                                    _terminalModes))
            .Returns(true);
            _channelSessionMock.InSequence(_mockSequence)
            .Setup(p => p.SendShellRequest())
            .Returns(true);
            _channelSessionMock.InSequence(_mockSequence)
            .Setup(p => p.SendData(_expectedBytesSent1));
            _channelSessionMock.InSequence(_mockSequence)
            .Setup(p => p.SendData(_expectedBytesSent2));
        }
Пример #44
0
        public void Given_I_Call_UpdateCase_Then_The_Correct_Methods_Are_Called()
        {
            //arrange
            const int newOutcomeCode      = 110;
            const int existingOutcomeCode = 210;

            _blaiseApiMock.Setup(b => b.GetRecordDataFields(_nisraDataRecordMock.Object)).Returns(_newFieldData);
            _blaiseApiMock.Setup(b => b.GetRecordDataFields(_existingDataRecordMock.Object)).Returns(_existingFieldData);
            _catiDataMock.InSequence(_mockSequence).Setup(c => c.RemoveCatiManaBlock(_newFieldData));
            _catiDataMock.InSequence(_mockSequence).Setup(c => c.AddCatiManaCallItems(_newFieldData, _existingFieldData,
                                                                                      newOutcomeCode));
            _blaiseApiMock.Setup(b => b.UpdateCase(_existingDataRecordMock.Object, _newFieldData,
                                                   _instrumentName, _serverParkName));

            //act
            _sut.UpdateCase(_nisraDataRecordMock.Object, _existingDataRecordMock.Object,
                            _instrumentName, _serverParkName, newOutcomeCode, existingOutcomeCode, _primaryKey);

            //assert
            _catiDataMock.Verify(v => v.RemoveCatiManaBlock(_newFieldData), Times.Once);
            _catiDataMock.Verify(v => v.RemoveCallHistoryBlock(_newFieldData), Times.Once);
            _catiDataMock.Verify(v => v.RemoveWebNudgedField(_newFieldData), Times.Once);
            _catiDataMock.Verify(v => v.AddCatiManaCallItems(_newFieldData, _existingFieldData, newOutcomeCode),
                                 Times.Once);

            _blaiseApiMock.Verify(v => v.UpdateCase(_existingDataRecordMock.Object, _newFieldData,
                                                    _instrumentName, _serverParkName), Times.Once);
        }
Пример #45
0
        public void Given_The_Case_Is_Not_Open_In_Cati_When_I_Call_UpdateCase_Then_The_Case_Is_Updated()
        {
            //arrange
            _blaiseApiMock.Setup(b => b.CaseInUseInCati(_existingDataRecordMock.Object)).Returns(false);

            _blaiseApiMock.Setup(b => b.GetRecordDataFields(_nisraDataRecordMock.Object)).Returns(_newFieldData);
            _blaiseApiMock.Setup(b => b.GetRecordDataFields(_existingDataRecordMock.Object)).Returns(_existingFieldData);
            _catiDataMock.InSequence(_mockSequence).Setup(c => c.RemoveCatiManaBlock(_newFieldData));
            _catiDataMock.InSequence(_mockSequence).Setup(c => c.AddCatiManaCallItems(_newFieldData, _existingFieldData,
                                                                                      _outcomeCode));
            _blaiseApiMock.Setup(b => b.UpdateCase(_existingDataRecordMock.Object, _newFieldData,
                                                   _instrumentName, _serverParkName));

            //act
            _sut.UpdateCase(_nisraDataRecordMock.Object, _existingDataRecordMock.Object, _instrumentName, _serverParkName);

            //assert
            _catiDataMock.Verify(v => v.RemoveCatiManaBlock(_newFieldData), Times.Once);
            _catiDataMock.Verify(v => v.RemoveCallHistoryBlock(_newFieldData), Times.Once);
            _catiDataMock.Verify(v => v.RemoveWebNudgedField(_newFieldData), Times.Once);
            _catiDataMock.Verify(v => v.AddCatiManaCallItems(_newFieldData, _existingFieldData, _outcomeCode), Times.Once);

            _blaiseApiMock.Verify(v => v.UpdateCase(_existingDataRecordMock.Object, _newFieldData,
                                                    _instrumentName, _serverParkName), Times.Once);
        }
        public async Task Given_I_Call_InstallInstrument_Then_The_Correct_Services_Are_Called_In_The_Correct_Order()
        {
            //arrange
            const string instrumentFilePath = "d:\\temp\\OPN1234.zip";

            _storageServiceMock.InSequence(_mockSequence).Setup(s => s.DownloadPackageFromInstrumentBucketAsync(
                                                                    _instrumentFile, _tempPath)).ReturnsAsync(instrumentFilePath);

            _fileServiceMock.InSequence(_mockSequence).Setup(b => b
                                                             .UpdateInstrumentFileWithSqlConnection(instrumentFilePath));

            _fileServiceMock.InSequence(_mockSequence).Setup(f => f
                                                             .GetInstrumentNameFromFile(_instrumentFile)).Returns(_instrumentName);

            _blaiseSurveyApiMock.InSequence(_mockSequence).Setup(b => b
                                                                 .InstallSurvey(_instrumentName, _serverParkName, instrumentFilePath, SurveyInterviewType.Cati));

            _fileServiceMock.InSequence(_mockSequence).Setup(f => f
                                                             .RemovePathAndFiles(_tempPath));

            //act
            await _sut.InstallInstrumentAsync(_serverParkName, _instrumentPackageDto, _tempPath);

            //assert
            _storageServiceMock.Verify(v => v.DownloadPackageFromInstrumentBucketAsync(_instrumentFile, _tempPath), Times.Once);
            _fileServiceMock.Verify(v => v.UpdateInstrumentFileWithSqlConnection(instrumentFilePath), Times.Once);
            _fileServiceMock.Verify(v => v.GetInstrumentNameFromFile(_instrumentFile), Times.Once);
            _blaiseSurveyApiMock.Verify(v => v.InstallSurvey(_instrumentName, _serverParkName,
                                                             instrumentFilePath, SurveyInterviewType.Cati), Times.Once);
        }
Пример #47
0
        public void EndExecute_ChannelClosed_ShouldDisposeChannelSession()
        {
            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.IsOpen).Returns(false);
            _channelSessionMock.InSequence(seq).Setup(p => p.Dispose());

            var asyncResult = _sshCommand.BeginExecute();

            _sshCommand.EndExecute(asyncResult);

            _channelSessionMock.Verify(p => p.Dispose(), Times.Once);
        }
Пример #48
0
        public void MembershipRepository()
        {
            Mock <IDbSetFactory>       factory = new Mock <IDbSetFactory>();
            Mock <DbSet <Membership> > dbSet   = new Mock <DbSet <Membership> >();

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

            MembershipRepository repo = new MembershipRepository(factory.Object);

            var Membership = new Membership();

            var sequence = new MockSequence();

            dbSet.InSequence(sequence).Setup(e => e.Add(Membership));
            dbSet.InSequence(sequence).Setup(e => e.Find(Membership.Id));
            dbSet.InSequence(sequence).Setup(e => e.Find(Membership.Id));
            dbSet.InSequence(sequence).Setup(e => e.Find(Membership.Id));
            repo.Create(Membership);
            repo.Get(Membership.Id);
            repo.Update(Membership);
            repo.Delete(Membership.Id);
        }
        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.IsOpen).Returns(true);
            _channelSessionMock.InSequence(seq).Setup(p => p.Close());
            _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)));
        }
Пример #50
0
        public void TeamRepository()
        {
            Mock <IDbSetFactory> factory = new Mock <IDbSetFactory>();
            Mock <DbSet <Team> > dbSet   = new Mock <DbSet <Team> >();

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

            TeamRepository repo = new TeamRepository(factory.Object);

            var Team = new Team();

            var sequence = new MockSequence();

            dbSet.InSequence(sequence).Setup(e => e.Add(Team));
            dbSet.InSequence(sequence).Setup(e => e.Find(Team.Id));
            dbSet.InSequence(sequence).Setup(e => e.Find(Team.Id));
            dbSet.InSequence(sequence).Setup(e => e.Find(Team.Id));
            repo.Create(Team);
            repo.Get(Team.Id);
            repo.Update(Team);
            repo.Delete(Team.Id);
        }
Пример #51
0
        public void MoodRepository()
        {
            Mock <IDbSetFactory> factory = new Mock <IDbSetFactory>();
            Mock <DbSet <Mood> > dbSet   = new Mock <DbSet <Mood> >();

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

            MoodRepository repo = new MoodRepository(factory.Object);

            var Mood = new Mood();

            var sequence = new MockSequence();

            dbSet.InSequence(sequence).Setup(e => e.Add(Mood));
            dbSet.InSequence(sequence).Setup(e => e.Find(Mood.Id));
            dbSet.InSequence(sequence).Setup(e => e.Find(Mood.Id));
            dbSet.InSequence(sequence).Setup(e => e.Find(Mood.Id));
            repo.Create(Mood);
            repo.Get(Mood.Id);
            repo.Update(Mood);
            repo.Delete(Mood.Id);
        }
Пример #52
0
        public void PathRepository()
        {
            Mock <IDbSetFactory> factory = new Mock <IDbSetFactory>();
            Mock <DbSet <Path> > dbSet   = new Mock <DbSet <Path> >();

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

            PathRepository repo = new PathRepository(factory.Object);

            var Path = new Path();

            var sequence = new MockSequence();

            dbSet.InSequence(sequence).Setup(e => e.Add(Path));
            dbSet.InSequence(sequence).Setup(e => e.Find(Path.Id));
            dbSet.InSequence(sequence).Setup(e => e.Find(Path.Id));
            dbSet.InSequence(sequence).Setup(e => e.Find(Path.Id));
            repo.Create(Path);
            repo.Get(Path.Id);
            repo.Update(Path);
            repo.Delete(Path.Id);
        }
Пример #53
0
        public void GoalRepository()
        {
            Mock <IDbSetFactory> factory = new Mock <IDbSetFactory>();
            Mock <DbSet <Goal> > dbSet   = new Mock <DbSet <Goal> >();

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

            GoalRepository repo = new GoalRepository(factory.Object);

            var Goal = new Goal();

            var sequence = new MockSequence();

            dbSet.InSequence(sequence).Setup(e => e.Add(Goal));
            dbSet.InSequence(sequence).Setup(e => e.Find(Goal.Id));
            dbSet.InSequence(sequence).Setup(e => e.Find(Goal.Id));
            dbSet.InSequence(sequence).Setup(e => e.Find(Goal.Id));
            repo.Create(Goal);
            repo.Get(Goal.Id);
            repo.Update(Goal);
            repo.Delete(Goal.Id);
        }
Пример #54
0
        public void ReportRepository()
        {
            Mock <IDbSetFactory>   factory = new Mock <IDbSetFactory>();
            Mock <DbSet <Report> > dbSet   = new Mock <DbSet <Report> >();

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

            ReportRepository repo = new ReportRepository(factory.Object);

            var Report = new Report();

            var sequence = new MockSequence();

            dbSet.InSequence(sequence).Setup(e => e.Add(Report));
            dbSet.InSequence(sequence).Setup(e => e.Find(Report.Id));
            dbSet.InSequence(sequence).Setup(e => e.Find(Report.Id));
            dbSet.InSequence(sequence).Setup(e => e.Find(Report.Id));
            repo.Create(Report);
            repo.Get(Report.Id);
            repo.Update(Report);
            repo.Delete(Report.Id);
        }
Пример #55
0
        public void BadgeRepository()
        {
            Mock <IDbSetFactory>  factory = new Mock <IDbSetFactory>();
            Mock <DbSet <Badge> > dbSet   = new Mock <DbSet <Badge> >();

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

            BadgeRepository repo = new BadgeRepository(factory.Object);

            var badge = new Badge();

            var sequence = new MockSequence();

            dbSet.InSequence(sequence).Setup(e => e.Add(badge));
            dbSet.InSequence(sequence).Setup(e => e.Find(badge.Id));
            dbSet.InSequence(sequence).Setup(e => e.Find(badge.Id));
            dbSet.InSequence(sequence).Setup(e => e.Find(badge.Id));
            repo.Create(badge);
            repo.Get(badge.Id);
            repo.Update(badge);
            repo.Delete(badge.Id);
        }
Пример #56
0
        public void AttainmentRepository()
        {
            Mock <IDbSetFactory>       factory = new Mock <IDbSetFactory>();
            Mock <DbSet <Attainment> > dbSet   = new Mock <DbSet <Attainment> >();

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

            AttainmentRepository repo = new AttainmentRepository(factory.Object);

            var attainment = new Attainment();

            var sequence = new MockSequence();

            dbSet.InSequence(sequence).Setup(e => e.Add(attainment));
            dbSet.InSequence(sequence).Setup(e => e.Find(attainment.Id));
            dbSet.InSequence(sequence).Setup(e => e.Find(attainment.Id));
            dbSet.InSequence(sequence).Setup(e => e.Find(attainment.Id));
            repo.Create(attainment);
            repo.Get(attainment.Id);
            repo.Update(attainment);
            repo.Delete(attainment.Id);
        }
Пример #57
0
        public void ActivityRepository()
        {
            Mock <IDbSetFactory>     factory = new Mock <IDbSetFactory>();
            Mock <DbSet <Activity> > dbSet   = new Mock <DbSet <Activity> >();

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

            ActivityRepository repo = new ActivityRepository(factory.Object);

            var activity = new Activity();

            var sequence = new MockSequence();

            dbSet.InSequence(sequence).Setup(e => e.Add(activity));
            dbSet.InSequence(sequence).Setup(e => e.Find(activity.Id));
            dbSet.InSequence(sequence).Setup(e => e.Find(activity.Id));
            dbSet.InSequence(sequence).Setup(e => e.Find(activity.Id));
            repo.Create(activity);
            repo.Get(activity.Id);
            repo.Update(activity);
            repo.Delete(activity.Id);
        }
        public void AttainmentLogic()
        {
            Mock<IUnitOfWork> uow = new Mock<IUnitOfWork>();
            Mock<IAttainmentRepository> repo = new Mock<IAttainmentRepository>();
            Mock<IBadgeRepository> badgeRepo = new Mock<IBadgeRepository>();
            Mock<IActivityRepository> activityRepo = new Mock<IActivityRepository>();
            Mock<ITargetRepository> targetRepo = new Mock<ITargetRepository>();
            Mock<ITeamLogic> teamLogic = new Mock<ITeamLogic>();

            AttainmentLogic logic = new AttainmentLogic(uow.Object, repo.Object, badgeRepo.Object, activityRepo.Object, targetRepo.Object, teamLogic.Object);

            var attainment = new Attainment();
            var sequence = new MockSequence();
            repo.InSequence(sequence).Setup(r => r.Create(attainment));
            repo.InSequence(sequence).Setup(r => r.Update(attainment));
            repo.InSequence(sequence).Setup(r => r.Get(attainment.Id));
            repo.InSequence(sequence).Setup(r => r.Delete(attainment.Id));
            logic.Create(attainment);
            logic.Update(attainment);
            logic.Get(attainment.Id);
            logic.Delete(attainment.Id);
        }
Пример #59
0
        public void StatusRepository()
        {
            Mock <IDbSetFactory>   factory = new Mock <IDbSetFactory>();
            Mock <DbSet <Status> > dbSet   = new Mock <DbSet <Status> >();

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

            StatusRepository repo = new StatusRepository(factory.Object);

            var Status = new Status();

            var sequence = new MockSequence();

            dbSet.InSequence(sequence).Setup(e => e.Add(Status));
            dbSet.InSequence(sequence).Setup(e => e.Find(Status.Id));
            dbSet.InSequence(sequence).Setup(e => e.Find(Status.Id));
            dbSet.InSequence(sequence).Setup(e => e.Find(Status.Id));
            repo.Create(Status);
            repo.Get(Status.Id);
            repo.Update(Status);
            repo.Delete(Status.Id);
        }
        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();
        }