public void WhenPublishingEventShouldResultInLogEntriesCountOfOne()
        {
            // Arrange
            using (var context = new AuditLogContext(_options))
            {
                var repository    = new AuditLogRepository(context);
                var eventListener = new AuditLogEventListener(repository);
                using var eventBus = new EventBusBuilder()
                                     .FromEnvironment()
                                     .CreateEventBus(new ConnectionFactory())
                                     .AddEventListener(eventListener, "#");

                var awaitHandle = new ManualResetEvent(false);

                // Act
                PublishMessage(eventBus);
                awaitHandle.WaitOne(1000);
            }

            // Assert
            using (var context = new AuditLogContext(_options))
            {
                Assert.AreEqual(1, context.LogEntries.Count());
                Assert.IsTrue(context.LogEntries.Any(entry => entry.EventJson.Contains("Hello world")));
            }
        }
Example #2
0
        public void TestCleanup()
        {
            var context = new AuditLogContext(_options);

            context.Set <AuditLogItem>().RemoveRange(context.Set <AuditLogItem>());
            context.SaveChanges();
        }
        public void CreateOneLogEntryResultsInCountOf5()
        {
            // Arrange
            using (var context = new AuditLogContext(_options))
            {
                var repository = new AuditLogRepository(context);
                var logEntry   = new LogEntry
                {
                    Timestamp  = new DateTime(2019, 7, 2).Ticks,
                    EventJson  = "{'title': 'Something'}",
                    EventType  = "DomainEvent",
                    RoutingKey = "Test.TestQueue.TestCreated"
                };

                // Act
                repository.Create(logEntry);
            }

            // Assert
            using (var context = new AuditLogContext(_options))
            {
                var result = context.LogEntries.Count();
                Assert.AreEqual(5, result);
            }
        }
Example #4
0
        public void SavingAnItemWorks(string data, string topic)
        {
            // Arrange
            using (var context = new AuditLogContext(_options))
            {
                var repository = new AuditLogItemRepository(context);

                var item = new AuditLogItem
                {
                    Data  = data,
                    Topic = topic,
                    Id    = Guid.NewGuid().ToString()
                };

                // Act
                repository.Save(item);
            }

            // Assert
            using var controlContext = new AuditLogContext(_options);

            var resultData = controlContext.AuditLogItems.ToArray();

            Assert.AreEqual(1, resultData.Length);

            var firstItem = resultData.First();

            Assert.AreEqual(data, firstItem.Data);
            Assert.AreEqual(topic, firstItem.Topic);
        }
 protected static void WriteToLog(AuditLog logItem)
 {
     using (var context = new AuditLogContext())
     {
         context.AuditLogs.AddObject(logItem);
         context.SaveChanges();
     }
 }
Example #6
0
        public static void ClassInitialize(TestContext tc)
        {
            _connection = new SqliteConnection("DataSource=:memory:");
            _connection.Open();
            _options = new DbContextOptionsBuilder <AuditLogContext>()
                       .UseSqlite(_connection).Options;

            using var context = new AuditLogContext(_options);
            context.Database.EnsureCreated();
        }
        public void FindAllResultCountIs4()
        {
            // Arrange
            using var context = new AuditLogContext(_options);
            var repository = new AuditLogRepository(context);

            // Act
            var result = repository.FindAll();

            // Assert
            Assert.AreEqual(4, result.Count());
        }
        public void FindAllIsInstanceOfIEnumerableOfLogEntry()
        {
            // Arrange
            using var context = new AuditLogContext(_options);
            var repository = new AuditLogRepository(context);

            // Act
            var result = repository.FindAll();

            // Assert
            Assert.IsInstanceOfType(result, typeof(IEnumerable <LogEntry>));
        }
        public void FindByWithNoDomainEventShouldBeCountOf4()
        {
            // Arrange
            using var context = new AuditLogContext(_options);
            var repository = new AuditLogRepository(context);
            var criteria   = new LogEntryCriteria
            {
                FromTimestamp = new DateTime(2019, 2, 2).Ticks,
                ToTimestamp   = new DateTime(2019, 9, 10).Ticks,
            };

            // Act
            var result = repository.FindBy(criteria);

            // Assert
            Assert.AreEqual(4, result.Count());
        }
        public void FindByWithTimestampsOutOfReachShouldBeCountOf0()
        {
            // Arrange
            using var context = new AuditLogContext(_options);
            var repository = new AuditLogRepository(context);
            var criteria   = new LogEntryCriteria
            {
                EventType     = "DomainEvent",
                FromTimestamp = new DateTime(2019, 6, 7).Ticks,
                ToTimestamp   = new DateTime(2019, 6, 10).Ticks,
            };

            // Act
            var result = repository.FindBy(criteria);

            // Assert
            Assert.AreEqual(0, result.Count());
        }
        public void FindByIsInstanceOfIEnumerableOfLogEntry()
        {
            // Arrange
            using var context = new AuditLogContext(_options);
            var repository = new AuditLogRepository(context);
            var criteria   = new LogEntryCriteria
            {
                EventType     = "DomainEvent",
                FromTimestamp = new DateTime(2019, 7, 1).Ticks,
                ToTimestamp   = new DateTime(2019, 7, 3).Ticks,
            };

            // Act
            var result = repository.FindBy(criteria);

            // Assert
            Assert.IsInstanceOfType(result, typeof(IEnumerable <LogEntry>));
        }
        public void TestInitialize()
        {
            AuditLogLoggerFactory.LoggerFactory = NullLoggerFactory.Instance;
            Environment.SetEnvironmentVariable("HOSTNAME", "localhost");
            Environment.SetEnvironmentVariable("PORT", "5672");
            Environment.SetEnvironmentVariable("USERNAME", "Guest");
            Environment.SetEnvironmentVariable("PASSWORD", "Guest");
            Environment.SetEnvironmentVariable("EXCHANGE_NAME", "TestExchange");
            _connection = new SqliteConnection("DataSource=:memory:");
            _connection.Open();

            _options = new DbContextOptionsBuilder <AuditLogContext>()
                       .UseSqlite(_connection)
                       .Options;

            using var context = new AuditLogContext(_options);
            context.Database.EnsureCreated();
        }
        public void EventIsProperlyReceived(string data)
        {
            // Arrange
            AuditLogContext dbContext      = new AuditLogContext(_options);
            TestBusContext  testBusContext = new TestBusContext();

            using var hostBuilder = new MicroserviceHostBuilder()
                                    .WithBusContext(testBusContext)
                                    .RegisterDependencies(services =>
            {
                services.AddSingleton(dbContext);
                services.AddTransient <IAuditLogItemRepository, AuditLogItemRepository>();
            })
                                    .AddEventListener <IAuditLogItemRepository>()
                                    .AddEventListener <AuditEventLoggingListener>();

            using var host = hostBuilder.CreateHost();

            host.Start();

            DummyEvent evt = new DummyEvent("test.queue")
            {
                Text = data
            };

            IEventPublisher eventPublisher = new EventPublisher(testBusContext);

            // Act
            eventPublisher.Publish(evt);

            Thread.Sleep(1500);

            // Assert
            AuditLogItem[] resultData = dbContext.AuditLogItems.ToArray();
            Assert.AreEqual(1, resultData.Length);

            string expectedData = JsonConvert.SerializeObject(evt);

            var firstItem = resultData.First();

            Assert.AreEqual(expectedData, firstItem.Data);
            Assert.AreEqual(evt.Id.ToString(), firstItem.Id);
            Assert.AreEqual(new DateTime(evt.Timestamp).ToFileTimeUtc(), firstItem.TimeStamp);
        }
Example #14
0
        public void RetrievingItemsWithTypeWorks(string types, int expectedAmount)
        {
            string[] typeNames = types.Split(',');

            // Arrange
            InjectData(_dummyData);

            using var context = new AuditLogContext(_options);
            var repository = new AuditLogItemRepository(context);

            var criteria = new AuditLogItemCriteria {
                Types = typeNames, ToTimeStamp = 100
            };

            // Act
            AuditLogItem[] results = repository.FindBy(criteria).ToArray();

            // Assert
            Assert.AreEqual(expectedAmount, results.Length);
        }
Example #15
0
        public void RetrievingItemsFromSpecificTimePeriodWorks(long fromTimeStamp, long toTimeStamp, int expectedAmount)
        {
            // Arrange
            InjectData(_dummyData);

            using var context = new AuditLogContext(_options);
            var repository = new AuditLogItemRepository(context);

            var criteria = new AuditLogItemCriteria
            {
                FromTimeStamp = fromTimeStamp,
                ToTimeStamp   = toTimeStamp
            };

            // Act
            AuditLogItem[] results = repository.FindBy(criteria).ToArray();

            // Assert
            Assert.AreEqual(expectedAmount, results.Length);
        }
Example #16
0
        public void AllowingMetaEventsFiltersEvents(bool allowMeta, int expectedAmount)
        {
            // Arrange
            InjectData(_dummyData);

            using var context = new AuditLogContext(_options);
            var repository = new AuditLogItemRepository(context);

            var criteria = new AuditLogItemCriteria
            {
                AllowMetaEvents = allowMeta,
                ToTimeStamp     = 600,
                FromTimeStamp   = 0
            };

            // Act
            AuditLogItem[] results = repository.FindBy(criteria).ToArray();

            // Assert
            Assert.AreEqual(expectedAmount, results.Length);
        }
        private void SeedData()
        {
            using var context = new AuditLogContext(_options);
            var logEntries = new List <LogEntry>
            {
                new LogEntry
                {
                    Timestamp  = new DateTime(2019, 5, 8).Ticks,
                    RoutingKey = "Test.*",
                    EventJson  = "{'title': 'Some title'}",
                    EventType  = "DomainEvent"
                },
                new LogEntry
                {
                    Timestamp  = new DateTime(2019, 7, 2).Ticks,
                    RoutingKey = "Test.#",
                    EventJson  = "{'title': 'Some title'}",
                    EventType  = "DomainEvent"
                },
                new LogEntry
                {
                    Timestamp  = new DateTime(2019, 7, 2).Ticks,
                    RoutingKey = "Test.#",
                    EventJson  = "{'title': 'Some title'}",
                    EventType  = "DomainEvent"
                },
                new LogEntry
                {
                    Timestamp  = new DateTime(2019, 8, 15).Ticks,
                    RoutingKey = "Test2.#",
                    EventJson  = "{'title': 'Some title'}",
                    EventType  = "DomainEvent"
                }
            };

            context.LogEntries.AddRange(logEntries);

            context.SaveChanges();
        }
 /// <summary>
 /// Inject needed dependencies
 /// </summary>
 public AuditLogItemRepository(AuditLogContext context)
 {
     _auditLogContext = context;
 }
Example #19
0
        public static void Main(string[] args)
        {
            var logLevel = Environment.GetEnvironmentVariable("LOG_LEVEL") ??
                           throw new InvalidEnvironmentException(
                                     "Environment variable [LOG_LEVEL] was not provided.");

            Enum.TryParse(logLevel, true, out LogLevel result);

            var loggerFactory = LoggerFactory.Create(builder => builder.SetMinimumLevel(result).AddConsole());

            AuditLogLoggerFactory.LoggerFactory = loggerFactory;

            var logger = loggerFactory.CreateLogger("Program");

            try
            {
                var connectionString = Environment.GetEnvironmentVariable("CONNECTION_STRING") ??
                                       throw new InvalidEnvironmentException(
                                                 "Environment variable [CONNECTION_STRING] was not provided.");

                var options = new DbContextOptionsBuilder <AuditLogContext>()
                              .UseMySql(connectionString)
                              .Options;
                using var context = new AuditLogContext(options);

                var       createdAndSeeded = false;
                const int waitTime         = 1000;
                while (!createdAndSeeded)
                {
                    try
                    {
                        context.Database.EnsureCreated();
                        createdAndSeeded = true;
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                        Thread.Sleep(waitTime);
                    }
                }

                var repository        = new AuditLogRepository(context);
                var routingKeyMatcher = new RoutingKeyMatcher();
                var eventListener     = new AuditLogEventListener(repository);
                var eventBusBuilder   = new EventBusBuilder().FromEnvironment();
                using var eventBus = eventBusBuilder.CreateEventBus(new ConnectionFactory
                {
                    HostName = eventBusBuilder.HostName,
                    Port     = eventBusBuilder.Port,
                    UserName = eventBusBuilder.UserName,
                    Password = eventBusBuilder.Password
                });
                var eventReplayer   = new EventReplayer(eventBus);
                var commandListener =
                    new AuditLogCommandListener(repository, eventReplayer, routingKeyMatcher, eventBus);
                eventBus.AddEventListener(eventListener, "#");
                eventBus.AddCommandListener(commandListener, "AuditLog");

                logger.LogTrace("Host started, audit logger ready to log");

                _stopEvent.WaitOne();
            }
            catch (Exception e)
            {
                logger.LogError($"Error occured while running the client with message: {e.Message}");
            }
        }
Example #20
0
 /// <summary>
 /// Inject data directly into the context
 /// </summary>
 private void InjectData(params AuditLogItem[] items)
 {
     using var context = new AuditLogContext(_options);
     context.AuditLogItems.AddRange(items);
     context.SaveChanges();
 }