Example #1
0
        /// <inheritdoc />
        public override async Task AddToBatchAsync(IExpectation expectation, CancellationToken cancellationToken)
        {
            var entityInfo = ExtractEntityInfo();

            var cmd = CurrentCommand;

            Driver.AdjustCommand(cmd);

            if (entityInfo == null)
            {
                //Выполняем текущий батч
                await ExecuteBatchWithTimingAsync(CurrentCommand, cancellationToken);

                //Исполняем команду
                LogCommand(cmd);
                var rowCount = await ExecuteNonQueryAsync(cmd, cancellationToken);

                expectation.VerifyOutcomeNonBatched(rowCount, cmd);
                return;
            }

            mCurrentEntites.Add(entityInfo);

            if (mCurrentEntites.Count >= BatchSize)
            {
                await ExecuteBatchWithTimingAsync(CurrentCommand, cancellationToken);
            }
        }
        /// <summary>
        /// Add a method call for this state' mock.
        /// This allows derived method to cleanly get a the setupresult behavior while adding
        /// their own.
        /// </summary>
        /// <param name="invocation">The invocation for this method</param>
        /// <param name="method">The method that was called</param>
        /// <param name="args">The arguments this method was called with</param>
        protected virtual object DoMethodCall(IInvocation invocation, MethodInfo method, object[] args)
        {
            IExpectation expectation = repository.Replayer.GetRecordedExpectation(invocation, proxy, method, args);

            RhinoMocks.Logger.LogReplayedExpectation(invocation, expectation);
            return(expectation.ReturnOrThrow(invocation, args));
        }
Example #3
0
        /// <summary>
        /// Executes the current <see cref="IDbCommand"/> and compares the row Count
        /// to the <c>expectedRowCount</c>.
        /// </summary>
        /// <param name="expectation">
        /// The expected number of rows affected by the query.  A value of less than <c>0</c>
        /// indicates that the number of rows to expect is unknown or should not be a factor.
        /// </param>
        /// <exception cref="HibernateException">
        /// Thrown when there is an expected number of rows to be affected and the
        /// actual number of rows is different.
        /// </exception>
        public override void AddToBatch(IExpectation expectation)
        {
            IDbCommand cmd      = CurrentCommand;
            int        rowCount = ExecuteNonQuery(cmd);

            expectation.VerifyOutcomeNonBatched(rowCount, cmd);
        }
        /// <summary>
        /// Get the expectation for this method on this object with this arguments
        /// </summary>
        public IExpectation GetRecordedExpectation(IInvocation invocation, object proxy, MethodInfo method, object[] args)
        {
            Validate.IsNotNull(proxy, "proxy");
            Validate.IsNotNull(method, "method");
            Validate.IsNotNull(args, "args");
            if (replayerToCall != null)
            {
                return(replayerToCall.GetRecordedExpectation(invocation, proxy, method, args));
            }

            //merge recorders that contains only a single empty recorder
            if (recordedActions.Count == 1 && recordedActions[0] is IMethodRecorder)
            {
                replayerToCall = (IMethodRecorder)recordedActions[0];
                return(replayerToCall.GetRecordedExpectation(invocation, proxy, method, args));
            }

            IExpectation expectation = DoGetRecordedExpectation(invocation, proxy, method, args);

            if (HasExpectations == false)
            {
                MoveToParentReplayer();
            }
            return(expectation);
        }
 /// <summary>
 /// Creates a new <see cref="ConstraintsExpectation"/> instance.
 /// </summary>
 /// <param name="expectation">Expectation.</param>
 /// <param name="constraints">Constraints.</param>
 public ConstraintsExpectation(IExpectation expectation, AbstractConstraint[] constraints)
     : base(expectation)
 {
     Validate.IsNotNull(() => constraints);
     this.constraints = constraints;
     ConstraintsMatchMethod();
 }
        public void ApplyExpectation(IExpectation expectation)
        {
            if (expectation is HasTypeExpectation)
            {
                HandleHasTypeExpectation(expectation as HasTypeExpectation);
                return;
            }

            if (expectation is HasInstanceExpectation)
            {
                HandleHasInstanceExpectation(expectation as HasInstanceExpectation);
                return;
            }

            if (expectation is DoesNotHaveTypeExpectation)
            {
                HandleDoesNotHaveTypeExpectation(expectation as DoesNotHaveTypeExpectation);
                return;
            }

            if (expectation is DoesNotHaveInstanceExpectation)
            {
                HandleDoesNotHaveInstanceExpectation(expectation as DoesNotHaveInstanceExpectation);
                return;
            }

            // TODO: Open/Closed priciple!?
            // TODO: Refactor to Expectation applyer!? Use extension methods?

            throw new ArgumentOutOfRangeException("expectation");
        }
        /// <inheritdoc />
        public override void AddToBatch(IExpectation expectation)
        {
            var entityInfo = ExtractEntityInfo();

            var cmd = CurrentCommand;

            if (entityInfo == null)
            {
                //Выполняем текущий батч
                ExecuteBatchWithTiming(CurrentCommand);

                //Исполняем команду
                Driver.AdjustCommand(cmd);
                LogCommand(cmd);
                var rowCount = ExecuteNonQuery(cmd);
                expectation.VerifyOutcomeNonBatched(rowCount, cmd);
                return;
            }

            mCurrentEntites.Add(entityInfo);

            if (mCurrentEntites.Count >= BatchSize)
            {
                ExecuteBatchWithTiming(CurrentCommand);
            }
        }
		public override async Task AddToBatchAsync(IExpectation expectation, CancellationToken cancellationToken)
		{
			cancellationToken.ThrowIfCancellationRequested();
			totalExpectedRowsAffected += expectation.ExpectedRowCount;
			var batchUpdate = CurrentCommand;
			await (PrepareAsync(batchUpdate, cancellationToken)).ConfigureAwait(false);
			Driver.AdjustCommand(batchUpdate);
			string lineWithParameters = null;
			var sqlStatementLogger = Factory.Settings.SqlStatementLogger;
			if (sqlStatementLogger.IsDebugEnabled || Log.IsDebugEnabled())
			{
				lineWithParameters = sqlStatementLogger.GetCommandLineWithParameters(batchUpdate);
				var formatStyle = sqlStatementLogger.DetermineActualStyle(FormatStyle.Basic);
				lineWithParameters = formatStyle.Formatter.Format(lineWithParameters);
				currentBatchCommandsLog.Append("command ")
					.Append(currentBatch.CountOfCommands)
					.Append(":")
					.AppendLine(lineWithParameters);
			}
			if (Log.IsDebugEnabled())
			{
				Log.Debug("Adding to batch:{0}", lineWithParameters);
			}
			currentBatch.Append(batchUpdate);

			if (currentBatch.CountOfCommands >= batchSize)
			{
				await (DoExecuteBatchAsync(batchUpdate, cancellationToken)).ConfigureAwait(false);
			}
		}
 public override void AddToBatch(IExpectation expectation)
 {
     #region NHibernate code
     _totalExpectedRowsAffected += expectation.ExpectedRowCount;
     IDbCommand batchUpdate = CurrentCommand;
     Driver.AdjustCommand(batchUpdate);
     string lineWithParameters = null;
     var sqlStatementLogger = Factory.Settings.SqlStatementLogger;
     if (sqlStatementLogger.IsDebugEnabled || Log.IsDebugEnabled)
     {
         lineWithParameters = sqlStatementLogger.GetCommandLineWithParameters(batchUpdate);
         var formatStyle = sqlStatementLogger.DetermineActualStyle(FormatStyle.Basic);
         lineWithParameters = formatStyle.Formatter.Format(lineWithParameters);
         _currentBatchCommandsLog.Append("command ")
             .Append(_currentBatch.CountOfCommands)
             .Append(":")
             .AppendLine(lineWithParameters);
     }
     if (Log.IsDebugEnabled)
     {
         Log.Debug("Adding to batch:" + lineWithParameters);
     }
     #endregion
     _currentBatch.Append((System.Data.SqlClient.SqlCommand)(ReliableSqlCommand)batchUpdate);
     #region NHibernate code
     if (_currentBatch.CountOfCommands >= _batchSize)
     {
         ExecuteBatchWithTiming(batchUpdate);
     }
     #endregion
 }
        public override void AddToBatch(IExpectation expectation)
        {
            totalExpectedRowsAffected += expectation.ExpectedRowCount;
            var batchUpdate = CurrentCommand;

            string lineWithParameters = null;
            var sqlStatementLogger = Factory.Settings.SqlStatementLogger;
            if (sqlStatementLogger.IsDebugEnabled || log.IsDebugEnabled)
            {
                lineWithParameters = sqlStatementLogger.GetCommandLineWithParameters(batchUpdate);
                var formatStyle = sqlStatementLogger.DetermineActualStyle(FormatStyle.Basic);
                lineWithParameters = formatStyle.Formatter.Format(lineWithParameters);
                currentBatchCommandsLog.Append("command ")
                    .Append(currentBatch.CountOfCommands)
                    .Append(":")
                    .AppendLine(lineWithParameters);
            }
            if (log.IsDebugEnabled)
            {
                log.Debug("Adding to batch:" + lineWithParameters);
            }
            currentBatch.Append(((ProfiledSqlDbCommand)batchUpdate).Command);

            if (currentBatch.CountOfCommands >= batchSize)
            {
                ExecuteBatchWithTiming(batchUpdate);
            }
        }
        public override void AddToBatch(IExpectation expectation)
        {
            _totalExpectedRowsAffected += expectation.ExpectedRowCount;
            var batchUpdate = CurrentCommand;
            Driver.AdjustCommand(batchUpdate);
            var sqlStatementLogger = Factory.Settings.SqlStatementLogger;
            if (sqlStatementLogger.IsDebugEnabled)
            {
                var lineWithParameters = sqlStatementLogger.GetCommandLineWithParameters(batchUpdate);
                var formatStyle = sqlStatementLogger.DetermineActualStyle(FormatStyle.Basic);
                lineWithParameters = formatStyle.Formatter.Format(lineWithParameters);
                _currentBatchCommandsLog.Append("command ")
                    .Append(_currentBatch.CountOfCommands)
                    .Append(":")
                    .AppendLine(lineWithParameters);
            }

            var update = batchUpdate as ProfiledGenericDbCommand<SqlCommand>;
            if (update != null)
            {
                _currentBatch.Append(update.Command);
            }
            else
            {
                _currentBatch.Append((SqlCommand)batchUpdate);
            }

            if (_currentBatch.CountOfCommands >= _batchSize)
            {
                ExecuteBatchWithTiming(batchUpdate);
            }
        }
Example #12
0
        public void ApplyExpectation(IExpectation expectation)
        {
            if (expectation is HasTypeExpectation)
            {
                HandleHasTypeExpectation(expectation as HasTypeExpectation);
                return;
            }

            if (expectation is HasInstanceExpectation)
            {
                HandleHasInstanceExpectation(expectation as HasInstanceExpectation);
                return;
            }

            if (expectation is DoesNotHaveTypeExpectation)
            {
                HandleDoesNotHaveTypeExpectation(expectation as DoesNotHaveTypeExpectation);
                return;
            }

            if (expectation is DoesNotHaveInstanceExpectation)
            {
                HandleDoesNotHaveInstanceExpectation(expectation as DoesNotHaveInstanceExpectation);
                return;
            }

            // TODO: Open/Closed priciple!?
            // TODO: Refactor to Expectation applyer!? Use extension methods?

            throw new ArgumentOutOfRangeException("expectation");
        }
        public void HasCallLeftWhenThereArentCallLeft()
        {
            Range        r    = new Range(0, 1);
            IExpectation test = GetExpectation(method, r, 1);

            Assert.False(test.CanAcceptCalls);
        }
        public override void AddToBatch(IExpectation expectation)
        {
            _totalExpectedRowsAffected += expectation.ExpectedRowCount;
            var batchUpdate = CurrentCommand;

            Driver.AdjustCommand(batchUpdate);
            var sqlStatementLogger = Factory.Settings.SqlStatementLogger;

            if (sqlStatementLogger.IsDebugEnabled)
            {
                var lineWithParameters = sqlStatementLogger.GetCommandLineWithParameters(batchUpdate);
                var formatStyle        = sqlStatementLogger.DetermineActualStyle(FormatStyle.Basic);
                lineWithParameters = formatStyle.Formatter.Format(lineWithParameters);
                _currentBatchCommandsLog.Append("command ")
                .Append(_currentBatch.CountOfCommands)
                .Append(":")
                .AppendLine(lineWithParameters);
            }

            var update = batchUpdate as ProfiledSqlDbCommand;

            if (update != null)
            {
                _currentBatch.Append(update.SqlCommand);
            }
            else
            {
                _currentBatch.Append((SqlCommand)batchUpdate);
            }

            if (_currentBatch.CountOfCommands >= _batchSize)
            {
                ExecuteBatchWithTiming(batchUpdate);
            }
        }
Example #15
0
        public override void AddToBatch(IExpectation expectation)
        {
            totalExpectedRowsAffected += expectation.ExpectedRowCount;
            IDbCommand batchUpdate = CurrentCommand;

            Prepare(batchUpdate);
            Driver.AdjustCommand(batchUpdate);
            string lineWithParameters = null;
            var    sqlStatementLogger = Factory.Settings.SqlStatementLogger;

            if (sqlStatementLogger.IsDebugEnabled || Log.IsDebugEnabled)
            {
                lineWithParameters = sqlStatementLogger.GetCommandLineWithParameters(batchUpdate);
                var formatStyle = sqlStatementLogger.DetermineActualStyle(FormatStyle.Basic);
                lineWithParameters = formatStyle.Formatter.Format(lineWithParameters);
                currentBatchCommandsLog.Append("command ")
                .Append(currentBatch.CountOfCommands)
                .Append(":")
                .AppendLine(lineWithParameters);
            }
            if (Log.IsDebugEnabled)
            {
                Log.Debug("Adding to batch:" + lineWithParameters);
            }
            currentBatch.Append((MySqlCommand)batchUpdate);

            if (currentBatch.CountOfCommands >= batchSize)
            {
                DoExecuteBatch(batchUpdate);
            }
        }
		/// <summary>
		/// Executes the current <see cref="IDbCommand"/> and compares the row Count
		/// to the <c>expectedRowCount</c>.
		/// </summary>
		/// <param name="expectation">
		/// The expected number of rows affected by the query.  A value of less than <c>0</c>
		/// indicates that the number of rows to expect is unknown or should not be a factor.
		/// </param>
		/// <exception cref="HibernateException">
		/// Thrown when there is an expected number of rows to be affected and the
		/// actual number of rows is different.
		/// </exception>
		public override void AddToBatch(IExpectation expectation)
		{
			IDbCommand cmd = CurrentCommand;
			Driver.AdjustCommand(cmd);
			int rowCount = ExecuteNonQuery(cmd);
			expectation.VerifyOutcomeNonBatched(rowCount, cmd);
		}
        public override void AddToBatch(IExpectation expectation)
        {
            _totalExpectedRowsAffected += expectation.ExpectedRowCount;
            var batchUpdate = CurrentCommand;

            Driver.AdjustCommand(batchUpdate);
            string lineWithParameters = null;
            var    sqlStatementLogger = Factory.Settings.SqlStatementLogger;

            if (sqlStatementLogger.IsDebugEnabled || Log.IsDebugEnabled())
            {
                lineWithParameters = sqlStatementLogger.GetCommandLineWithParameters(batchUpdate);
                var formatStyle = sqlStatementLogger.DetermineActualStyle(FormatStyle.Basic);
                lineWithParameters = formatStyle.Formatter.Format(lineWithParameters);
                _currentBatchCommandsLog.Append("command ")
                .Append(_currentBatch.CountOfCommands)
                .Append(":")
                .AppendLine(lineWithParameters);
            }
            if (Log.IsDebugEnabled())
            {
                Log.Debug("Adding to batch:{0}", lineWithParameters);
            }
            _currentBatch.Append((System.Data.SqlClient.SqlCommand)Driver.UnwrapDbCommand(batchUpdate));

            if (_currentBatch.CountOfCommands >= _batchSize)
            {
                ExecuteBatchWithTiming(batchUpdate);
            }
        }
        /// <summary>
        /// Logs the expectation as it was recorded
        /// </summary>
        /// <param name="invocation">The invocation.</param>
        /// <param name="expectation">The expectation.</param>
        public void LogReplayedExpectation(IInvocation invocation, IExpectation expectation)
        {
            string methodCall = MethodCallUtil.StringPresentation(invocation, invocation.Method, invocation.Arguments);

            WriteLine("Replayed expectation: {0}", methodCall);
            WriteCurrentMethod();
        }
Example #19
0
 public static void Empty <T>(this IExpectation <T> e, string message, params object[] args)
 {
     // We have to enforce the constraint at runtime because Expectation<object>
     // is possible and it is meant to represent type erasure caused
     // with EnumerableExpectation.All() or Any()
     e.As <IEnumerable>().Like(Matchers.BeEmpty(), message, (object[])args);
 }
Example #20
0
        public void Should_throw_when_expectation_is_null()
        {
            // Arrange
            IExpectation expectation = null;

            // Act & assert
            Assert.Throws <ArgumentNullException>(() => _expectationExpression.Add(expectation));
        }
 public RecorderChangerTests()
 {
     proxy = new object();
     method = typeof (object).GetMethod("ToString");
     expectation = new AnyArgsExpectation(new FakeInvocation(method), new Range(1, 1));
     args = new object[0];
     mocks = new MockRepository();
 }
 public RecorderChangerTests()
 {
     proxy       = new object();
     method      = typeof(object).GetMethod("ToString");
     expectation = new AnyArgsExpectation(new FakeInvocation(method), new Range(1, 1));
     args        = new object[0];
     mocks       = new MockRepository();
 }
        public static Exception ToThrow(this IExpectation <Action> expectation)
        {
            var exception = Capture(expectation.Actual);

            ExpectationHelper.PassFail(exception != null, expectation);

            return(exception);
        }
Example #24
0
        private void AssertDescriptionIsEqual(IExpectation expectation, string expected)
        {
            DescriptionWriter writer = new DescriptionWriter();

            expectation.DescribeActiveExpectationsTo(writer);

            Assert.AreEqual(expected, writer.ToString());
        }
        public void ExpectationEqualToSameTypeWithSameArgs()
        {
            IExpectation one = GetExpectation(method, new Range(2, 3), 4);
            IExpectation two = GetExpectation(method, new Range(2, 3), 4);

            Assert.NotSame(one, two);
            Assert.Equal(one, two);
        }
        public void SettingMethodRepeatToAnyMeansThatCanAlwaysAcceptCalls()
        {
            IExpectation test = GetExpectation(method, new Range(0, 0), 5);

            Assert.False(test.CanAcceptCalls);
            test.RepeatableOption = RepeatableOption.Any;
            Assert.True(test.CanAcceptCalls);
        }
		protected static void SetupExpectation(IExpectation expectation, Range r, int actual)
		{
			expectation.Expected = r;
			for (int i = 0; i < actual; i++)
			{
				expectation.AddActualCall();
			}
		}
        public void SettingReaptableToAnyMeansThatExceptionIsAlwaysSatisfied()
        {
            IExpectation test = GetExpectation(method, new Range(0, 1), 5);

            Assert.False(test.ExpectationSatisfied);
            test.RepeatableOption = RepeatableOption.Any;
            Assert.True(test.ExpectationSatisfied);
        }
 protected static void SetupExpectation(IExpectation expectation, Range r, int actual)
 {
     expectation.Expected = r;
     for (int i = 0; i < actual; i++)
     {
         expectation.AddActualCall();
     }
 }
        public void AbstractExpectationPropertiesReturnTheValuesSetByDerivedClass()
        {
            Range        r    = new Range(0, 30);
            IExpectation test = GetExpectation(method, r, 5);

            Assert.Equal(r, test.Expected);
            Assert.Equal(5, test.ActualCallsCount);
        }
        public void HashCodeIsTheSameAcrossInvocations()
        {
            Range        r          = new Range(0, 5);
            MethodInfo   voidMethod = typeof(IDemo).GetMethod("VoidNoArgs");
            IExpectation test       = GetExpectation(voidMethod, r, 0);

            Assert.Equal(test.GetHashCode(), test.GetHashCode());
        }
        public void ExpectationIsClosedForVoidMethod()
        {
            Range        r          = new Range(0, 5);
            MethodInfo   voidMethod = typeof(IDemo).GetMethod("VoidNoArgs");
            IExpectation test       = GetExpectation(voidMethod, r, 0);

            Assert.True(test.ActionsSatisfied);
        }
 /// <summary>
 /// Logs the expectation as it was recorded
 /// </summary>
 /// <param name="invocation">The invocation.</param>
 /// <param name="expectation">The expectation.</param>
 public void LogReplayedExpectation(IInvocation invocation, IExpectation expectation)
 {
     if (_logReplayed)
     {
         string methodCall =
             MethodCallUtil.StringPresentation(invocation, invocation.Method, invocation.Arguments);
         Trace.WriteLine(string.Format("Replayed expectation: {0}", methodCall));
     }
 }
Example #34
0
 /// <summary>
 /// Creates a new <see cref="ProxyMethodExpectationTriplet"/> instance.
 /// </summary>
 /// <param name="proxy">Proxy.</param>
 /// <param name="method">Method.</param>
 /// <param name="expectation">Expectation.</param>
 public ProxyMethodExpectationTriplet(object proxy, MethodInfo method, IExpectation expectation)
 {
     Validate.IsNotNull(proxy, "proxy");
     Validate.IsNotNull(method, "method");
     Validate.IsNotNull(expectation, "expectation");
     this.proxy       = proxy;
     this.method      = method;
     this.expectation = expectation;
 }
 /// <summary>
 /// Creates a new <see cref="ProxyMethodExpectationTriplet"/> instance.
 /// </summary>
 /// <param name="proxy">Proxy.</param>
 /// <param name="method">Method.</param>
 /// <param name="expectation">Expectation.</param>
 public ProxyMethodExpectationTriplet(object proxy, MethodInfo method, IExpectation expectation)
 {
     Validate.IsNotNull(proxy, "proxy");
     Validate.IsNotNull(method, "method");
     Validate.IsNotNull(expectation, "expectation");
     this.proxy = proxy;
     this.method = method;
     this.expectation = expectation;
 }
        public void AddExpectation(IExpectation expectation, bool hasHigherPrecedence)
        {
            if (expectation == null)
            {
                throw new ArgumentNullException("expectation");
            }

            expectationScope.Add(expectation, hasHigherPrecedence);
        }
        /// <summary>
        /// Records the specified call with the specified args on the mocked object.
        /// </summary>
        /// <param name="proxy">Mocked object.</param>
        /// <param name="method">Method.</param>
        /// <param name="expectation">Expectation.</param>
        protected override void DoRecord(object proxy, MethodInfo method, IExpectation expectation)
        {
            Validate.IsNotNull(proxy, "proxy");
            Validate.IsNotNull(method, "method");
            Validate.IsNotNull(expectation, "expectation");
            ProxyMethodExpectationTriplet entry = new ProxyMethodExpectationTriplet(proxy, method, expectation);

            recordedActions.Add(entry);
        }
        public void AddExpectation(IExpectation expectation)
        {
            if (expectation == null)
            {
                throw new ArgumentNullException(nameof(expectation));
            }

            _expectations.Add(new ScenarioExpectation(CurrentActor, expectation));
        }
 public override void AddToBatch(IExpectation expectation)
 {
     if (StatsEnabled)
     {
         batchSizes[currentBatch]++;
         Console.WriteLine("Adding to batch [" + batchSQL + "]");
     }
     base.AddToBatch(expectation);
 }
 /// <summary>
 /// Logs the expectation as is was recorded
 /// </summary>
 /// <param name="invocation">
 /// The invocation.
 /// </param>
 /// <param name="expectation">
 /// The expectation.
 /// </param>
 public void LogRecordedExpectation(IInvocation invocation, IExpectation expectation)
 {
     if (_logRecorded)
     {
         string methodCall =
             MethodCallUtil.StringPresentation(invocation, invocation.Method, invocation.Arguments);
         Trace.WriteLine(string.Format("Recorded expectation: {0}", methodCall));
     }
 }
Example #41
0
        public void setup()
        {
            example = new Example();

            failingExpectation = CreateSubstituteExpectation(e => e.IsFail.Returns(true));
            passingExpectation = CreateSubstituteExpectation(e => e.IsPass.Returns(true));
            pendingExpectation = CreateSubstituteExpectation(e => e.IsPending.Returns(true));

            exampleReporter = Substitute.For<IExampleReporter>();
        }
        public ComplexOrderingTests()
        {
            recorder = new UnorderedMethodRecorder(new ProxyMethodExpectationsDictionary());
            nestedRecorder = new UnorderedMethodRecorder(new ProxyMethodExpectationsDictionary());
            recorder.AddRecorder(nestedRecorder);

            proxy = new object();
            method = typeof (object).GetMethod("ToString");
            expectation = new AnyArgsExpectation(new FakeInvocation(method), new Range(1, 1));
            args = new object[0];
        }
Example #43
0
        TestResult CreateTestResultFromExpectation(IExpectation expectation)
        {
            var result = new TestResult(new TestName { Name = expectation.Message });

            if (expectation.IsFail)
                result.Failure(expectation.ToString(), "");
            else if (expectation.IsPass)
                result.Success();
            else if (expectation.IsPending)
                result.Ignore(expectation.ToString(), "");

            return result;
        }
        public override void AddToBatch(IExpectation expectation)
        {
            totalExpectedRowsAffected += expectation.ExpectedRowCount;
            log.Debug("Adding to batch:");
            IDbCommand batchUpdate = CurrentCommand;
            LogCommand(batchUpdate);

            CurrentBatch.Append(batchUpdate);
            if (CurrentBatch.CountOfCommands >= batchSize)
            {
                DoExecuteBatch(batchUpdate);
            }
        }
		public override void AddToBatch(IExpectation expectation)
		{
            bool firstOnBatch = true;
			totalExpectedRowsAffected += expectation.ExpectedRowCount;
			log.Info("Adding to batch");
            LogCommand(CurrentCommand);

            if (currentBatch == null)
            {
                // use first command as the batching command
                currentBatch = CurrentCommand;
                parameterValueArrayHashTable = new Hashtable();
                //oracle does not allow array containing all null values
                // so this HashTable is keeping track if all values are null or not
                parameterIsAllNullsHashTable = new Hashtable();
            }
            else
            {
                firstOnBatch = false;
            }

            ArrayList parameterValueArray;
            foreach (IDataParameter currentParameter in CurrentCommand.Parameters)
            {                
                if (firstOnBatch)
                {
                    parameterValueArray = new ArrayList();
                    parameterValueArrayHashTable.Add(currentParameter.ParameterName, parameterValueArray);
                    parameterIsAllNullsHashTable.Add(currentParameter.ParameterName, true);
                }
                else
                {
                    parameterValueArray = parameterValueArrayHashTable[currentParameter.ParameterName] as ArrayList;
                }

                if (currentParameter.Value != System.DBNull.Value)
                {
                    parameterIsAllNullsHashTable[currentParameter.ParameterName] = false;
                }
                parameterValueArray.Add(currentParameter.Value);
            } 
            
            countOfCommands++;

            if (countOfCommands >= batchSize)
            {
                DoExecuteBatch(currentBatch);
            }

            
		}
		public override void AddToBatch(IExpectation expectation)
		{
			totalExpectedRowsAffected += expectation.ExpectedRowCount;
			log.Debug("Adding to batch:");
			IDbCommand batchUpdate = CurrentCommand;
			string commandLoggedText = GetCommandLogString(batchUpdate);
			currentBatchCommandsLog.Append("Batch command: ").
				AppendLine(commandLoggedText);
			currentBatch.Append((System.Data.SqlClient.SqlCommand) batchUpdate);
			if (currentBatch.CountOfCommands >= batchSize)
			{
				DoExecuteBatch(batchUpdate);
			}
		}
		public override void AddToBatch(IExpectation expectation)
		{
			bool firstOnBatch = true;
			totalExpectedRowsAffected += expectation.ExpectedRowCount;
			log.Info("Adding to batch");
			LogCommand(CurrentCommand);

			if (currentBatch == null)
			{
				// use first command as the batching command
				currentBatch = CurrentCommand;
				parameterValueListHashTable = new Dictionary<string, List<object>>();
				//oracle does not allow array containing all null values
				// so this Dictionary is keeping track if all values are null or not
				parameterIsAllNullsHashTable = new Dictionary<string, bool>();
			}
			else
			{
				firstOnBatch = false;
			}

			List<object> parameterValueList;
			foreach (IDataParameter currentParameter in CurrentCommand.Parameters)
			{                
				if (firstOnBatch)
				{
					parameterValueList = new List<object>();
					parameterValueListHashTable.Add(currentParameter.ParameterName, parameterValueList);
					parameterIsAllNullsHashTable.Add(currentParameter.ParameterName, true);
				}
				else
				{
					parameterValueList = parameterValueListHashTable[currentParameter.ParameterName];
				}

				if (currentParameter.Value != DBNull.Value)
				{
					parameterIsAllNullsHashTable[currentParameter.ParameterName] = false;
				}
				parameterValueList.Add(currentParameter.Value);
			} 
			
			countOfCommands++;

			if (countOfCommands >= batchSize)
			{
				ExecuteBatchWithTiming(currentBatch);
			}
		}
        public override void AddToBatch(IExpectation expectation)
        {
            this.totalExpectedRowsAffected += expectation.ExpectedRowCount;
            IDbCommand batchUpdate = CurrentCommand;
            Driver.AdjustCommand(batchUpdate);
            string lineWithParameters = null;
            var sqlStatementLogger = Factory.Settings.SqlStatementLogger;
            if (sqlStatementLogger.IsDebugEnabled || Log.IsDebugEnabled)
            {
                lineWithParameters = sqlStatementLogger.GetCommandLineWithParameters(batchUpdate);
                var formatStyle = sqlStatementLogger.DetermineActualStyle(FormatStyle.Basic);
                lineWithParameters = formatStyle.Formatter.Format(lineWithParameters);
                this.currentBatchCommandsLog.Append("command ")
                    .Append(this.currentBatch.CountOfCommands)
                    .Append(":")
                    .AppendLine(lineWithParameters);
            }
            if (Log.IsDebugEnabled)
            {
                Log.Debug("Adding to batch:" + lineWithParameters);
            }

            if (batchUpdate is ProfiledSqlCommand)
            {
                var sqlCommand = ((ProfiledSqlCommand)batchUpdate).SqlCommand;
                this.currentBatch.Append(sqlCommand);
                if (this.profiler != null)
                {
                    this.profiler.ExecuteStart(sqlCommand, ExecuteType.NonQuery);
                }
            }
            else
            {
                this.currentBatch.Append((System.Data.SqlClient.SqlCommand)batchUpdate);
            }

            if (this.currentBatch.CountOfCommands >= this.batchSize)
            {
                this.ExecuteBatchWithTiming(batchUpdate);
            }
        }
Example #49
0
 /// <summary>
 /// Logs the expectation as is was recorded
 /// </summary>
 /// <param name="invocation">The invocation.</param>
 /// <param name="expectation">The expectation.</param>
 public void LogRecordedExpectation(IInvocation invocation, IExpectation expectation)
 {
 }
		protected bool Check(int rows, object id, int tableNumber, IExpectation expectation, IDbCommand statement)
		{
			try
			{
				expectation.VerifyOutcomeNonBatched(rows, statement);
			}
			catch (StaleStateException)
			{
				if (!IsNullableTable(tableNumber))
				{
					if (Factory.Statistics.IsStatisticsEnabled)
						Factory.StatisticsImplementor.OptimisticFailure(EntityName);

					throw new StaleObjectStateException(EntityName, id);
				}
			}
			catch (TooManyRowsAffectedException ex)
			{
				throw new HibernateException("Duplicate identifier in table for: " + MessageHelper.InfoString(this, id, Factory), ex);
			}
			catch (Exception)
			{
				return false;
			}
			return true;
		}
 protected override void DoRecord(object proxy, MethodInfo method, IExpectation expectation)
 {
     DoRecordCalled = true;
 }
 protected override void DoRemoveExpectation(IExpectation expectation)
 {
     DoRemoveExpectationCalled = true;
 }
		public override void AddToBatch(IExpectation expectation)
		{
			bool firstOnBatch = true;
			totalExpectedRowsAffected += expectation.ExpectedRowCount;
            string lineWithParameters = null;
            var sqlStatementLogger = Factory.Settings.SqlStatementLogger;
            if (sqlStatementLogger.IsDebugEnabled || log.IsDebugEnabled)
            {
                lineWithParameters = sqlStatementLogger.GetCommandLineWithParameters(CurrentCommand);
                var formatStyle = sqlStatementLogger.DetermineActualStyle(FormatStyle.Basic);
                lineWithParameters = formatStyle.Formatter.Format(lineWithParameters);
                currentBatchCommandsLog.Append("command ")
                    .Append(countOfCommands)
                    .Append(":")
                    .AppendLine(lineWithParameters);
            }
            if (log.IsDebugEnabled)
            {
                log.Debug("Adding to batch:" + lineWithParameters);
            }

			if (currentBatch == null)
			{
				// use first command as the batching command
				currentBatch = CurrentCommand;
				parameterValueListHashTable = new Dictionary<string, List<object>>();
				//oracle does not allow array containing all null values
				// so this Dictionary is keeping track if all values are null or not
				parameterIsAllNullsHashTable = new Dictionary<string, bool>();
			}
			else
			{
				firstOnBatch = false;
			}

			List<object> parameterValueList;
			foreach (IDataParameter currentParameter in CurrentCommand.Parameters)
			{                
				if (firstOnBatch)
				{
					parameterValueList = new List<object>();
					parameterValueListHashTable.Add(currentParameter.ParameterName, parameterValueList);
					parameterIsAllNullsHashTable.Add(currentParameter.ParameterName, true);
				}
				else
				{
					parameterValueList = parameterValueListHashTable[currentParameter.ParameterName];
				}

				if (currentParameter.Value != DBNull.Value)
				{
					parameterIsAllNullsHashTable[currentParameter.ParameterName] = false;
				}
				parameterValueList.Add(currentParameter.Value);
			} 
			
			countOfCommands++;

			if (countOfCommands >= batchSize)
			{
				ExecuteBatchWithTiming(currentBatch);
			}
		}
Example #54
0
		/// <summary>
		/// Adds the expected row count into the batch.
		/// </summary>
		/// <param name="expectation">The number of rows expected to be affected by the query.</param>
		/// <remarks>
		/// If Batching is not supported, then this is when the Command should be executed.  If Batching
		/// is supported then it should hold of on executing the batch until explicitly told to.
		/// </remarks>
		public abstract void AddToBatch(IExpectation expectation);
 protected override void DoReplaceExpectation(object proxy, MethodInfo method, IExpectation oldExpectation, IExpectation newExpectation)
 {
     DoReplaceExpectationCalled = true;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="CallbackExpectation"/> class. 
 /// Creates a new <see cref="CallbackExpectation"/> instance.
 /// </summary>
 /// <param name="expectation">
 /// Expectation.
 /// </param>
 /// <param name="callback">
 /// Callback.
 /// </param>
 public CallbackExpectation(IExpectation expectation, Delegate callback)
     : base(expectation)
 {
     this.callback = callback;
     ValidateCallback();
 }
Example #57
0
 /// <summary>
 /// Logs the expectation as it was recorded
 /// </summary>
 /// <param name="invocation">The invocation.</param>
 /// <param name="expectation">The expectation.</param>
 public void LogReplayedExpectation(IInvocation invocation, IExpectation expectation)
 {
 }
		protected object PerformInsert(object ownerId, IPersistentCollection collection, IExpectation expectation,
		                               object entry, int index, bool useBatch, bool callable, ISessionImplementor session)
		{
			object entryId = null;
			int offset = 0;
			IDbCommand st = useBatch
			                	? session.Batcher.PrepareBatchCommand(SqlInsertRowString.CommandType, SqlInsertRowString.Text,
			                	                                      SqlInsertRowString.ParameterTypes)
			                	: session.Batcher.PrepareCommand(SqlInsertRowString.CommandType, SqlInsertRowString.Text,
			                	                                 SqlInsertRowString.ParameterTypes);
			try
			{
				//offset += expectation.Prepare(st, factory.ConnectionProvider.Driver);
				offset = WriteKey(st, ownerId, offset, session);
				if (hasIdentifier)
				{
					entryId = collection.GetIdentifier(entry, index);
					offset = WriteIdentifier(st, entryId, offset, session);
				}
				if (hasIndex)
				{
					offset = WriteIndex(st, collection.GetIndex(entry, index, this), offset, session);
				}
				WriteElement(st, collection.GetElement(entry), offset, session);
				if (useBatch)
				{
					session.Batcher.AddToBatch(expectation);
				}
				else
				{
					expectation.VerifyOutcomeNonBatched(session.Batcher.ExecuteNonQuery(st), st);
				}
			}
			catch (Exception e)
			{
				if (useBatch)
				{
					session.Batcher.AbortBatch(e);
				}
				throw;
			}
			finally
			{
				if (!useBatch)
				{
					session.Batcher.CloseCommand(st, null);
				}
			}
			return entryId;
		}
 /// <summary>
 /// Logs the expectation as it was recorded
 /// </summary>
 /// <param name="invocation">
 /// The invocation.
 /// </param>
 /// <param name="expectation">
 /// The expectation.
 /// </param>
 public void LogReplayedExpectation(IInvocation invocation, IExpectation expectation)
 {
     string methodCall = MethodCallUtil.StringPresentation(invocation, invocation.Method, invocation.Arguments);
     WriteLine("Replayed expectation: {0}", methodCall);
     WriteCurrentMethod();
 }
 public ExpectationVerificationInformation(CallRecordCollection allCallRecords, IExpectation expected)
 {
     this.AllCallRecords = allCallRecords;
       this.Expected = expected;
 }