public LoggingTests(IntegrationTestContext <Startup, AppDbContext> testContext)
        {
            _testContext = testContext;

            FakeLoggerFactory loggerFactory = null;

            testContext.ConfigureLogging(options =>
            {
                loggerFactory = new FakeLoggerFactory();

                options.ClearProviders();
                options.AddProvider(loggerFactory);
                options.SetMinimumLevel(LogLevel.Trace);
                options.AddFilter((category, level) => level == LogLevel.Trace &&
                                  (category == typeof(JsonApiReader).FullName || category == typeof(JsonApiWriter).FullName));
            });

            testContext.ConfigureServicesBeforeStartup(services =>
            {
                if (loggerFactory != null)
                {
                    services.AddSingleton(_ => loggerFactory);
                }
            });
        }
        public void RetryTest2()
        {
            FakeLoggerFactory loggerFac   = new FakeLoggerFactory();
            FakeDataOptions   defaultOpts = new FakeDataOptions()
            {
                ConnectionString = "Host=localhost;",
                MaxRetries       = 2,
            };

            defaultOpts.ShouldRetryList.Add(typeof(Npgsql.NpgsqlException));


            FakeDataCommand <int> command = new FakeDataCommand <int>("CommandForRetry", defaultOpts, loggerFac, (conn) => {
                throw new PostgresException(); // Emulating a Query error, for instance.
            });
            Exception exception = null;

            try
            {
                command.Run();
            }
            catch (Exception ex)
            {
                exception = ex;
            }

            Assert.Equal(command.ExecuteCount, 1); //Only one attempt, since no retry should be made to PostgresException
            Assert.True(exception != null);
            Assert.IsType <Npgsql.PostgresException>(exception);
        }
Beispiel #3
0
        public async Task CheckAllFiles()
        {
            var workspace = await TestHelpers.CreateSimpleWorkspace(new Dictionary <string, string>
            {
                { "a.cs", "class C1 { int n = true; }" },
                { "b.cs", "class C2 { int n = true; }" },
            });

            var fakeLoggerFactory = new FakeLoggerFactory();
            var messages          = new List <OmniSharp.Models.DiagnosticMessage>();
            var emitter           = new DiagnosticTestEmitter(messages);
            var forwarder         = new DiagnosticEventForwarder(emitter);
            var service           = new CSharpDiagnosticService(workspace, forwarder, fakeLoggerFactory);

            var controller = new DiagnosticsService(workspace, forwarder, service);
            var response   = await controller.Handle(new OmniSharp.Models.DiagnosticsRequest());

            await emitter.Emitted;

            Assert.Equal(1, messages.Count);
            var message = messages.First();

            Assert.Equal(2, message.Results.Count());

            var a = message.Results.First(x => x.FileName == "a.cs");

            Assert.Equal(1, a.QuickFixes.Count());
            Assert.Equal("a.cs", a.FileName);

            var b = message.Results.First(x => x.FileName == "b.cs");

            Assert.Equal(1, b.QuickFixes.Count());
            Assert.Equal("b.cs", b.FileName);
        }
Beispiel #4
0
        public void Lazy_loading_is_logged_only_when_actually_loading()
        {
            var messages      = new List <string>();
            var loggerFactory = new FakeLoggerFactory(messages);

            using (var context = new WarningAsErrorContext(loggerFactory))
            {
                context.Add(new WarningAsErrorEntity {
                    Nav = new IncludedEntity()
                });
                context.SaveChanges();
            }

            using (var context = new WarningAsErrorContext(loggerFactory))
            {
                var entity = context.WarningAsErrorEntities.OrderBy(e => e.Id).First();

                messages.Clear();
                Assert.NotNull(entity.Nav);

                Assert.Contains(
                    CoreStrings.LogNavigationLazyLoading.GenerateMessage("Nav", "WarningAsErrorEntity"),
                    messages);

                messages.Clear();
                Assert.NotNull(entity.Nav);
                Assert.DoesNotContain(
                    CoreStrings.LogNavigationLazyLoading.GenerateMessage("Nav", "WarningAsErrorEntity"),
                    messages);
            }
        }
        public void BatchInsertTest()
        {
            var dataOptions = new FakeDataOptions()
            {
                ConnectionString = "Host=localhost;"
            };
            var loggerFactory = new FakeLoggerFactory();

            FakeBatchCommand fakeCommand = new FakeBatchCommand(10, dataOptions, loggerFactory);

            //Add up to 30 entities
            //Execute should be execute 3 times.
            for (int i = 0; i < 30; i++)
            {
                fakeCommand.AddEntity(new Entity {
                    Id = i
                });
            }

            Assert.Equal(3, fakeCommand.ExecuteCount);

            fakeCommand.Run(); //In a real case, this would be called to dump remanescent data

            //Run for last execution (4 times)
            Assert.Equal(4, fakeCommand.ExecuteCount);
        }
Beispiel #6
0
        public async Task CodeCheckSpecifiedFileOnly()
        {
            var workspace = await TestHelpers.CreateSimpleWorkspace(new Dictionary <string, string>
            {
                { "a.cs", "class C { int n = true; }" }
            });

            var fakeLoggerFactory = new FakeLoggerFactory();
            var messages          = new List <OmniSharp.Models.DiagnosticMessage>();
            var emitter           = new DiagnosticTestEmitter(messages);
            var forwarder         = new DiagnosticEventForwarder(emitter);

            forwarder.IsEnabled = true;
            var service = new CSharpDiagnosticService(workspace, forwarder, fakeLoggerFactory);

            service.QueueDiagnostics("a.cs");

            await emitter.Emitted;

            Assert.Equal(1, messages.Count);
            var message = messages.First();

            Assert.Equal(1, message.Results.Count());
            var result = message.Results.First();

            Assert.Equal(1, result.QuickFixes.Count());
            Assert.Equal("a.cs", result.FileName);
        }
        public LoggingTests(ExampleIntegrationTestContext <TestableStartup <AuditDbContext>, AuditDbContext> testContext)
        {
            _testContext = testContext;

            testContext.UseController <AuditEntriesController>();

            FakeLoggerFactory loggerFactory = null;

            testContext.ConfigureLogging(options =>
            {
                loggerFactory = new FakeLoggerFactory();

                options.ClearProviders();
                options.AddProvider(loggerFactory);
                options.SetMinimumLevel(LogLevel.Trace);
                options.AddFilter((_, __) => true);
            });

            testContext.ConfigureServicesBeforeStartup(services =>
            {
                if (loggerFactory != null)
                {
                    services.AddSingleton(_ => loggerFactory);
                }
            });
        }
        public async Task LogsExceptionInPipelineStep()
        {
            using (var writer = new TestBulkWriter <PipelineTestsMyTestClass>())
            {
                var items = Enumerable
                            .Range(1, 1000)
                            .Select(i => new PipelineTestsMyTestClass {
                    Id = i, Name = "Bob"
                })
                            .ToAsyncEnumerable();

                var loggerFactory = new FakeLoggerFactory();
                var pipeline      = EtlPipeline
                                    .StartWith(items)
                                    .Project <PipelineTestsMyTestClass>(i => throw new Exception("This is my exception"))
                                    .LogWith(loggerFactory)
                                    .WriteTo(writer);

                var pipelineTask = pipeline.ExecuteAsync();
                await Assert.ThrowsAsync <Exception>(() => pipelineTask);

                var errorMessages = loggerFactory.LoggedMessages.Where(m => m.LogLevel == LogLevel.Error).ToList();
                Assert.Single(errorMessages);

                Assert.Contains("Error", errorMessages[0].Message);
                Assert.Equal("This is my exception", errorMessages[0].Exception.Message);
            }
        }
        public ExceptionHandlerTests(ExampleIntegrationTestContext <TestableStartup <ErrorDbContext>, ErrorDbContext> testContext)
        {
            _testContext = testContext;

            testContext.UseController <ThrowingArticlesController>();
            testContext.UseController <ConsumerArticlesController>();

            FakeLoggerFactory loggerFactory = null;

            testContext.ConfigureLogging(options =>
            {
                loggerFactory = new FakeLoggerFactory();

                options.ClearProviders();
                options.AddProvider(loggerFactory);
                options.SetMinimumLevel(LogLevel.Warning);
            });

            testContext.ConfigureServicesBeforeStartup(services =>
            {
                if (loggerFactory != null)
                {
                    services.AddSingleton(_ => loggerFactory);
                }
            });

            testContext.ConfigureServicesAfterStartup(services =>
            {
                services.AddResourceService <ConsumerArticleService>();
                services.AddScoped <IExceptionHandler, AlternateExceptionHandler>();
            });
        }
Beispiel #10
0
        public void Lazy_load_with_disposed_context_can_be_configured_to_log()
        {
            var messages      = new List <string>();
            var loggerFactory = new FakeLoggerFactory(messages);

            using (var context = new WarningAsErrorContext(
                       loggerFactory,
                       CoreEventId.LazyLoadOnDisposedContextWarning))
            {
                context.Add(new WarningAsErrorEntity {
                    Nav = new IncludedEntity()
                });
                context.SaveChanges();
            }

            WarningAsErrorEntity entity;

            using (var context = new WarningAsErrorContext(
                       loggerFactory,
                       CoreEventId.LazyLoadOnDisposedContextWarning))
            {
                entity = context.WarningAsErrorEntities.OrderBy(e => e.Id).First();
            }

            Assert.Null(entity.Nav);

            Assert.Contains(
                CoreStrings.LogLazyLoadOnDisposedContextWarning.GenerateMessage("Nav", "WarningAsErrorEntity"),
                messages);
        }
Beispiel #11
0
        public void Throws_by_default_for_lazy_load_with_disposed_context()
        {
            var messages      = new List <string>();
            var loggerFactory = new FakeLoggerFactory(messages);

            using (var context = new WarningAsErrorContext(loggerFactory))
            {
                context.Add(new WarningAsErrorEntity {
                    Nav = new IncludedEntity()
                });
                context.SaveChanges();
            }

            WarningAsErrorEntity entity;

            using (var context = new WarningAsErrorContext(loggerFactory))
            {
                entity = context.WarningAsErrorEntities.OrderBy(e => e.Id).First();
            }

            Assert.Equal(
                CoreStrings.WarningAsErrorTemplate(
                    CoreEventId.LazyLoadOnDisposedContextWarning.ToString(),
                    CoreStrings.LogLazyLoadOnDisposedContextWarning.GenerateMessage("Nav", "WarningAsErrorEntity")),
                Assert.Throws <InvalidOperationException>(
                    () => entity.Nav).Message);
        }
Beispiel #12
0
        public async Task LogsStartAndFinishOfPipelineSteps()
        {
            using (var writer = new TestBulkWriter <PipelineTestsOtherTestClass>())
            {
                var items = Enumerable.Range(1, 1000).Select(i => new PipelineTestsMyTestClass {
                    Id = i, Name = "Bob"
                });
                var loggerFactory = new FakeLoggerFactory();
                var pipeline      = EtlPipeline
                                    .StartWith(items)
                                    .LogWith(loggerFactory)
                                    .Aggregate(f =>
                {
                    Thread.Sleep(1);
                    return(f.Max(c => c.Id));
                })
                                    .Pivot(i =>
                {
                    var result = new List <PipelineTestsMyTestClass>();
                    for (var j = 1; j <= i; j++)
                    {
                        result.Add(new PipelineTestsMyTestClass {
                            Id = j, Name = $"Bob {j}"
                        });
                    }
                    return(result);
                })
                                    .Project(i =>
                {
                    var nameParts = i.Name.Split(' ');
                    return(new PipelineTestsOtherTestClass {
                        Id = i.Id, FirstName = nameParts[0], LastName = nameParts[1]
                    });
                })
                                    .TransformInPlace(i =>
                {
                    i.Id       -= 1;
                    i.FirstName = "Alice";
                    i.LastName  = $"{i.Id}";
                })
                                    .WriteTo(writer);

                await pipeline.ExecuteAsync();

                var totalStepsExpected = 6;
                Assert.True(2 * totalStepsExpected == loggerFactory.LoggedMessages.Count, string.Join("\r\n", loggerFactory.LoggedMessages.Select(m => m.Message))); //2 log messages for each step in the pipeline

                for (var i = 1; i <= totalStepsExpected; i++)
                {
                    var messagesForStep = loggerFactory.LoggedMessages.Where(m => m.Message.Contains($"step {i} of {totalStepsExpected}")).ToList();
                    Assert.True(messagesForStep.Count == 2, $"Found {messagesForStep.Count} messages for step {i}");

                    Assert.Equal(1, messagesForStep.Count(m => m.Message.Contains("Starting")));
                    Assert.Equal(1, messagesForStep.Count(m => m.Message.Contains("Completing")));
                }
            }
        }
Beispiel #13
0
 public WarningAsErrorContext(
     FakeLoggerFactory sink = null,
     EventId?toLog          = null,
     EventId?toThrow        = null)
 {
     _sink    = sink;
     _toLog   = toLog;
     _toThrow = toThrow;
 }
        public LoggingTests()
        {
            var factory = new FakeLoggerFactory();

            _logger = factory.Logger;
            _bus    = CqrsBus
                      .UseAssemblyFor <FakeLogger>()
                      .AddLogging(factory)
                      .Build();
        }
Beispiel #15
0
        public async Task Response422IfUpdatingNotSettableAttribute()
        {
            // Arrange
            var builder = WebHost.CreateDefaultBuilder().UseStartup <TestStartup>();

            var loggerFactory = new FakeLoggerFactory();

            builder.ConfigureLogging(options =>
            {
                options.AddProvider(loggerFactory);
                options.SetMinimumLevel(LogLevel.Trace);
                options.AddFilter((category, level) => level == LogLevel.Trace &&
                                  (category == typeof(JsonApiReader).FullName || category == typeof(JsonApiWriter).FullName));
            });

            var server = new TestServer(builder);
            var client = server.CreateClient();

            var todoItem = _todoItemFaker.Generate();

            _context.TodoItems.Add(todoItem);
            await _context.SaveChangesAsync();

            var serializer = TestFixture <TestStartup> .GetSerializer <TodoItem>(server.Host.Services, ti => new { ti.CalculatedValue });

            var content = serializer.Serialize(todoItem);
            var request = PrepareRequest("PATCH", $"/api/v1/todoItems/{todoItem.Id}", content);

            // Act
            var response = await client.SendAsync(request);

            // Assert
            Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);

            var body = await response.Content.ReadAsStringAsync();

            var document = JsonConvert.DeserializeObject <ErrorDocument>(body);

            Assert.Single(document.Errors);

            var error = document.Errors.Single();

            Assert.Equal(HttpStatusCode.UnprocessableEntity, error.StatusCode);
            Assert.Equal("Failed to deserialize request body.", error.Title);
            Assert.StartsWith("Property 'TodoItem.CalculatedValue' is read-only. - Request body: <<", error.Detail);

            Assert.NotEmpty(loggerFactory.Logger.Messages);
            Assert.Contains(loggerFactory.Logger.Messages,
                            x => x.Text.StartsWith("Received request at ") && x.Text.Contains("with body:"));
            Assert.Contains(loggerFactory.Logger.Messages,
                            x => x.Text.StartsWith("Sending 422 response for request at ") && x.Text.Contains("Failed to deserialize request body."));
        }
        public DecorationTests()
        {
            FakeRetryFailuresEventHandler.TimesHandled = 0;

            var loggerFactory = new FakeLoggerFactory();

            _logger = loggerFactory.Logger;

            _bus = CqrsBus.UseAssemblyFor <FakeLogger>()
                   .AddLogging(loggerFactory)
                   .AddRetry()
                   .Build();
        }
        public void InvalidConnectionTest()
        {
            var mock = new Mock <DataCommandOptions>();

            mock.Setup(opt => opt.CreateConnection()).Returns(() => null);

            //Setup some valid properties
            mock.Object.ConnectionString = "Host=localhost;";

            FakeLoggerFactory loggerFac = new FakeLoggerFactory();
            var command = new FakeDataCommand <int>("ACommand", mock.Object, loggerFac, (conn) => 0);

            Assert.Throws <InvalidOperationException>(() => command.Run());
        }
        protected UseCaseTests()
        {
            var loggerFactory = new FakeLoggerFactory();

            var httpClientFactory = new FakeHttpClientFactory();

            HttpClient = httpClientFactory.Client;

            var configurationFactory = new ConfigurationFactory();

            Config = configurationFactory.Create();

            _filesContainerMock = new Mock <CloudBlobContainer>(new Uri("https://something.com/files"));
            _filesContainerMock.Setup(s => s.GetBlockBlobReference(It.IsAny <string>()))
            .Returns(() =>
            {
                var mock = CreateMockCloudBlockBlob("idk");
                mock.Setup(s => s.ExistsAsync()).ReturnsAsync(false);
                return(mock.Object);
            });
            var blobClientMock = new Mock <CloudBlobClient>(new Uri("https://something.com"));

            blobClientMock.Setup(s => s.GetContainerReference("files")).Returns(_filesContainerMock.Object);

            StorageAccount = new Mock <CloudStorageAccount>(new StorageCredentials("storageaccount", ""), false);
            StorageAccount.Setup(s => s.CreateCloudBlobClient()).Returns(blobClientMock.Object);

            var storageAccountFactory = new Mock <IStorageAccountFactory>();

            storageAccountFactory.Setup(s => s.Get()).Returns(StorageAccount.Object);


            _provider = new ServiceCollection()
                        .AddRealTimePresenter(Config)

                        .RemoveAll <ILoggerFactory>()
                        .AddSingleton <ILoggerFactory>(loggerFactory)

                        .RemoveAll <IHttpClientFactory>()
                        .AddSingleton <IHttpClientFactory>(httpClientFactory)
                        .AddSingleton(httpClientFactory)

                        .RemoveAll <IConfiguration>()
                        .AddSingleton(Config)

                        .RemoveAll <IStorageAccountFactory>()
                        .AddSingleton(storageAccountFactory.Object)

                        .BuildServiceProvider();
        }
        public void Adding_DbContext_Members_That_Do_Not_Implement_IIdentifiable_Logs_Warning()
        {
            // Arrange
            var loggerFactory        = new FakeLoggerFactory();
            var resourceGraphBuilder = new ResourceGraphBuilder(new JsonApiOptions(), loggerFactory);

            resourceGraphBuilder.AddResource(typeof(TestContext));

            // Act
            resourceGraphBuilder.Build();

            // Assert
            Assert.Single(loggerFactory.Logger.Messages);
            Assert.Equal(LogLevel.Warning, loggerFactory.Logger.Messages[0].LogLevel);
            Assert.Equal("Entity 'UnitTests.Internal.ResourceGraphBuilder_Tests+TestContext' does not implement 'IIdentifiable'.", loggerFactory.Logger.Messages[0].Text);
        }
        public ConnectedProjectionsStreamStoreSubscriptionTests()
        {
            _fixture = new Fixture();

            _streamStoreMock = new StreamStoreMock();
            _commandBusMock  = new Mock <IConnectedProjectionsCommandBus>();

            var loggerFactory = new FakeLoggerFactory();

            _loggerMock = loggerFactory.ResolveLoggerMock <ConnectedProjectionsStreamStoreSubscription>();

            _sut = new ConnectedProjectionsStreamStoreSubscription(
                _streamStoreMock.Object,
                _commandBusMock.Object,
                loggerFactory);
        }
        public ConnectedProjectionsCommandHandlerTests()
        {
            _fixture = new Fixture()
                       .CustomizeConnectedProjectionIdentifiers()
                       .CustomizeConnectedProjectionCommands();

            var fakeLoggerFactory = new FakeLoggerFactory();

            _handlerLoggerMock      = fakeLoggerFactory.ResolveLoggerMock <ConnectedProjectionsCommandHandler>();
            _subscriptionRunnerMock = new Mock <IConnectedProjectionsSubscriptionRunner>();
            _catchUpRunnerMock      = new Mock <IConnectedProjectionsCatchUpRunner>();
            _commandBusMock         = new Mock <IConnectedProjectionsCommandBus>();

            _sut = new ConnectedProjectionsCommandHandler(
                _subscriptionRunnerMock.Object,
                _catchUpRunnerMock.Object,
                _commandBusMock.Object,
                fakeLoggerFactory);
        }
Beispiel #22
0
        public async Task EnablesWhenEndPointIsHit()
        {
            var workspace = await TestHelpers.CreateSimpleWorkspace(new Dictionary <string, string>
            {
                { "a.cs", "class C1 { int n = true; }" },
                { "b.cs", "class C2 { int n = true; }" },
            });

            var fakeLoggerFactory = new FakeLoggerFactory();
            var messages          = new List <OmniSharp.Models.DiagnosticMessage>();
            var emitter           = new DiagnosticTestEmitter(messages);
            var forwarder         = new DiagnosticEventForwarder(emitter);
            var service           = new CSharpDiagnosticService(workspace, forwarder, fakeLoggerFactory);

            var controller = new DiagnosticsService(workspace, forwarder, service);
            var response   = await controller.Handle(new OmniSharp.Models.DiagnosticsRequest());

            Assert.Equal(true, forwarder.IsEnabled);
        }
        public void ConstructorTest()
        {
            DataCommandOptions defaultOpts = new FakeDataOptions();
            FakeLoggerFactory  loggerFac   = new FakeLoggerFactory();

            Assert.Throws <ArgumentNullException>(() => new FakeDataCommand <int>(null, null, null));
            Assert.Throws <ArgumentNullException>(() => new FakeDataCommand <int>("", null, null));
            Assert.Throws <ArgumentNullException>(() => new FakeDataCommand <int>(" ", null, null));
            Assert.Throws <ArgumentNullException>(() => new FakeDataCommand <int>("WithAName", defaultOpts, null));

            // Should check argument exceptions, because some properties in data options are empty
            // ConnectionString is a required option
            Assert.Throws <ArgumentException>(() => new FakeDataCommand <int>("WithAName", defaultOpts, loggerFac));

            // Now, let's setup this as this should be
            defaultOpts.ConnectionString = "some connection string;";

            // Creates a data command. No Exception should be thrown at this time.
            new FakeDataCommand <int>("WithAName", defaultOpts, loggerFac);
        }
        public void ExecuteWithOpenConnectionTest()
        {
            var dataOptions = new FakeDataOptions()
            {
                ConnectionString = "Host=localhost;"
            };
            var loggerFactory = new FakeLoggerFactory();

            var mockCommand = new FakeDataCommand <int>("ACommand", dataOptions, loggerFactory, (conn) => 0);

            //Setup the mock command
            var ret = mockCommand.Run();

            //Do the asserts
            Assert.True(dataOptions.CreatedConnection != null);
            Assert.True(dataOptions.CreatedConnection.OpenCount == 1);
            Assert.True(dataOptions.CreatedConnection.State == ConnectionState.Closed);
            Assert.True(mockCommand.LastExecuteState == ConnectionState.Open);
            Assert.True(ret == 0);
        }
Beispiel #25
0
        public void When_using_custom_exception_handler_it_must_create_error_document_and_log()
        {
            // Arrange
            var loggerFactory = new FakeLoggerFactory();
            var options       = new JsonApiOptions {
                IncludeExceptionStackTraceInErrors = true
            };
            var handler = new CustomExceptionHandler(loggerFactory, options);

            // Act
            var errorDocument = handler.HandleException(new NoPermissionException("YouTube"));

            // Assert
            Assert.Single(errorDocument.Errors);
            Assert.Equal("For support, email to: [email protected]?subject=YouTube",
                         errorDocument.Errors[0].Meta.Data["support"]);
            Assert.NotEmpty((string[])errorDocument.Errors[0].Meta.Data["StackTrace"]);

            Assert.Single(loggerFactory.Logger.Messages);
            Assert.Equal(LogLevel.Warning, loggerFactory.Logger.Messages[0].LogLevel);
            Assert.Contains("Access is denied.", loggerFactory.Logger.Messages[0].Text);
        }
        public void RetryTest1()
        {
            int tryOpenCount = 0;

            FakeDataOptions defaultOpts = new FakeDataOptions()
            {
                ConnectionString    = "Host=localhost;",
                MaxRetries          = 2,
                OnOpeningConnection = () => {
                    tryOpenCount++;
                    Task.Delay(1000);

                    throw new Npgsql.NpgsqlException();
                }
            };

            defaultOpts.ShouldRetryList.Add(typeof(Npgsql.NpgsqlException));

            FakeLoggerFactory loggerFac = new FakeLoggerFactory();

            DataCommand <int> command   = new FakeDataCommand <int>("CommandForRetry", defaultOpts, loggerFac);
            Exception         exception = null;

            try
            {
                command.Run();
            }
            catch (Exception ex)
            {
                exception = ex;
            }

            Assert.Equal(tryOpenCount, 3); //The first attempt + 2 retries
            Assert.True(exception != null);
            Assert.IsType <Npgsql.NpgsqlException>(exception);
        }
        public void Low_level_services_can_be_replaced_after_being_added()
        {
            var serviceCollection = new ServiceCollection();

            var loggerFactory = new FakeLoggerFactory();

            serviceCollection
                .AddEntityFramework();

            serviceCollection
                .AddInstance<ILoggerFactory>(loggerFactory);

            var provider = serviceCollection.BuildServiceProvider();

            Assert.Same(loggerFactory, provider.GetRequiredService<ILoggerFactory>());
        }
        public void Required_low_level_services_are_not_added_if_already_present()
        {
            var serviceCollection = new ServiceCollection();

            var loggerFactory = new FakeLoggerFactory();

            serviceCollection
                .AddInstance<ILoggerFactory>(loggerFactory)
                .AddEntityFramework();

            var provider = serviceCollection.BuildServiceProvider();

            Assert.Same(loggerFactory, provider.GetRequiredService<ILoggerFactory>());
        }
Beispiel #29
0
 private Bot CreateBot()
 {
     fakeLoggerFactory = new FakeLoggerFactory();
     return(new Bot(new CoyoteHandler(fakeLoggerFactory), new PostAnalyzer(null), new Blacklist(), fakeLoggerFactory));
 }
Beispiel #30
0
 protected override void When()
 {
     FakeLoggerFactory.InitializeOnce();
     _createdLogger = LogFactory.Create("Given_a_app_configured_logger_factory.When_creating_a_logger");
 }
Beispiel #31
0
 protected override void When()
 {
     FakeLoggerFactory.InitializeOnce();
     _createdLogger = LogFactory.Create <FakeLoggerFactory>();
 }
Beispiel #32
0
        public When_the_subscription_runner_processing_a_stream_event_throws_a_detected_stream_gap_exception()
        {
            var fixture = new Fixture();

            _commandBusMock = new Mock <IConnectedProjectionsCommandBus>();
            var streamMock = new Mock <IConnectedProjectionsStreamStoreSubscription>();

            streamMock
            .SetupGet(stream => stream.StreamIsRunning)
            .Returns(true);

            var contextMock = new Mock <IConnectedProjectionContext <FakeProjectionContext> >();

            contextMock
            .Setup(context => context.GetProjectionPosition(It.IsAny <ConnectedProjectionIdentifier>(), It.IsAny <CancellationToken>()))
            .ReturnsAsync((long?)null);

            var missingMessagesPositions = fixture.CreateMany <long>(2, 10).ToList();

            _registeredProjections = new List <IConnectedProjection>
            {
                new FakeProjection(
                    $"{MissingMessageProjectionIdentifier}-1",
                    ThrowMissingMessageException(missingMessagesPositions),
                    contextMock.Object),
                new FakeProjection(
                    "do-nothing",
                    (messages, strategy, name, ct) => Task.CompletedTask,
                    contextMock.Object),
                new FakeProjection(
                    $"{MissingMessageProjectionIdentifier}-2",
                    ThrowMissingMessageException(missingMessagesPositions),
                    contextMock.Object)
            };

            var registeredProjectionsMock = new Mock <IRegisteredProjections>();

            registeredProjectionsMock
            .Setup(projections => projections.GetProjection(It.IsAny <ConnectedProjectionIdentifier>()))
            .Returns((ConnectedProjectionIdentifier projectionId) => _registeredProjections.FirstOrDefault(projection => projection.Id.Equals(projectionId)));

            var loggerFactory = new FakeLoggerFactory();

            _loggerMock = loggerFactory.ResolveLoggerMock <ConnectedProjectionsSubscriptionRunner>();

            _gapStrategySettings = fixture.Create <StreamGapStrategyConfigurationSettings>();
            var gapStrategyMock = new Mock <IStreamGapStrategy>();

            gapStrategyMock
            .SetupGet(strategy => strategy.Settings)
            .Returns(_gapStrategySettings);

            _sut = new ConnectedProjectionsSubscriptionRunner(
                registeredProjectionsMock.Object,
                streamMock.Object,
                _commandBusMock.Object,
                gapStrategyMock.Object,
                loggerFactory);

            foreach (var projection in _registeredProjections)
            {
                _sut.HandleSubscriptionCommand(new Subscribe(projection.Id)).GetAwaiter();
            }

            VerifySetup();
            _sut.HandleSubscriptionCommand(new ProcessStreamEvent(fixture.Create <StreamMessage>(), fixture.Create <CancellationToken>())).GetAwaiter();
        }