Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions src/KurrentDB.Core.Tests/Http/Info/when_getting_info.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
// Copyright (c) Kurrent, Inc and/or licensed to Kurrent, Inc under one or more agreements.
// Kurrent, Inc licenses this file to you under the Kurrent License v1 (see LICENSE.md).

using System;
using System.Net;
using System.Threading.Tasks;
using KurrentDB.Common.Utils;
using Newtonsoft.Json.Linq;
using NUnit.Framework;

namespace KurrentDB.Core.Tests.Http.Info;

[TestFixture(typeof(LogFormat.V2), typeof(string))]
public class when_getting_info<TLogFormat, TStreamId> : HttpBehaviorSpecification<TLogFormat, TStreamId> {
private JObject _response;

protected override Task Given() => Task.CompletedTask;

protected override async Task When() {
await Get("/info", "");
_response = _lastResponseBody.ParseJson<JObject>();
}
Comment on lines +13 to +22
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Action required

1. kurrentdb.core.tests missing testenvironmentwireup.cs 📘 Rule violation ⛯ Reliability

This PR adds new tests to the KurrentDB.Core.Tests project but the project does not include the
required TestEnvironmentWireUp.cs using ToolkitTestEnvironment.Initialize/Reset. This can lead
to inconsistent test initialization/teardown and shared infrastructure leakage across test runs.
Agent Prompt
## Issue description
`src/KurrentDB.Core.Tests` is being extended with new tests, but it lacks the required `TestEnvironmentWireUp.cs` that configures standard test initialization/teardown via `ToolkitTestEnvironment.Initialize` and `ToolkitTestEnvironment.Reset`.

## Issue Context
Compliance requires consistent assembly-level hooks for test infrastructure in every test project.

## Fix Focus Areas
- src/KurrentDB.Core.Tests/TestEnvironmentWireUp.cs[1-120]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


[Test]
public void returns_ok() {
Assert.AreEqual(HttpStatusCode.OK, _lastResponse.StatusCode);
}

[Test]
public void response_contains_cluster_id() {
var clusterId = _response["clusterId"];
Assert.That(clusterId, Is.Not.Null, "clusterId should be present in /info response");
Assert.That(clusterId.Type, Is.EqualTo(JTokenType.String));

var parsed = Guid.TryParse(clusterId.Value<string>(), out var guid);
Assert.That(parsed, Is.True, "clusterId should be a valid GUID");
Assert.That(guid, Is.Not.EqualTo(Guid.Empty));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ public int LastEpochNumber

public ValueTask Init(CancellationToken token) => ValueTask.CompletedTask;

public EpochRecord GetFirstEpoch() => _epochs.FirstOrDefault();
public EpochRecord GetLastEpoch() => _epochs.LastOrDefault();

public ValueTask<IReadOnlyList<EpochRecord>> GetLastEpochs(int maxCount, CancellationToken token) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,290 @@
// Copyright (c) Kurrent, Inc and/or licensed to Kurrent, Inc under one or more agreements.
// Kurrent, Inc licenses this file to you under the Kurrent License v1 (see LICENSE.md).

using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using KurrentDB.Core.Bus;
using KurrentDB.Core.LogAbstraction;
using KurrentDB.Core.Messages;
using KurrentDB.Core.Messaging;
using KurrentDB.Core.Services.Storage.EpochManager;
using KurrentDB.Core.Tests.TransactionLog;
using KurrentDB.Core.TransactionLog.Chunks;
using KurrentDB.Core.TransactionLog.LogRecords;
using NUnit.Framework;

namespace KurrentDB.Core.Tests.Services.Storage.EpochManager;

[TestFixture(typeof(LogFormat.V2), typeof(string))]
public sealed class when_getting_first_epoch_from_empty_log<TLogFormat, TStreamId> : SpecificationWithDirectoryPerTestFixture, IDisposable {
private TFChunkDb _db;
private LogFormatAbstractor<TStreamId> _logFormat;
private TFChunkWriter _writer;
private SynchronousScheduler _mainBus;
private readonly Guid _instanceId = Guid.NewGuid();
private readonly List<Message> _published = new();

private EpochManager<TStreamId> GetManager(int cacheSize = 10) {
return new EpochManager<TStreamId>(_mainBus,
cacheSize,
_db.Config.EpochCheckpoint,
_writer,
initialReaderCount: 1,
maxReaderCount: 5,
new TFChunkReader(_db, _db.Config.WriterCheckpoint),
_logFormat.RecordFactory,
_logFormat.StreamNameIndex,
_logFormat.EventTypeIndex,
_logFormat.CreatePartitionManager(
reader: new TFChunkReader(_db, _db.Config.WriterCheckpoint),
writer: _writer),
_instanceId);
}

[OneTimeSetUp]
public override async Task TestFixtureSetUp() {
await base.TestFixtureSetUp();

var indexDirectory = GetFilePathFor("index");
_logFormat = LogFormatHelper<TLogFormat, TStreamId>.LogFormatFactory.Create(new() {
IndexDirectory = indexDirectory,
});

_mainBus = new(nameof(when_getting_first_epoch_from_empty_log<TLogFormat, TStreamId>));
_mainBus.Subscribe(new AdHocHandler<SystemMessage.EpochWritten>(m => _published.Add(m)));
_db = new TFChunkDb(TFChunkHelper.CreateDbConfig(PathName, 0));
await _db.Open();
_writer = new TFChunkWriter(_db);
await _writer.Open(CancellationToken.None);
}

[OneTimeTearDown]
public override async Task TestFixtureTearDown() {
Dispose();
await base.TestFixtureTearDown();
}

[Test]
public async Task first_epoch_lifecycle() {
var manager = GetManager();
await manager.Init(CancellationToken.None);

// null before any epochs exist
Assert.That(manager.GetFirstEpoch(), Is.Null);

// available after writing epoch 0
await manager.WriteNewEpoch(0, CancellationToken.None);
var firstEpoch = manager.GetFirstEpoch();
Assert.That(firstEpoch, Is.Not.Null);
Assert.That(firstEpoch.EpochNumber, Is.EqualTo(0));
Assert.That(firstEpoch.EpochPosition, Is.EqualTo(0));
Assert.That(firstEpoch.PrevEpochPosition, Is.EqualTo(-1));

// still available after writing more epochs
for (int i = 1; i <= 20; i++)
await manager.WriteNewEpoch(i, CancellationToken.None);

Assert.That(manager.GetFirstEpoch().EpochId, Is.EqualTo(firstEpoch.EpochId));
}

public void Dispose() {
try {
_logFormat?.Dispose();
using var task = _writer?.DisposeAsync().AsTask() ?? Task.CompletedTask;
task.Wait();
} catch {
// workaround for TearDown error
}

using (var task = _db?.DisposeAsync().AsTask() ?? Task.CompletedTask) {
task.Wait();
}
}
}

[TestFixture(typeof(LogFormat.V2), typeof(string))]
public sealed class when_getting_first_epoch_after_caching<TLogFormat, TStreamId> : SpecificationWithDirectoryPerTestFixture, IDisposable {
private TFChunkDb _db;
private LogFormatAbstractor<TStreamId> _logFormat;
private TFChunkWriter _writer;
private SynchronousScheduler _mainBus;
private readonly Guid _instanceId = Guid.NewGuid();
private readonly List<Message> _published = new();

private EpochManager<TStreamId> GetManager(int cacheSize = 10) {
return new EpochManager<TStreamId>(_mainBus,
cacheSize,
_db.Config.EpochCheckpoint,
_writer,
initialReaderCount: 1,
maxReaderCount: 5,
new TFChunkReader(_db, _db.Config.WriterCheckpoint),
_logFormat.RecordFactory,
_logFormat.StreamNameIndex,
_logFormat.EventTypeIndex,
_logFormat.CreatePartitionManager(
reader: new TFChunkReader(_db, _db.Config.WriterCheckpoint),
writer: _writer),
_instanceId);
}

[OneTimeSetUp]
public override async Task TestFixtureSetUp() {
await base.TestFixtureSetUp();

var indexDirectory = GetFilePathFor("index");
_logFormat = LogFormatHelper<TLogFormat, TStreamId>.LogFormatFactory.Create(new() {
IndexDirectory = indexDirectory,
});

_mainBus = new(nameof(when_getting_first_epoch_after_caching<TLogFormat, TStreamId>));
_mainBus.Subscribe(new AdHocHandler<SystemMessage.EpochWritten>(m => _published.Add(m)));
_db = new TFChunkDb(TFChunkHelper.CreateDbConfig(PathName, 0));
await _db.Open();
_writer = new TFChunkWriter(_db);
await _writer.Open(CancellationToken.None);
}

[OneTimeTearDown]
public override async Task TestFixtureTearDown() {
Dispose();
await base.TestFixtureTearDown();
}

[Test]
public async Task is_set_after_caching_epoch_zero() {
var manager = GetManager();
await manager.Init(CancellationToken.None);

var epoch0 = new EpochRecord(0, 0, Guid.NewGuid(), -1, DateTime.UtcNow, _instanceId);
await manager.CacheEpoch(epoch0, CancellationToken.None);

var firstEpoch = manager.GetFirstEpoch();
Assert.That(firstEpoch, Is.Not.Null);
Assert.That(firstEpoch.EpochId, Is.EqualTo(epoch0.EpochId));
}

public void Dispose() {
try {
_logFormat?.Dispose();
using var task = _writer?.DisposeAsync().AsTask() ?? Task.CompletedTask;
task.Wait();
} catch {
// workaround for TearDown error
}

using (var task = _db?.DisposeAsync().AsTask() ?? Task.CompletedTask) {
task.Wait();
}
}
}

[TestFixture(typeof(LogFormat.V2), typeof(string))]
public sealed class when_getting_first_epoch_with_existing_epochs<TLogFormat, TStreamId> : SpecificationWithDirectoryPerTestFixture, IDisposable {
private TFChunkDb _db;
private LogFormatAbstractor<TStreamId> _logFormat;
private TFChunkWriter _writer;
private SynchronousScheduler _mainBus;
private readonly Guid _instanceId = Guid.NewGuid();
private readonly List<Message> _published = new();
private List<EpochRecord> _epochs;

private EpochManager<TStreamId> GetManager(int cacheSize = 10) {
return new EpochManager<TStreamId>(_mainBus,
cacheSize,
_db.Config.EpochCheckpoint,
_writer,
initialReaderCount: 1,
maxReaderCount: 5,
new TFChunkReader(_db, _db.Config.WriterCheckpoint),
_logFormat.RecordFactory,
_logFormat.StreamNameIndex,
_logFormat.EventTypeIndex,
_logFormat.CreatePartitionManager(
reader: new TFChunkReader(_db, _db.Config.WriterCheckpoint),
writer: _writer),
_instanceId);
}

private async ValueTask<EpochRecord> WriteEpochRaw(int epochNumber, long lastPos, CancellationToken token) {
long pos = _writer.Position;
var epoch = new EpochRecord(pos, epochNumber, Guid.NewGuid(), lastPos, DateTime.UtcNow, _instanceId);
var rec = new SystemLogRecord(epoch.EpochPosition, epoch.TimeStamp, SystemRecordType.Epoch,
SystemRecordSerialization.Json, epoch.AsSerialized());
await _writer.Write(rec, token);
await _writer.Flush(token);
return epoch;
}

[OneTimeSetUp]
public override async Task TestFixtureSetUp() {
await base.TestFixtureSetUp();

var indexDirectory = GetFilePathFor("index");
_logFormat = LogFormatHelper<TLogFormat, TStreamId>.LogFormatFactory.Create(new() {
IndexDirectory = indexDirectory,
});

_mainBus = new(nameof(when_getting_first_epoch_with_existing_epochs<TLogFormat, TStreamId>));
_mainBus.Subscribe(new AdHocHandler<SystemMessage.EpochWritten>(m => _published.Add(m)));
_db = new TFChunkDb(TFChunkHelper.CreateDbConfig(PathName, 0));
await _db.Open();
_writer = new TFChunkWriter(_db);
await _writer.Open(CancellationToken.None);

_epochs = new List<EpochRecord>();
var lastPos = -1L;
for (int i = 0; i < 30; i++) {
var epoch = await WriteEpochRaw(i, lastPos, CancellationToken.None);
_epochs.Add(epoch);
lastPos = epoch.EpochPosition;
}
}

[OneTimeTearDown]
public override async Task TestFixtureTearDown() {
Dispose();
await base.TestFixtureTearDown();
}

[Test]
public async Task is_available_when_epoch_zero_is_in_cache() {
var manager = GetManager(cacheSize: 1000);
await manager.Init(CancellationToken.None);

var firstEpoch = manager.GetFirstEpoch();
Assert.That(firstEpoch, Is.Not.Null);
Assert.That(firstEpoch.EpochNumber, Is.EqualTo(0));
Assert.That(firstEpoch.EpochId, Is.EqualTo(_epochs[0].EpochId));
}

[Test]
public async Task is_available_when_epoch_zero_is_not_in_cache() {
var manager = GetManager(cacheSize: 5);
await manager.Init(CancellationToken.None);

// cache only holds 5 epochs (25-29), but epoch 0 should still be available
Assert.That(manager.GetLastEpoch().EpochNumber, Is.EqualTo(29));

var firstEpoch = manager.GetFirstEpoch();
Assert.That(firstEpoch, Is.Not.Null);
Assert.That(firstEpoch.EpochNumber, Is.EqualTo(0));
Assert.That(firstEpoch.EpochId, Is.EqualTo(_epochs[0].EpochId));
}

public void Dispose() {
try {
_logFormat?.Dispose();
using var task = _writer?.DisposeAsync().AsTask() ?? Task.CompletedTask;
task.Wait();
} catch {
// workaround for TearDown error
}

using (var task = _db?.DisposeAsync().AsTask() ?? Task.CompletedTask) {
task.Wait();
}
}
}
3 changes: 2 additions & 1 deletion src/KurrentDB.Core/ClusterVNode.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1066,7 +1066,8 @@ GossipAdvertiseInfo GetGossipAdvertiseInfo() {
["userManagement"] = options.Auth.AuthenticationType == Opts.AuthenticationTypeDefault && !options.Application.Insecure,
["atomPub"] = options.Interface.EnableAtomPubOverHttp || options.DevMode.Dev
},
_authenticationProvider
_authenticationProvider,
epochManager
);

_mainBus.Subscribe<SystemMessage.StateChangeMessage>(infoController);
Expand Down
Loading
Loading