using Microsoft.Extensions.Logging.Abstractions;
using NSubstitute;
using ScadaLink.Commons.Entities.ExternalSystems;
using ScadaLink.Commons.Interfaces.Repositories;
namespace ScadaLink.ExternalSystemGateway.Tests;
///
/// WP-9: Tests for Database access — connection resolution, cached writes.
///
public class DatabaseGatewayTests
{
private readonly IExternalSystemRepository _repository = Substitute.For();
[Fact]
public async Task GetConnection_NotFound_Throws()
{
_repository.GetAllDatabaseConnectionsAsync().Returns(new List());
var gateway = new DatabaseGateway(
_repository,
NullLogger.Instance);
await Assert.ThrowsAsync(
() => gateway.GetConnectionAsync("nonexistent"));
}
[Fact]
public async Task CachedWrite_NoStoreAndForward_Throws()
{
var conn = new DatabaseConnectionDefinition("testDb", "Server=localhost;Database=test") { Id = 1 };
_repository.GetAllDatabaseConnectionsAsync()
.Returns(new List { conn });
var gateway = new DatabaseGateway(
_repository,
NullLogger.Instance,
storeAndForward: null);
await Assert.ThrowsAsync(
() => gateway.CachedWriteAsync("testDb", "INSERT INTO t VALUES (1)"));
}
[Fact]
public async Task CachedWrite_ConnectionNotFound_Throws()
{
_repository.GetAllDatabaseConnectionsAsync().Returns(new List());
var gateway = new DatabaseGateway(
_repository,
NullLogger.Instance);
await Assert.ThrowsAsync(
() => gateway.CachedWriteAsync("nonexistent", "INSERT INTO t VALUES (1)"));
}
// ── ExternalSystemGateway-001: buffered CachedDbWrite delivery handler ──
[Fact]
public async Task DeliverBuffered_ConnectionNoLongerExists_ReturnsFalseSoMessageParks()
{
_repository.GetAllDatabaseConnectionsAsync().Returns(new List());
var gateway = new DatabaseGateway(_repository, NullLogger.Instance);
var message = new ScadaLink.StoreAndForward.StoreAndForwardMessage
{
Id = Guid.NewGuid().ToString("N"),
Category = ScadaLink.Commons.Types.Enums.StoreAndForwardCategory.CachedDbWrite,
Target = "gone-db",
PayloadJson =
"""{"ConnectionName":"gone-db","Sql":"INSERT INTO t VALUES (1)","Parameters":null}""",
};
var delivered = await gateway.DeliverBufferedAsync(message);
Assert.False(delivered); // permanent — the S&F engine parks the message
}
}