예제 #1
0
        public void GetResponseStatus_Translate_Locked_Status(OperationCode operationCode, ResponseStatus status, ResponseStatus translatedStatus)
        {
            var operation = new FakeOperation(operationCode, status);
            var actual    = operation.GetResponseStatus();

            Assert.AreEqual(translatedStatus, actual);
        }
예제 #2
0
        public void Getconfig_Uses_Paramater_Transcoder()
        {
            var contentTranscoder = new Mock <ITypeTranscoder>();
            var operation         = new FakeOperation(contentTranscoder.Object);

            var config           = new BucketConfig();
            var configTranscoder = new Mock <ITypeTranscoder>();

            configTranscoder
            .Setup(transcoder => transcoder.Decode <BucketConfig>(It.IsAny <byte[]>(), It.IsAny <int>(),
                                                                  It.IsAny <int>(), It.IsAny <Flags>(), It.IsAny <OperationCode>()))
            .Returns(config);

            var result = operation.GetConfig(configTranscoder.Object);

            Assert.AreSame(config, result);

            // make sure the transcoder for decoding document content is not used
            configTranscoder.Verify(
                t => t.Decode <BucketConfig>(It.IsAny <byte[]>(), It.IsAny <int>(), It.IsAny <int>(), It.IsAny <Flags>(),
                                             It.IsAny <OperationCode>()), Times.Once);
            contentTranscoder.Verify(
                t => t.Decode <BucketConfig>(It.IsAny <byte[]>(), It.IsAny <int>(), It.IsAny <int>(), It.IsAny <Flags>(),
                                             It.IsAny <OperationCode>()), Times.Never);
        }
예제 #3
0
        public async Task When_Status_Indicates_Failure_ErrorCode_Is_Populated()
        {
            var errorMap = JsonConvert.DeserializeObject <ErrorMap>(ResourceHelper.ReadResource("kv-error-map.json"));

            var node = new ClusterNode(new ClusterContext(new CancellationTokenSource(),
                                                          new ClusterOptions()))
            {
                ErrorMap = errorMap
            };

            var mockConnection = new Mock <IConnection>();

            mockConnection.Setup(x => x.IsDead).Returns(false);
            node.Connection = mockConnection.Object;

            var insert = new FakeOperation(OpCode.Add, ResponseStatus.KeyExists);

            try
            {
                await node.ExecuteOp(insert, CancellationToken.None, TimeSpan.FromMinutes(5));
            }
            catch (KeyExistsException e)
            {
                Assert.NotNull((e.InnerException as KeyValueException)?.ErrorCode);
            }
        }
예제 #4
0
        public void UpdateDocument()
        {
            const string sql       = @"-- uspPrintError prints error information about the error that caused 
-- execution to jump to the CATCH block of a TRY...CATCH construct. 
-- Should be executed from within the scope of a CATCH block otherwise 
-- it will return without printing any error information.
CREATE PROCEDURE [dbo].[uspPrintError] 
AS
BEGIN
    SET NOCOUNT ON;

    -- Print error information. 
    PRINT 'Error ' + CONVERT(varchar(50), ERROR_NUMBER()) +
          ', Severity ' + CONVERT(varchar(5), ERROR_SEVERITY()) +
          ', State ' + CONVERT(varchar(5), ERROR_STATE()) + 
          ', Procedure ' + ISNULL(ERROR_PROCEDURE(), '-') + 
          ', Line ' + CONVERT(varchar(5), ERROR_LINE());
    PRINT ERROR_MESSAGE();
END;
GO
";
            const string yesterday = "20130429";
            var          testData  = new FakeOperation(
                new Row {
                { "action", "Update" }, { "count", "0000000001" }, { "created", "20060426" }, { "database", "AdventureWorks" }, { "dropped", "False" }, { "id", "X1785396043" }, { "lastused", yesterday }, { "modified", "20060426" }, { "name", "uspPrintError" }, { "schema", "dbo" }, { "server", "localhost" }, { "sqlscript", sql }, { "type", "Stored Procedure" }, { "use", "0000000000" }
            }
                );
            var luceneLoad = new LuceneLoad(@"c:\Sqloogle\SearchIndex");
            var results    = TestOperation(testData, luceneLoad);
        }
        public async Task Should_execute_operations_with_same_partition_key_together()
        {
            var fakeContainer    = new FakeContainer();
            var fakeCosmosClient = new FakeCosmosClient(fakeContainer);
            var containerHolderHolderResolver = new ContainerHolderResolver(new FakeProvider(fakeCosmosClient),
                                                                            new ContainerInformation("fakeContainer", new PartitionKeyPath("/deep/down")), "fakeDatabase");

            var storageSession = new StorageSession(containerHolderHolderResolver, new ContextBag(), true);
            var firstOperation = new FakeOperation
            {
                PartitionKey = new PartitionKey("PartitionKey1")
            };

            storageSession.AddOperation(firstOperation);
            var secondOperation = new FakeOperation
            {
                PartitionKey = new PartitionKey("PartitionKey1")
            };

            storageSession.AddOperation(secondOperation);

            await((ICompletableSynchronizedStorageSession)storageSession).CompleteAsync();

            Assert.That(firstOperation.WasApplied, Is.True);
            Assert.That(secondOperation.WasApplied, Is.True);
            Assert.That(firstOperation.AppliedBatch, Is.EqualTo(secondOperation.AppliedBatch), "Operations with the same partition key must be in the same batch");
        }
        public void Behaviors_are_applied_sorted_by_precedence_with_the_higher_precedence_behaviors_on_the_outside_across_factories(WorkflowConfiguration configuration, FakeOperation operation)
        {
            var factory1 = new FakeOperationBehaviorFactory();
            factory1.OperationBehaviors.Add(new FakeOperationBehavior { SetPrecedence = BehaviorPrecedence.StateRecovery });
            factory1.OperationBehaviors.Add(new FakeOperationBehavior { SetPrecedence = BehaviorPrecedence.Logging });
            factory1.OperationBehaviors.Add(new FakeOperationBehavior { SetPrecedence = BehaviorPrecedence.WorkCompensation });
            var factory2 = new FakeOperationBehaviorFactory();
            factory2.OperationBehaviors.Add(new FakeOperationBehavior { SetPrecedence = BehaviorPrecedence.PreRecovery });
            factory2.OperationBehaviors.Add(new FakeOperationBehavior { SetPrecedence = BehaviorPrecedence.Containment });
            configuration.WithBehaviorFactory(factory1).WithBehaviorFactory(factory2);

            var result = OperationResolverHelper.ApplyBehaviors(operation, configuration);

            Assert.IsType<FakeOperationBehavior>(result);
            var behavior1 = (OperationBehavior)result;
            Assert.Equal(BehaviorPrecedence.Logging, behavior1.Precedence);
            Assert.IsType<FakeOperationBehavior>(behavior1.InnerOperation);
            var behavior2 = (OperationBehavior)behavior1.InnerOperation;
            Assert.Equal(BehaviorPrecedence.Containment, behavior2.Precedence);
            Assert.IsType<FakeOperationBehavior>(behavior2.InnerOperation);
            var behavior3 = (OperationBehavior)behavior2.InnerOperation;
            Assert.Equal(BehaviorPrecedence.WorkCompensation, behavior3.Precedence);
            Assert.IsType<FakeOperationBehavior>(behavior3.InnerOperation);
            var behavior4 = (OperationBehavior)behavior3.InnerOperation;
            Assert.Equal(BehaviorPrecedence.StateRecovery, behavior4.Precedence);
            Assert.IsType<FakeOperationBehavior>(behavior4.InnerOperation);
            var behavior5 = (OperationBehavior)behavior4.InnerOperation;
            Assert.Equal(BehaviorPrecedence.PreRecovery, behavior5.Precedence);
            Assert.IsType<FakeOperation>(behavior5.InnerOperation);
        }
예제 #7
0
        public async Task When_Status_Indicates_Failure_ErrorCode_Is_Populated()
        {
            var errorMap = JsonConvert.DeserializeObject <ErrorMap>(ResourceHelper.ReadResource("kv-error-map.json"));

            var node = new ClusterNode(new ClusterContext(new CancellationTokenSource(),
                                                          new ClusterOptions()), new Mock <IConnectionFactory>().Object,
                                       new Mock <ILogger <ClusterNode> >().Object,
                                       new Mock <ITypeTranscoder>().Object,
                                       new Mock <ICircuitBreaker>().Object,
                                       new Mock <ISaslMechanismFactory>().Object)
            {
                ErrorMap = errorMap
            };

            var mockConnection = new Mock <IConnection>();

            mockConnection.Setup(x => x.IsDead).Returns(false);
            node.Connection = mockConnection.Object;

            var insert = new FakeOperation(OpCode.Add, ResponseStatus.KeyExists);

            try
            {
                await node.ExecuteOp(insert, CancellationToken.None, TimeSpan.FromMinutes(5));
            }
            catch (DocumentExistsException)
            {
                //need to resolve from context
                //Assert.NotNull((e.InnerException as DocumentExistsException)?.ErrorCode);
            }
        }
        public void Logged_exceptions_are_rethrown(IWorkflowLogger logger, Exception error)
        {
            var innerOperation = new FakeOperation { ThrowOnExecute = error };
            var sut = new OperationErrorLoggingBehavior(logger).AttachTo(innerOperation);

            Assert.Throws<Exception>(() => sut.Execute());
        }
예제 #9
0
        public void UpdateDocument()
        {
            const string sql = @"-- uspPrintError prints error information about the error that caused
            -- execution to jump to the CATCH block of a TRY...CATCH construct.
            -- Should be executed from within the scope of a CATCH block otherwise
            -- it will return without printing any error information.
            CREATE PROCEDURE [dbo].[uspPrintError]
            AS
            BEGIN
            SET NOCOUNT ON;

            -- Print error information.
            PRINT 'Error ' + CONVERT(varchar(50), ERROR_NUMBER()) +
              ', Severity ' + CONVERT(varchar(5), ERROR_SEVERITY()) +
              ', State ' + CONVERT(varchar(5), ERROR_STATE()) +
              ', Procedure ' + ISNULL(ERROR_PROCEDURE(), '-') +
              ', Line ' + CONVERT(varchar(5), ERROR_LINE());
            PRINT ERROR_MESSAGE();
            END;
            GO
            ";
            const string yesterday = "20130429";
            var testData = new FakeOperation(
               new Row { { "action", "Update" }, { "count", "0000000001" }, { "created", "20060426" }, { "database", "AdventureWorks" }, { "dropped", "False" }, { "id", "X1785396043" }, { "lastused", yesterday }, { "modified", "20060426" }, { "name", "uspPrintError" }, { "schema", "dbo" }, { "server", "localhost" }, { "sqlscript", sql }, { "type", "Stored Procedure" }, { "use", "0000000000" } }
            );
            var luceneLoad = new LuceneLoad(@"c:\Sqloogle\SearchIndex");
            var results = TestOperation(testData, luceneLoad);
        }
예제 #10
0
        public async Task SendAsync_SingleOpCancelledBeforeDequeued_ThrowsCancelledException()
        {
            // Arrange

            var connection        = new Mock <IConnection>();
            var connectionFactory = new Mock <IConnectionFactory>();

            connection.Setup(m => m.IsDead).Returns(false);
            connectionFactory
            .Setup(m => m.CreateAndConnectAsync(_ipEndPoint, It.IsAny <CancellationToken>()))
            .ReturnsAsync(() => connection.Object);

            var pool = CreatePool(connectionFactory: connectionFactory.Object);

            pool.MinimumSize = 1;
            pool.MaximumSize = 1;

            await pool.InitializeAsync();

            var operation = new FakeOperation();

            // Act

            var sendTask = pool.SendAsync(operation, new CancellationTokenSource(50).Token);
            await Task.WhenAny(Task.Delay(3000), operation.Completed);

            // Assert

            Assert.True(operation.Completed.IsCompleted);
            Assert.True(operation.Completed.IsCanceled);
        }
        public async Task Should_not_execute_release_operations_when_operations_successful()
        {
            var fakeContainer    = new FakeContainer();
            var fakeCosmosClient = new FakeCosmosClient(fakeContainer);
            var containerHolderHolderResolver = new ContainerHolderResolver(new FakeProvider(fakeCosmosClient),
                                                                            new ContainerInformation("fakeContainer", new PartitionKeyPath("/deep/down")), "fakeDatabase");

            var storageSession = new StorageSession(containerHolderHolderResolver, new ContextBag(), true);
            var operation      = new FakeOperation
            {
                PartitionKey = new PartitionKey("PartitionKey1")
            };

            storageSession.AddOperation(operation);
            var releaseOperation = new ReleaseLockOperation
            {
                PartitionKey = new PartitionKey("PartitionKey1")
            };

            storageSession.AddOperation(releaseOperation);

            await((ICompletableSynchronizedStorageSession)storageSession).CompleteAsync();
            storageSession.Dispose();

            Assert.That(releaseOperation.WasApplied, Is.False);
            Assert.That(releaseOperation.WasDisposed, Is.True);
        }
 public void When_()
 {
     var op = new FakeOperation(new ErrorCode {
         Retry = new RetrySpec {
             Strategy = RetryStrategy.None
         }
     });
 }
        public void Exceptions_during_the_execution_of_the_decorated_operation_are_not_propagated()
        {
            var operation = new FakeOperation { ThrowOnExecute = new Exception() };
            var sut = new ContinueOnFailureBehavior();
            sut.AttachTo(operation);

            sut.Execute();
        }
예제 #14
0
        public void A_behaviorless_operation_is_its_own_innermost_operation()
        {
            var sut = new FakeOperation();

            var result = sut.GetInnermostOperation();

            Assert.Equal(sut, result);
        }
예제 #15
0
        public void Failing_operations_are_retried_aspoecific_number_of_times()
        {
            var operation = new FakeOperation { ThrowOnExecute = new Exception(), ErrorCount = 2 };
            var sut = new RetryBehavior(1, TimeSpan.Zero);
            sut.AttachTo(operation);

            Assert.Throws<Exception>(() => sut.Execute());
        }
예제 #16
0
        public void Failing_operations_are_retried()
        {
            var operation = new FakeOperation { ThrowOnExecute = new Exception(), ErrorCount = 1 };
            var sut = new RetryBehavior(1, TimeSpan.Zero);
            sut.AttachTo(operation);

            sut.Execute();
        }
예제 #17
0
        public void Errors_from_the_execution_do_not_bubble_out_when_asserting_the_execution_order()
        {
            var operation = new FakeOperation {
                ThrowOnExecute = new Exception()
            };

            Assert.Throws <AssertionException>(() => operation.ExecutesChildOperations(typeof(Operation1)));
        }
예제 #18
0
        public void You_can_verify_that_executing_an_operation_has_executed_a_specific_sequence_of_child_operations_even_though_an_operation_fails()
        {
            var operation = new FakeOperation(new FakeOperation {
                ThrowOnExecute = new Exception()
            });

            operation.ExecutesChildOperations(typeof(FakeOperation));
        }
예제 #19
0
        public void Executing_an_operation_calls_the_OnExecute_method()
        {
            var sut = new FakeOperation();

            sut.Execute();

            Assert.True(sut.HasExecuted);
        }
        public void Errors_compensated_for_are_rethrown()
        {
            var operation = new FakeOperation { ThrowOnExecute = new Exception() };
            var sut = new CompensatingOperationBehavior(new FakeOperation());
            sut.AttachTo(operation);

            Assert.Throws<Exception>(() => sut.Execute());
        }
예제 #21
0
        public async Task When_Status_Indicates_Failure_Context_Is_Populated()
        {
            var errorMap = new ErrorMap(JsonConvert.DeserializeObject <ErrorMapDto>(ResourceHelper.ReadResource("kv-error-map.json")));

            var mockConnection = new Mock <IConnection>();

            var mockConnectionPool = new Mock <IConnectionPool>();

            mockConnectionPool
            .Setup(m => m.SendAsync(It.IsAny <IOperation>(), It.IsAny <CancellationToken>()))
            .Returns((IOperation operation, CancellationToken _) => operation.SendAsync(mockConnection.Object));

            var mockConnectionPoolFactory = new Mock <IConnectionPoolFactory>();

            mockConnectionPoolFactory
            .Setup(m => m.Create(It.IsAny <ClusterNode>()))
            .Returns(mockConnectionPool.Object);

            var node = new ClusterNode(new ClusterContext(new CancellationTokenSource(),
                                                          new ClusterOptions()), mockConnectionPoolFactory.Object,
                                       new Mock <ILogger <ClusterNode> >().Object,
                                       new DefaultObjectPool <OperationBuilder>(new OperationBuilderPoolPolicy()),
                                       new Mock <ICircuitBreaker>().Object,
                                       new Mock <ISaslMechanismFactory>().Object,
                                       new Mock <IRedactor>().Object,
                                       new IPEndPoint(IPAddress.Parse("127.0.0.1"), 11210),
                                       BucketType.Couchbase,
                                       new NodeAdapter
            {
                Hostname = "127.0.0.1"
            },
                                       NullRequestTracer.Instance)
            {
                ErrorMap = errorMap
            };

            var insert = new FakeOperation(OpCode.Add, ResponseStatus.KeyExists)
            {
                SName = "TheScope",
                CName = "TheCollection"
            };

            try
            {
                await node.ExecuteOp(insert, CancellationToken.None).ConfigureAwait(false);
            }
            catch (DocumentExistsException e)
            {
                var context = e.Context as KeyValueErrorContext;
                Assert.NotNull(e.Context);
                var message =
                    "KV Error: {Name=\"KEY_EEXISTS\", Description=\"key already exists, or CAS mismatch\", Attributes=\"item-only\"}";
                Assert.Equal(message, e.Context.Message);
                Assert.Equal("TheScope", context.ScopeName);
                Assert.Equal("TheCollection", context.CollectionName);
                Assert.NotEqual("0", context.ClientContextId);
            }
        }
예제 #22
0
        public async Task Test_ClusterMap_Version2(ResponseStatus status, string errorCode)
        {
            var errorMap = new ErrorMap(JsonSerializer.Deserialize(ResourceHelper.ReadResource("kv-error-map-v2.json"),
                                                                   InternalSerializationContext.Default.ErrorMapDto) !);

            var mockConnection = new Mock <IConnection>();

            var mockConnectionPool = new Mock <IConnectionPool>();

            mockConnectionPool
            .Setup(m => m.SendAsync(It.IsAny <IOperation>(), It.IsAny <CancellationToken>()))
            .Returns((IOperation operation, CancellationToken _) => operation.SendAsync(mockConnection.Object));

            var mockConnectionPoolFactory = new Mock <IConnectionPoolFactory>();

            mockConnectionPoolFactory
            .Setup(m => m.Create(It.IsAny <ClusterNode>()))
            .Returns(mockConnectionPool.Object);

            var node = new ClusterNode(new ClusterContext(new CancellationTokenSource(),
                                                          new ClusterOptions()), mockConnectionPoolFactory.Object,
                                       new Mock <ILogger <ClusterNode> >().Object,
                                       new DefaultObjectPool <OperationBuilder>(new OperationBuilderPoolPolicy()),
                                       new Mock <ICircuitBreaker>().Object,
                                       new Mock <ISaslMechanismFactory>().Object,
                                       new TypedRedactor(RedactionLevel.None),
                                       new HostEndpointWithPort("127.0.0.1", 11210),
                                       new NodeAdapter
            {
                Hostname = "127.0.0.1"
            },
                                       NoopRequestTracer.Instance)
            {
                ErrorMap = errorMap
            };

            var insert = new FakeOperation(OpCode.Add, status)
            {
                SName = "TheScope",
                CName = "TheCollection"
            };

            try
            {
                await node.ExecuteOp(insert).ConfigureAwait(false);
            }
            catch (CouchbaseException e)
            {
                var context = e.Context as KeyValueErrorContext;
                Assert.NotNull(e.Context);

                Assert.Contains(errorCode, e.Context.Message);
                Assert.Equal("TheScope", context.ScopeName);
                Assert.Equal("TheCollection", context.CollectionName);
                Assert.NotEqual("0", context.ClientContextId);
            }
        }
        public void The_inner_operation_is_not_skipped_if_it_is_not_a_conditional_operation()
        {
            var operation = new FakeOperation();
            var sut = new ConditionalExecutionBehavior().AttachTo(operation);

            sut.Execute();

            Assert.True(operation.HasExecuted);
        }
예제 #24
0
        public void Logged_exceptions_are_rethrown(IWorkflowLogger logger, Exception error)
        {
            var innerOperation = new FakeOperation {
                ThrowOnExecute = error
            };
            var sut = new OperationErrorLoggingBehavior(logger).AttachTo(innerOperation);

            Assert.Throws <Exception>(() => sut.Execute());
        }
        public void The_inner_operation_is_not_skipped_if_it_is_not_a_conditional_operation()
        {
            var operation = new FakeOperation();
            var sut       = new ConditionalExecutionBehavior().AttachTo(operation);

            sut.Execute();

            Assert.True(operation.HasExecuted);
        }
        public void The_decorated_operation_provides_the_child_operations(IOperation op1, IOperation op2)
        {
            var operation = new FakeOperation(op1, op2);
            var sut       = new TestBehavior().AttachTo(operation);

            var result = sut.GetChildOperations();

            Assert.Equal(operation.GetChildOperations(), result);
        }
        public void The_decorator_forwards_the_execution_to_the_decorated_operation()
        {
            var operation = new FakeOperation();
            var sut       = new TestBehavior().AttachTo(operation);

            sut.Execute();

            Assert.True(operation.HasExecuted);
        }
예제 #28
0
        public void Executed_child_operations_are_added_to_the_execution_info_list(IOperation childOperation)
        {
            var sut = new FakeOperation(childOperation);

            sut.Execute();

            Assert.Equal(1, sut.ExecutedChildOperations.Count());
            Assert.Equal(childOperation, sut.ExecutedChildOperations.ElementAt(0).Operation);
        }
예제 #29
0
        public async Task SendAsync_QueueFull_After_CleaningUpDeadConnections_SetsExceptionOnOperation()
        {
            // Arrange
            int count             = 0;
            var connection        = new Mock <IConnection>();
            var connectionFactory = new Mock <IConnectionFactory>();

            connectionFactory
            .Setup(m => m.CreateAndConnectAsync(_ipEndPoint, It.IsAny <CancellationToken>()))
            .ReturnsAsync(() => connection.Object);

            var pool = CreatePool(connectionFactory: connectionFactory.Object);

            pool.MinimumSize = 1;
            pool.MaximumSize = 1;
            connection.Setup(m => m.IsDead).Returns(() => {
                count++;
                // The first time IsDead is checked is during pool.InitializeAsync
                // The second time is done after dequeueing the first op
                if (count == 2)
                {
                    // simulate queue filling up during cleanup
                    while (true)
                    {
                        try
                        {
                            pool.SendAsync(new FakeOperation()).GetAwaiter().GetResult();
                        }
                        catch (SendQueueFullException)
                        {
                            break;
                        }
                    }
                    return(true); // simulate dead connection
                }
                return(false);
            });
            await pool.InitializeAsync();

            var operation = new FakeOperation()
            {
                Delay = TimeSpan.FromSeconds(3), Cid = 1
            };

            // Act

            // queue the operation we expect to be requeued after cleanup
            await pool.SendAsync(operation);

            // wait for operation to fail but not forever
            await Task.WhenAny(operation.Completed, Task.Delay(3000));

            // Assert
            Assert.True(operation.Completed.IsCompleted);
            await Assert.ThrowsAsync <SendQueueFullException>(() => operation.Completed);
        }
        public void When_ErrorMap_Is_Not_Null_And_RetryStrategy_Is_Not_None_ErrorMapRequestsRetry_Is_True(RetryStrategy strategy)
        {
            var op = new FakeOperation(new ErrorCode {
                Retry = new RetrySpec {
                    Strategy = strategy
                }
            });

            Assert.True(op.ErrorMapRequestsRetry());
        }
        public void When_ErrorMap_Is_Not_Null_And_RetryStrategy_Is_None_ErrorMapRequestsRetry_Is_False()
        {
            var op = new FakeOperation(new ErrorCode {
                Retry = new RetrySpec {
                    Strategy = RetryStrategy.None
                }
            });

            Assert.False(op.ErrorMapRequestsRetry());
        }
        public void The_innermost_operation_is_logged_as_the_source(FakeWorkflowLogger logger, Exception error)
        {
            var innerOperation = new FakeOperation { ThrowOnExecute = error };
            var behavior = new FakeOperationBehavior().AttachTo(innerOperation);
            var sut = new OperationErrorLoggingBehavior(logger).AttachTo(behavior);

            ExecuteIgnoringErrors(sut.Execute);

            Assert.Equal(1, logger.OperationFailures[innerOperation].Count);
        }
        public void Start_and_finish_are_logged_in_case_of_failure(FakeWorkflowLogger logger)
        {
            var innerOperation = new FakeOperation { ThrowOnExecute = new Exception() };
            var sut = new OperationExecutionLoggingBehavior(logger).AttachTo(innerOperation);

            ExecuteIgnoringErrors(sut.Execute);

            Assert.Equal(1, logger.StartedOperations.Count);
            Assert.Equal(1, logger.FinishedOperations.Count);
        }
        public void Executing_an_operation_logs_the_duration(FakeWorkflowLogger logger)
        {
            Time.Stop();
            var innerOperation = new FakeOperation { ExecuteAction = () => Time.Wait(TimeSpan.FromMilliseconds(10)) };
            var sut = new OperationExecutionLoggingBehavior(logger).AttachTo(innerOperation);

            sut.Execute();

            Assert.Equal(TimeSpan.FromMilliseconds(10).TotalMilliseconds, logger.FinishedOperationDurations[0].TotalMilliseconds);
        }
예제 #35
0
        public void You_can_make_data_available_to_child_operations(object input)
        {
            var childInputOperation = new FakeInputOperation <object>();
            var sut = new FakeOperation(childInputOperation);

            sut.ExecuteAction = () => sut.PublicPipeInputToChildOperations(input);

            sut.Execute();

            Assert.Equal(input, childInputOperation.ProvidedInput);
        }
        public void Asserting_a_sequence_of_child_operation_executions_highlight_matches_after_errors()
        {
            var operation = new FakeOperation(new Operation1(), new FakeOperation(new Operation1()), new Operation1());
            AssertionException exception = null;

            try { operation.ExecutesChildOperations(typeof(Operation1), typeof(FakeOperation), typeof(Operation2), typeof(Operation1)); }
            catch (AssertionException e) { exception = e; }

            var formattedErrorMessage = string.Format("Operations{0}=========={0}Operation1 [match]{0}FakeOperation [match]{0}Operation1 [error: expected Operation2]{0}Operation1 [match]", NL);
            Assert.Equal(formattedErrorMessage, exception.Message);
        }
        public void When_an_error_occurs_in_the_operation_the_compensating_operation_is_immediately_executed()
        {
            var operation = new FakeOperation { ThrowOnExecute = new Exception() };
            var compensatingOperation = new FakeOperation();
            var sut = new CompensatingOperationBehavior(compensatingOperation);
            sut.AttachTo(operation);

            ExecuteIgnoringErrors(sut.Execute);

            Assert.True(compensatingOperation.HasExecuted);
        }
        public void When_no_error_occurs_in_the_operation_the_compensating_operation_is_not_executed()
        {
            var operation = new FakeOperation();
            var compensatingOperation = new FakeOperation();
            var sut = new CompensatingOperationBehavior(compensatingOperation);
            sut.AttachTo(operation);

            sut.Execute();

            Assert.False(compensatingOperation.HasExecuted);
        }
        public void Exceptions_thrown_during_the_execution_are_logged(FakeWorkflowLogger logger, Exception error)
        {
            var innerOperation = new FakeOperation { ThrowOnExecute = error };
            var sut = new OperationErrorLoggingBehavior(logger).AttachTo(innerOperation);

            ExecuteIgnoringErrors(sut.Execute);

            Assert.Equal(1, logger.OperationFailures.Count);
            Assert.Equal(1, logger.OperationFailures[innerOperation].Count);
            Assert.Equal(innerOperation.ThrowOnExecute, logger.OperationFailures[innerOperation][0]);
        }
예제 #40
0
        public void Exceptions_during_the_execution_of_the_decorated_operation_are_not_propagated()
        {
            var operation = new FakeOperation {
                ThrowOnExecute = new Exception()
            };
            var sut = new ContinueOnFailureBehavior();

            sut.AttachTo(operation);

            sut.Execute();
        }
예제 #41
0
        public void Failing_operations_are_retried_a_specific_number_of_times()
        {
            var operation = new FakeOperation {
                ThrowOnExecute = new Exception(), ErrorCount = 2
            };
            var sut = new RetryBehavior(1, TimeSpan.Zero);

            sut.AttachTo(operation);

            Assert.Throws <Exception>(() => sut.Execute());
        }
예제 #42
0
        public void You_cannot_retry_an_operation_where_a_non_idempotent_child_operation_has_executed()
        {
            var operation = new FakeOperation(new IdempotentOperation(), new FakeOperation {
                ThrowOnExecute = new Exception(), ErrorCount = 1
            });
            var sut = new RetryBehavior(1, TimeSpan.Zero);

            sut.AttachTo(operation);

            Assert.Throws <Exception>(() => sut.Execute());
        }
예제 #43
0
        public void Failing_operations_are_retried()
        {
            var operation = new FakeOperation {
                ThrowOnExecute = new Exception(), ErrorCount = 1
            };
            var sut = new RetryBehavior(1, TimeSpan.Zero);

            sut.AttachTo(operation);

            sut.Execute();
        }
예제 #44
0
        public void When_retry_exception_types_are_specified_errors_of_different_types_will_not_be_retried()
        {
            var operation = new FakeOperation {
                ThrowOnExecute = new NullReferenceException(), ErrorCount = 1
            };
            var sut = new RetryBehavior(1, TimeSpan.Zero, typeof(InsufficientMemoryException));

            sut.AttachTo(operation);

            Assert.Throws <NullReferenceException>(() => sut.Execute());
        }
예제 #45
0
        public void When_retry_exception_types_are_specified_errors_of_sub_types_will_be_retried()
        {
            var operation = new FakeOperation {
                ThrowOnExecute = new ArgumentNullException(), ErrorCount = 1
            };
            var sut = new RetryBehavior(1, TimeSpan.Zero, typeof(ArgumentException));

            sut.AttachTo(operation);

            sut.Execute();
        }
예제 #46
0
        public void Retries_are_delayed_the_specified_duration()
        {
            var operation = new FakeOperation { ThrowOnExecute = new Exception(), ErrorCount = 1 };
            var sut = new RetryBehavior(1, TimeSpan.FromSeconds(5));
            sut.AttachTo(operation);
            var before = Time.OffsetUtcNow;

            sut.Execute();

            var duration = Time.OffsetUtcNow - before;
            Assert.Equal(TimeSpan.FromSeconds(5), duration); 
        }
        public void Compensating_operations_have_input_values_supplied_from_the_original_operation(object input)
        {
            var operation = new FakeInputOperation<object> { ThrowOnExecute = new Exception() };
            var compensatingOperation = new FakeInputOperation<object>();
            var sut = new CompensatingOperationBehavior(compensatingOperation);
            operation.Input(input);
            var parentOperation = new FakeOperation(new FakeOutputOperation<object> { OutputValue = input }, sut.AttachTo(new FakeOperationBehavior().AttachTo(operation)));

            ExecuteIgnoringErrors(parentOperation.Execute);

            Assert.True(compensatingOperation.InputWasProvided);
            Assert.Equal(input, compensatingOperation.ProvidedInput);
        }
        public void SetUp()
        {
            var configuration = new ClientConfiguration();
            var clusterManager = new ClusterManager(configuration, (p) =>
            {
                var operation = new FakeOperation(new ManualByteConverter());
                operation.SetOperationResult(new FakeOperationResult(operation)
                {
                    Message = "nmv",
                    Cas = 231,
                    Status = ResponseStatus.VBucketBelongsToAnotherServer,
                    Success = false,
                    Value = string.Empty
                });
                return new FakeIOStrategy<FakeOperation>(operation);
            });
 
            _cluster = new CouchbaseCluster(configuration, clusterManager);
        }
        public void Applying_behaviors_returns_the_original_operation_when_no_behaviors_are_created(WorkflowConfiguration configuration, FakeOperation operation)
        {
            var result = OperationResolverHelper.ApplyBehaviors(operation, configuration);

            Assert.Equal(operation, result);
        }
예제 #50
0
        public void When_IOErrorThreshold_IsNot_Met_By_IOErrorInterval_NodeUnavailableException_Is_Thrown()
        {
            var json = File.ReadAllText(@"Data\\Configuration\\nodesext-cb-beta-4.json");
            var config = JsonConvert.DeserializeObject<BucketConfig>(json);
            var node = config.GetNodes().First();

            var endPoint = UriExtensions.GetEndPoint(_address);
            var configuration = new ClientConfiguration
            {
                IOErrorThreshold = 10,
                IOErrorCheckInterval = 100
            };
            var connectionPool = new FakeConnectionPool();
            var ioStrategy = new FakeIOStrategy(endPoint, connectionPool, false);
            var server = new Server(ioStrategy,
                node,
                configuration,
                config,
                new FakeTranscoder());

            Assert.IsFalse(server.IsDown);

            var stopWatch = new Stopwatch();
            stopWatch.Start();
            for (int i = 0; i < 11; i++)
            {
                server.CheckOnline(true);
                Console.WriteLine("{0}=>{1}", server.IsDown, server.IOErrorCount);
                Thread.Sleep(10);
            }
            // ReSharper disable once ThrowingSystemException
            Assert.Throws<NodeUnavailableException>(() =>
            {
                var operation = new FakeOperation(new DefaultTranscoder());
                server.Send(operation);
                throw operation.Exception;
            });
        }
        public void When_specifying_a_compensated_exception_type_other_types_of_exceptions_will_not_be_compensated()
        {
            var operation = new FakeOperation { ThrowOnExecute = new Exception() };
            var compensatingOperation = new FakeOperation();
            var sut = new CompensatingOperationBehavior(compensatingOperation, typeof(ArgumentException));
            sut.AttachTo(operation);

            ExecuteIgnoringErrors(sut.Execute);

            Assert.False(compensatingOperation.HasExecuted);
        }
        public void You_can_verify_that_executing_an_operation_has_executed_a_specific_sequence_of_child_operations_without_failures()
        {
            var operation = new FakeOperation(new Operation1(), new FakeOperation(new Operation2()));

            operation.ExecutesChildOperationsWithoutErrors(typeof(Operation1), typeof(FakeOperation), typeof(Operation2));
        }
예제 #53
0
        public void When_retry_exception_types_are_specified_errors_of_different_types_will_not_be_retried()
        {
            var operation = new FakeOperation { ThrowOnExecute = new NullReferenceException(), ErrorCount = 1 };
            var sut = new RetryBehavior(1, TimeSpan.Zero, typeof(InsufficientMemoryException));
            sut.AttachTo(operation);

            Assert.Throws<NullReferenceException>(() => sut.Execute());
        }
예제 #54
0
        public void You_can_retry_an_operation_where_an_indempotent_child_operation_has_executed()
        {
            var operation = new FakeOperation(new IndempotentOperation { ThrowOnExecute = new Exception(), ErrorCount = 1 });
            var sut = new RetryBehavior(1, TimeSpan.Zero);
            sut.AttachTo(operation);

            sut.Execute();
        }
        public void When_no_compensating_action_is_triggered_no_event_is_logged(FakeWorkflowLogger log)
        {
            var operation = new FakeOperation { ThrowOnExecute = new Exception() };
            var compensatingOperation = new FakeOperation();
            var sut = new CompensatingOperationBehavior(compensatingOperation, typeof(ArgumentException));
            sut.AttachTo(operation);
            sut.Initialize(new FakeWorkflowConfiguration { Logger = log });

            ExecuteIgnoringErrors(sut.Execute);

            Assert.Equal(0, log.AppliedBehaviors.Count);
        }
        public void Executing_a_compensating_operation_logs_an_event(FakeWorkflowLogger log)
        {
            var operation = new FakeOperation { ThrowOnExecute = new ArgumentException() };
            var compensatingOperation = new FakeOperation();
            var sut = new CompensatingOperationBehavior(compensatingOperation, typeof(Exception));
            sut.AttachTo(operation);
            sut.Initialize(new FakeWorkflowConfiguration { Logger = log });

            ExecuteIgnoringErrors(sut.Execute);

            Assert.Equal(1, log.AppliedBehaviors.Count);
            Assert.Equal("Executing compensating operation", log.AppliedBehaviors[0].Description);
        }
예제 #57
0
        public void When_retry_exception_types_are_specified_errors_of_sub_types_will_be_retried()
        {
            var operation = new FakeOperation { ThrowOnExecute = new ArgumentNullException(), ErrorCount = 1 };
            var sut = new RetryBehavior(1, TimeSpan.Zero, typeof(ArgumentException));
            sut.AttachTo(operation);

            sut.Execute();
        }
        public void When_specifying_a_compensated_exception_type_the_compensating_operation_will_be_executed_in_case_of_an_exception_inheriting_from_this_exception()
        {
            var operation = new FakeOperation { ThrowOnExecute = new ArgumentException() };
            var compensatingOperation = new FakeOperation();
            var sut = new CompensatingOperationBehavior(compensatingOperation, typeof(Exception));
            sut.AttachTo(operation);

            ExecuteIgnoringErrors(sut.Execute);

            Assert.True(compensatingOperation.HasExecuted);
        }
        public void Errors_from_the_execution_do_not_bubble_out_when_asserting_the_execution_order()
        {
            var operation = new FakeOperation{ ThrowOnExecute = new Exception() };

            Assert.Throws<AssertionException>(() => operation.ExecutesChildOperations(typeof (Operation1)));
        }
        public void You_can_verify_that_executing_an_operation_has_executed_a_specific_sequence_of_child_operations_even_though_an_operation_fails()
        {
            var operation = new FakeOperation(new FakeOperation { ThrowOnExecute = new Exception() });

            operation.ExecutesChildOperations(typeof(FakeOperation));
        }