Added migration tool
This commit is contained in:
@@ -0,0 +1,34 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<LangVersion>14.0</LangVersion>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<IsPackable>false</IsPackable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="coverlet.collector" Version="8.0.0">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.3.0" />
|
||||
<PackageReference Include="xunit" Version="2.9.3" />
|
||||
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.5">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="FluentAssertions" Version="8.8.0" />
|
||||
<PackageReference Include="Moq" Version="4.20.72" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Using Include="Xunit" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\HaDbMigration\HaDbMigration.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,200 @@
|
||||
using FluentAssertions;
|
||||
using HaDbMigration.Configuration;
|
||||
|
||||
namespace HaDbMigration.Tests;
|
||||
|
||||
public sealed class MigrationOptionsTests
|
||||
{
|
||||
[Fact]
|
||||
public void Validate_WithValidOptions_ShouldNotThrow()
|
||||
{
|
||||
// Arrange
|
||||
var tempFile = Path.GetTempFileName();
|
||||
try
|
||||
{
|
||||
var options = new MigrationOptions
|
||||
{
|
||||
SqlitePath = tempFile,
|
||||
PostgresConnectionString = "Host=localhost;Database=test",
|
||||
BatchSize = 10_000,
|
||||
};
|
||||
|
||||
// Act
|
||||
var act = () => options.Validate();
|
||||
|
||||
// Assert
|
||||
act.Should().NotThrow();
|
||||
}
|
||||
finally
|
||||
{
|
||||
File.Delete(tempFile);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WithMissingSqliteFile_ShouldThrowFileNotFoundException()
|
||||
{
|
||||
// Arrange
|
||||
var options = new MigrationOptions
|
||||
{
|
||||
SqlitePath = @"C:\nonexistent\path\db.sqlite",
|
||||
PostgresConnectionString = "Host=localhost;Database=test",
|
||||
};
|
||||
|
||||
// Act
|
||||
var act = () => options.Validate();
|
||||
|
||||
// Assert
|
||||
act.Should().Throw<FileNotFoundException>()
|
||||
.WithMessage("*nonexistent*");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WithEmptyPostgresConnectionString_ShouldThrowArgumentException()
|
||||
{
|
||||
// Arrange
|
||||
var tempFile = Path.GetTempFileName();
|
||||
try
|
||||
{
|
||||
var options = new MigrationOptions
|
||||
{
|
||||
SqlitePath = tempFile,
|
||||
PostgresConnectionString = "",
|
||||
};
|
||||
|
||||
// Act
|
||||
var act = () => options.Validate();
|
||||
|
||||
// Assert
|
||||
act.Should().Throw<ArgumentException>()
|
||||
.WithMessage("*connection string*");
|
||||
}
|
||||
finally
|
||||
{
|
||||
File.Delete(tempFile);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WithWhitespacePostgresConnectionString_ShouldThrowArgumentException()
|
||||
{
|
||||
// Arrange
|
||||
var tempFile = Path.GetTempFileName();
|
||||
try
|
||||
{
|
||||
var options = new MigrationOptions
|
||||
{
|
||||
SqlitePath = tempFile,
|
||||
PostgresConnectionString = " ",
|
||||
};
|
||||
|
||||
// Act
|
||||
var act = () => options.Validate();
|
||||
|
||||
// Assert
|
||||
act.Should().Throw<ArgumentException>();
|
||||
}
|
||||
finally
|
||||
{
|
||||
File.Delete(tempFile);
|
||||
}
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0)] // below minimum
|
||||
[InlineData(50)] // below minimum
|
||||
[InlineData(99)] // just below threshold
|
||||
public void Validate_WithBatchSizeBelowMinimum_ShouldThrowArgumentOutOfRangeException(int batchSize)
|
||||
{
|
||||
// Arrange
|
||||
var tempFile = Path.GetTempFileName();
|
||||
try
|
||||
{
|
||||
var options = new MigrationOptions
|
||||
{
|
||||
SqlitePath = tempFile,
|
||||
PostgresConnectionString = "Host=localhost;Database=test",
|
||||
BatchSize = batchSize,
|
||||
};
|
||||
|
||||
// Act
|
||||
var act = () => options.Validate();
|
||||
|
||||
// Assert
|
||||
act.Should().Throw<ArgumentOutOfRangeException>()
|
||||
.WithMessage("*at least 100*");
|
||||
}
|
||||
finally
|
||||
{
|
||||
File.Delete(tempFile);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WithBatchSizeAtMinimum_ShouldNotThrow()
|
||||
{
|
||||
// Arrange
|
||||
var tempFile = Path.GetTempFileName();
|
||||
try
|
||||
{
|
||||
var options = new MigrationOptions
|
||||
{
|
||||
SqlitePath = tempFile,
|
||||
PostgresConnectionString = "Host=localhost;Database=test",
|
||||
BatchSize = 100,
|
||||
};
|
||||
|
||||
// Act
|
||||
var act = () => options.Validate();
|
||||
|
||||
// Assert
|
||||
act.Should().NotThrow();
|
||||
}
|
||||
finally
|
||||
{
|
||||
File.Delete(tempFile);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DefaultBatchSize_ShouldBe10000()
|
||||
{
|
||||
// Arrange & Act
|
||||
var options = new MigrationOptions
|
||||
{
|
||||
SqlitePath = "test.db",
|
||||
PostgresConnectionString = "Host=localhost",
|
||||
};
|
||||
|
||||
// Assert
|
||||
options.BatchSize.Should().Be(10_000);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DefaultDryRun_ShouldBeFalse()
|
||||
{
|
||||
// Arrange & Act
|
||||
var options = new MigrationOptions
|
||||
{
|
||||
SqlitePath = "test.db",
|
||||
PostgresConnectionString = "Host=localhost",
|
||||
};
|
||||
|
||||
// Assert
|
||||
options.DryRun.Should().BeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DefaultTruncate_ShouldBeFalse()
|
||||
{
|
||||
// Arrange & Act
|
||||
var options = new MigrationOptions
|
||||
{
|
||||
SqlitePath = "test.db",
|
||||
PostgresConnectionString = "Host=localhost",
|
||||
};
|
||||
|
||||
// Assert
|
||||
options.Truncate.Should().BeFalse();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,260 @@
|
||||
using System.Threading.Channels;
|
||||
using FluentAssertions;
|
||||
using HaDbMigration.Configuration;
|
||||
using HaDbMigration.Models;
|
||||
using HaDbMigration.Services;
|
||||
using HaDbMigration.Services.Interfaces;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Moq;
|
||||
|
||||
namespace HaDbMigration.Tests;
|
||||
|
||||
public sealed class MigrationOrchestratorTests
|
||||
{
|
||||
private readonly Mock<ISqliteReaderService> _readerMock;
|
||||
private readonly Mock<IPostgresWriterService> _writerMock;
|
||||
private readonly Mock<ISchemaService> _schemaMock;
|
||||
private readonly Mock<IValidationService> _validationMock;
|
||||
private readonly Mock<ILogger<MigrationOrchestrator>> _loggerMock;
|
||||
|
||||
public MigrationOrchestratorTests()
|
||||
{
|
||||
_readerMock = new Mock<ISqliteReaderService>();
|
||||
_writerMock = new Mock<IPostgresWriterService>();
|
||||
_schemaMock = new Mock<ISchemaService>();
|
||||
_validationMock = new Mock<IValidationService>();
|
||||
_loggerMock = new Mock<ILogger<MigrationOrchestrator>>();
|
||||
}
|
||||
|
||||
private MigrationOrchestrator CreateSut(
|
||||
bool truncate = false,
|
||||
bool dryRun = false)
|
||||
{
|
||||
var options = new MigrationOptions
|
||||
{
|
||||
SqlitePath = "test.db",
|
||||
PostgresConnectionString = "Host=localhost",
|
||||
Truncate = truncate,
|
||||
DryRun = dryRun,
|
||||
};
|
||||
|
||||
return new MigrationOrchestrator(
|
||||
options,
|
||||
_readerMock.Object,
|
||||
_writerMock.Object,
|
||||
_schemaMock.Object,
|
||||
_validationMock.Object,
|
||||
_loggerMock.Object);
|
||||
}
|
||||
|
||||
private void SetupHappyPath()
|
||||
{
|
||||
_schemaMock
|
||||
.Setup(x => x.ValidateTablesExistAsync(
|
||||
It.IsAny<IReadOnlyList<TableDescriptor>>(),
|
||||
It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(true);
|
||||
|
||||
_readerMock
|
||||
.Setup(x => x.ReadTableAsync(
|
||||
It.IsAny<TableDescriptor>(),
|
||||
It.IsAny<ChannelWriter<IReadOnlyList<object?[]>>>(),
|
||||
It.IsAny<CancellationToken>()))
|
||||
.Returns((TableDescriptor _, ChannelWriter<IReadOnlyList<object?[]>> writer, CancellationToken _) =>
|
||||
{
|
||||
writer.Complete();
|
||||
return Task.CompletedTask;
|
||||
});
|
||||
|
||||
_writerMock
|
||||
.Setup(x => x.WriteTableAsync(
|
||||
It.IsAny<TableDescriptor>(),
|
||||
It.IsAny<ChannelReader<IReadOnlyList<object?[]>>>(),
|
||||
It.IsAny<CancellationToken>()))
|
||||
.Returns(async (TableDescriptor table, ChannelReader<IReadOnlyList<object?[]>> reader, CancellationToken ct) =>
|
||||
{
|
||||
await foreach (var batch in reader.ReadAllAsync(ct))
|
||||
{
|
||||
}
|
||||
});
|
||||
|
||||
_schemaMock
|
||||
.Setup(x => x.ResetSequencesAsync(
|
||||
It.IsAny<IReadOnlyList<TableDescriptor>>(),
|
||||
It.IsAny<CancellationToken>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
_validationMock
|
||||
.Setup(x => x.ValidateRowCountsAsync(
|
||||
It.IsAny<IReadOnlyList<TableDescriptor>>(),
|
||||
It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync([]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RunAsync_WhenTablesDoNotExist_ShouldNotMigrateData()
|
||||
{
|
||||
// Arrange
|
||||
_schemaMock
|
||||
.Setup(x => x.ValidateTablesExistAsync(
|
||||
It.IsAny<IReadOnlyList<TableDescriptor>>(),
|
||||
It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(false);
|
||||
|
||||
var sut = CreateSut();
|
||||
|
||||
// Act
|
||||
await sut.RunAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
_readerMock.Verify(
|
||||
x => x.ReadTableAsync(
|
||||
It.IsAny<TableDescriptor>(),
|
||||
It.IsAny<ChannelWriter<IReadOnlyList<object?[]>>>(),
|
||||
It.IsAny<CancellationToken>()),
|
||||
Times.Never);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RunAsync_WithTruncateEnabled_ShouldTruncateTables()
|
||||
{
|
||||
// Arrange
|
||||
SetupHappyPath();
|
||||
var sut = CreateSut(truncate: true);
|
||||
|
||||
// Act
|
||||
await sut.RunAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
_schemaMock.Verify(
|
||||
x => x.TruncateTablesAsync(
|
||||
It.IsAny<IReadOnlyList<TableDescriptor>>(),
|
||||
It.IsAny<CancellationToken>()),
|
||||
Times.Once);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RunAsync_WithTruncateDisabled_ShouldNotTruncateTables()
|
||||
{
|
||||
// Arrange
|
||||
SetupHappyPath();
|
||||
var sut = CreateSut(truncate: false);
|
||||
|
||||
// Act
|
||||
await sut.RunAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
_schemaMock.Verify(
|
||||
x => x.TruncateTablesAsync(
|
||||
It.IsAny<IReadOnlyList<TableDescriptor>>(),
|
||||
It.IsAny<CancellationToken>()),
|
||||
Times.Never);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RunAsync_InDryRunMode_ShouldNotResetSequences()
|
||||
{
|
||||
// Arrange
|
||||
SetupHappyPath();
|
||||
var sut = CreateSut(dryRun: true);
|
||||
|
||||
// Act
|
||||
await sut.RunAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
_schemaMock.Verify(
|
||||
x => x.ResetSequencesAsync(
|
||||
It.IsAny<IReadOnlyList<TableDescriptor>>(),
|
||||
It.IsAny<CancellationToken>()),
|
||||
Times.Never);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RunAsync_InDryRunMode_ShouldNotTruncateEvenIfFlagSet()
|
||||
{
|
||||
// Arrange
|
||||
SetupHappyPath();
|
||||
var sut = CreateSut(truncate: true, dryRun: true);
|
||||
|
||||
// Act
|
||||
await sut.RunAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
_schemaMock.Verify(
|
||||
x => x.TruncateTablesAsync(
|
||||
It.IsAny<IReadOnlyList<TableDescriptor>>(),
|
||||
It.IsAny<CancellationToken>()),
|
||||
Times.Never);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RunAsync_AfterSuccessfulMigration_ShouldValidateRowCounts()
|
||||
{
|
||||
// Arrange
|
||||
SetupHappyPath();
|
||||
var sut = CreateSut();
|
||||
|
||||
// Act
|
||||
await sut.RunAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
_validationMock.Verify(
|
||||
x => x.ValidateRowCountsAsync(
|
||||
It.IsAny<IReadOnlyList<TableDescriptor>>(),
|
||||
It.IsAny<CancellationToken>()),
|
||||
Times.Once);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RunAsync_AfterSuccessfulMigration_ShouldResetSequences()
|
||||
{
|
||||
// Arrange
|
||||
SetupHappyPath();
|
||||
var sut = CreateSut();
|
||||
|
||||
// Act
|
||||
await sut.RunAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
_schemaMock.Verify(
|
||||
x => x.ResetSequencesAsync(
|
||||
It.IsAny<IReadOnlyList<TableDescriptor>>(),
|
||||
It.IsAny<CancellationToken>()),
|
||||
Times.Once);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RunAsync_ShouldValidateSchemaFirst()
|
||||
{
|
||||
// Arrange
|
||||
SetupHappyPath();
|
||||
var callOrder = new List<string>();
|
||||
|
||||
_schemaMock
|
||||
.Setup(x => x.ValidateTablesExistAsync(
|
||||
It.IsAny<IReadOnlyList<TableDescriptor>>(),
|
||||
It.IsAny<CancellationToken>()))
|
||||
.Callback(() => callOrder.Add("validate"))
|
||||
.ReturnsAsync(true);
|
||||
|
||||
_readerMock
|
||||
.Setup(x => x.ReadTableAsync(
|
||||
It.IsAny<TableDescriptor>(),
|
||||
It.IsAny<ChannelWriter<IReadOnlyList<object?[]>>>(),
|
||||
It.IsAny<CancellationToken>()))
|
||||
.Callback(() => callOrder.Add("read"))
|
||||
.Returns((TableDescriptor _, ChannelWriter<IReadOnlyList<object?[]>> writer, CancellationToken _) =>
|
||||
{
|
||||
writer.Complete();
|
||||
return Task.CompletedTask;
|
||||
});
|
||||
|
||||
var sut = CreateSut();
|
||||
|
||||
// Act
|
||||
await sut.RunAsync(CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
callOrder.First().Should().Be("validate");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
using System.Reflection;
|
||||
using FluentAssertions;
|
||||
using HaDbMigration.Models;
|
||||
using HaDbMigration.Services;
|
||||
using NpgsqlTypes;
|
||||
|
||||
namespace HaDbMigration.Tests;
|
||||
|
||||
public sealed class PostgresWriterServiceTests
|
||||
{
|
||||
private const BindingFlags PrivateStatic = BindingFlags.NonPublic | BindingFlags.Static;
|
||||
|
||||
private static object? InvokeConvertValue(object value, ColumnDescriptor column)
|
||||
{
|
||||
return typeof(PostgresWriterService)
|
||||
.GetMethod("ConvertValue", PrivateStatic)!
|
||||
.Invoke(null, [value, column]);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0L, false)] // SQLite integer 0 -> PostgreSQL false
|
||||
[InlineData(1L, true)] // SQLite integer 1 -> PostgreSQL true
|
||||
[InlineData(42L, true)] // any non-zero -> true
|
||||
public void ConvertValue_WithBooleanConversion_ShouldConvertIntToBool(
|
||||
long input, bool expected)
|
||||
{
|
||||
// Arrange
|
||||
var column = new ColumnDescriptor("test", "test", NpgsqlDbType.Boolean, IsBooleanConversion: true);
|
||||
|
||||
// Act
|
||||
var result = InvokeConvertValue(input, column);
|
||||
|
||||
// Assert
|
||||
result.Should().Be(expected);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ConvertValue_WithBigintColumn_ShouldConvertToLong()
|
||||
{
|
||||
// Arrange
|
||||
var column = new ColumnDescriptor("id", "id", NpgsqlDbType.Bigint);
|
||||
|
||||
// Act
|
||||
var result = InvokeConvertValue(42, column);
|
||||
|
||||
// Assert
|
||||
result.Should().Be(42L);
|
||||
result.Should().BeOfType<long>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ConvertValue_WithIntegerColumn_ShouldConvertToInt()
|
||||
{
|
||||
// Arrange
|
||||
var column = new ColumnDescriptor("ver", "ver", NpgsqlDbType.Integer);
|
||||
|
||||
// Act
|
||||
var result = InvokeConvertValue(42L, column);
|
||||
|
||||
// Assert
|
||||
result.Should().Be(42);
|
||||
result.Should().BeOfType<int>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ConvertValue_WithSmallintColumn_ShouldConvertToShort()
|
||||
{
|
||||
// Arrange
|
||||
var column = new ColumnDescriptor("idx", "idx", NpgsqlDbType.Smallint);
|
||||
|
||||
// Act
|
||||
var result = InvokeConvertValue(5, column);
|
||||
|
||||
// Assert
|
||||
result.Should().Be((short)5);
|
||||
result.Should().BeOfType<short>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ConvertValue_WithDoubleColumn_ShouldConvertToDouble()
|
||||
{
|
||||
// Arrange
|
||||
var column = new ColumnDescriptor("ts", "ts", NpgsqlDbType.Double);
|
||||
|
||||
// Act
|
||||
var result = InvokeConvertValue(1234567890.123, column);
|
||||
|
||||
// Assert
|
||||
result.Should().BeOfType<double>();
|
||||
((double)result!).Should().BeApproximately(1234567890.123, 0.001);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ConvertValue_WithTextColumn_ShouldConvertToString()
|
||||
{
|
||||
// Arrange
|
||||
var column = new ColumnDescriptor("data", "data", NpgsqlDbType.Text);
|
||||
|
||||
// Act
|
||||
var result = InvokeConvertValue("{\"key\": \"value\"}", column);
|
||||
|
||||
// Assert
|
||||
result.Should().Be("{\"key\": \"value\"}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ConvertValue_WithVarcharColumn_ShouldConvertToString()
|
||||
{
|
||||
// Arrange
|
||||
var column = new ColumnDescriptor("name", "name", NpgsqlDbType.Varchar);
|
||||
|
||||
// Act
|
||||
var result = InvokeConvertValue("test_entity", column);
|
||||
|
||||
// Assert
|
||||
result.Should().Be("test_entity");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ConvertValue_WithCharColumnAndEmptyString_ShouldReturnNull()
|
||||
{
|
||||
// Arrange
|
||||
var column = new ColumnDescriptor("legacy", "legacy", NpgsqlDbType.Char);
|
||||
|
||||
// Act
|
||||
var result = InvokeConvertValue("", column);
|
||||
|
||||
// Assert
|
||||
result.Should().BeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ConvertValue_WithByteaColumn_ShouldReturnByteArray()
|
||||
{
|
||||
// Arrange
|
||||
var column = new ColumnDescriptor("bin", "bin", NpgsqlDbType.Bytea);
|
||||
var bytes = new byte[] { 0x01, 0x02, 0x03 };
|
||||
|
||||
// Act
|
||||
var result = InvokeConvertValue(bytes, column);
|
||||
|
||||
// Assert
|
||||
result.Should().BeOfType<byte[]>();
|
||||
((byte[])result!).Should().Equal(0x01, 0x02, 0x03);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ConvertValue_WithTimestampTzAndStringDate_ShouldConvertToUtcDateTime()
|
||||
{
|
||||
// Arrange
|
||||
var column = new ColumnDescriptor("ts", "ts", NpgsqlDbType.TimestampTz);
|
||||
|
||||
// Act
|
||||
var result = InvokeConvertValue("2024-01-15 10:30:00", column);
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
result.Should().BeOfType<DateTime>();
|
||||
((DateTime)result!).Kind.Should().Be(DateTimeKind.Utc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ConvertValue_WithTimestampTzAndDateTime_ShouldEnsureUtcKind()
|
||||
{
|
||||
// Arrange
|
||||
var column = new ColumnDescriptor("ts", "ts", NpgsqlDbType.TimestampTz);
|
||||
var unspecified = new DateTime(2024, 1, 15, 10, 30, 0, DateTimeKind.Unspecified);
|
||||
|
||||
// Act
|
||||
var result = InvokeConvertValue(unspecified, column);
|
||||
|
||||
// Assert
|
||||
result.Should().NotBeNull();
|
||||
((DateTime)result!).Kind.Should().Be(DateTimeKind.Utc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ConvertValue_WithTimestampTzAndInvalidString_ShouldReturnNull()
|
||||
{
|
||||
// Arrange
|
||||
var column = new ColumnDescriptor("ts", "ts", NpgsqlDbType.TimestampTz);
|
||||
|
||||
// Act
|
||||
var result = InvokeConvertValue("not-a-date", column);
|
||||
|
||||
// Assert
|
||||
result.Should().BeNull();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
using FluentAssertions;
|
||||
using HaDbMigration.Models;
|
||||
using NpgsqlTypes;
|
||||
|
||||
namespace HaDbMigration.Tests;
|
||||
|
||||
public sealed class TableDescriptorsTests
|
||||
{
|
||||
[Fact]
|
||||
public void GetMigrationOrder_ShouldReturn13Tables()
|
||||
{
|
||||
// Act
|
||||
var tables = TableDescriptors.GetMigrationOrder();
|
||||
|
||||
// Assert
|
||||
tables.Should().HaveCount(13);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetMigrationOrder_ShouldHaveLeafTablesBeforeDependentTables()
|
||||
{
|
||||
// Arrange
|
||||
var tables = TableDescriptors.GetMigrationOrder();
|
||||
var tableNames = tables.Select(t => t.TableName).ToList();
|
||||
|
||||
// Assert - event_types before events
|
||||
tableNames.IndexOf("event_types").Should().BeLessThan(tableNames.IndexOf("events"));
|
||||
|
||||
// Assert - event_data before events
|
||||
tableNames.IndexOf("event_data").Should().BeLessThan(tableNames.IndexOf("events"));
|
||||
|
||||
// Assert - states_meta before states
|
||||
tableNames.IndexOf("states_meta").Should().BeLessThan(tableNames.IndexOf("states"));
|
||||
|
||||
// Assert - state_attributes before states
|
||||
tableNames.IndexOf("state_attributes").Should().BeLessThan(tableNames.IndexOf("states"));
|
||||
|
||||
// Assert - statistics_meta before statistics
|
||||
tableNames.IndexOf("statistics_meta").Should().BeLessThan(tableNames.IndexOf("statistics"));
|
||||
|
||||
// Assert - statistics_meta before statistics_short_term
|
||||
tableNames.IndexOf("statistics_meta").Should().BeLessThan(tableNames.IndexOf("statistics_short_term"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Events_ShouldHaveCorrectColumns()
|
||||
{
|
||||
// Act
|
||||
var table = TableDescriptors.Events;
|
||||
|
||||
// Assert
|
||||
table.TableName.Should().Be("events");
|
||||
table.SequenceColumn.Should().Be("event_id");
|
||||
table.Columns.Should().HaveCount(15);
|
||||
table.Columns[0].IsPrimaryKey.Should().BeTrue();
|
||||
table.Columns[0].SqliteName.Should().Be("event_id");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void StatisticsMeta_ShouldHaveBooleanConversionColumns()
|
||||
{
|
||||
// Act
|
||||
var table = TableDescriptors.StatisticsMeta;
|
||||
var hasMeanColumn = table.Columns.First(c => c.SqliteName == "has_mean");
|
||||
var hasSumColumn = table.Columns.First(c => c.SqliteName == "has_sum");
|
||||
|
||||
// Assert
|
||||
hasMeanColumn.IsBooleanConversion.Should().BeTrue();
|
||||
hasMeanColumn.NpgsqlType.Should().Be(NpgsqlDbType.Boolean);
|
||||
hasSumColumn.IsBooleanConversion.Should().BeTrue();
|
||||
hasSumColumn.NpgsqlType.Should().Be(NpgsqlDbType.Boolean);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RecorderRuns_ShouldHaveBooleanConversionForClosedIncorrect()
|
||||
{
|
||||
// Act
|
||||
var table = TableDescriptors.RecorderRuns;
|
||||
var closedIncorrectColumn = table.Columns.First(c => c.SqliteName == "closed_incorrect");
|
||||
|
||||
// Assert
|
||||
closedIncorrectColumn.IsBooleanConversion.Should().BeTrue();
|
||||
closedIncorrectColumn.NpgsqlType.Should().Be(NpgsqlDbType.Boolean);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MigrationChanges_ShouldHaveNoSequenceColumn()
|
||||
{
|
||||
// Act
|
||||
var table = TableDescriptors.MigrationChanges;
|
||||
|
||||
// Assert
|
||||
table.SequenceColumn.Should().BeNull();
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("events", "event_id")]
|
||||
[InlineData("event_data", "data_id")]
|
||||
[InlineData("event_types", "event_type_id")]
|
||||
[InlineData("states", "state_id")]
|
||||
[InlineData("state_attributes", "attributes_id")]
|
||||
[InlineData("states_meta", "metadata_id")]
|
||||
[InlineData("recorder_runs", "run_id")]
|
||||
[InlineData("schema_changes", "change_id")]
|
||||
[InlineData("statistics", "id")]
|
||||
[InlineData("statistics_meta", "id")]
|
||||
[InlineData("statistics_short_term", "id")]
|
||||
[InlineData("statistics_runs", "run_id")]
|
||||
public void TablesWithSequences_ShouldHaveCorrectSequenceColumn(
|
||||
string tableName, string expectedSequenceColumn)
|
||||
{
|
||||
// Act
|
||||
var table = TableDescriptors.GetMigrationOrder().First(t => t.TableName == tableName);
|
||||
|
||||
// Assert
|
||||
table.SequenceColumn.Should().Be(expectedSequenceColumn);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AllTables_ShouldHaveAtLeastOneColumn()
|
||||
{
|
||||
// Act
|
||||
var tables = TableDescriptors.GetMigrationOrder();
|
||||
|
||||
// Assert
|
||||
tables.Should().AllSatisfy(t => t.Columns.Should().NotBeEmpty());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AllTables_ShouldHaveUniqueNames()
|
||||
{
|
||||
// Act
|
||||
var tables = TableDescriptors.GetMigrationOrder();
|
||||
var names = tables.Select(t => t.TableName).ToList();
|
||||
|
||||
// Assert
|
||||
names.Should().OnlyHaveUniqueItems();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void States_ShouldHaveByteaColumnsForContextBinaries()
|
||||
{
|
||||
// Act
|
||||
var table = TableDescriptors.States;
|
||||
var byteaColumns = table.Columns
|
||||
.Where(c => c.NpgsqlType == NpgsqlDbType.Bytea)
|
||||
.Select(c => c.SqliteName)
|
||||
.ToList();
|
||||
|
||||
// Assert
|
||||
byteaColumns.Should().Contain("context_id_bin");
|
||||
byteaColumns.Should().Contain("context_user_id_bin");
|
||||
byteaColumns.Should().Contain("context_parent_id_bin");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Events_ShouldHaveByteaColumnsForContextBinaries()
|
||||
{
|
||||
// Act
|
||||
var table = TableDescriptors.Events;
|
||||
var byteaColumns = table.Columns
|
||||
.Where(c => c.NpgsqlType == NpgsqlDbType.Bytea)
|
||||
.Select(c => c.SqliteName)
|
||||
.ToList();
|
||||
|
||||
// Assert
|
||||
byteaColumns.Should().Contain("context_id_bin");
|
||||
byteaColumns.Should().Contain("context_user_id_bin");
|
||||
byteaColumns.Should().Contain("context_parent_id_bin");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
using FluentAssertions;
|
||||
using HaDbMigration.Configuration;
|
||||
using HaDbMigration.Models;
|
||||
using HaDbMigration.Services;
|
||||
using HaDbMigration.Services.Interfaces;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Moq;
|
||||
using NpgsqlTypes;
|
||||
|
||||
namespace HaDbMigration.Tests;
|
||||
|
||||
public sealed class ValidationServiceTests
|
||||
{
|
||||
private readonly Mock<ISqliteReaderService> _sqliteReaderMock;
|
||||
private readonly Mock<IPostgresWriterService> _postgresWriterMock;
|
||||
private readonly Mock<ILogger<ValidationService>> _loggerMock;
|
||||
|
||||
public ValidationServiceTests()
|
||||
{
|
||||
_sqliteReaderMock = new Mock<ISqliteReaderService>();
|
||||
_postgresWriterMock = new Mock<IPostgresWriterService>();
|
||||
_loggerMock = new Mock<ILogger<ValidationService>>();
|
||||
}
|
||||
|
||||
private ValidationService CreateSut(bool dryRun = false)
|
||||
{
|
||||
var options = new MigrationOptions
|
||||
{
|
||||
SqlitePath = "test.db",
|
||||
PostgresConnectionString = "Host=localhost",
|
||||
DryRun = dryRun,
|
||||
};
|
||||
|
||||
return new ValidationService(
|
||||
_sqliteReaderMock.Object,
|
||||
_postgresWriterMock.Object,
|
||||
options,
|
||||
_loggerMock.Object);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ValidateRowCountsAsync_WhenCountsMatch_ShouldReturnAllMatched()
|
||||
{
|
||||
// Arrange
|
||||
var table = new TableDescriptor(
|
||||
"test_table",
|
||||
[new ColumnDescriptor("id", "id", NpgsqlDbType.Bigint, IsPrimaryKey: true)],
|
||||
"id");
|
||||
|
||||
_sqliteReaderMock
|
||||
.Setup(x => x.GetRowCountAsync("test_table", It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(1000);
|
||||
|
||||
_postgresWriterMock
|
||||
.Setup(x => x.GetRowCountAsync("test_table", It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(1000);
|
||||
|
||||
var sut = CreateSut();
|
||||
|
||||
// Act
|
||||
var results = await sut.ValidateRowCountsAsync([table], CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
results.Should().HaveCount(1);
|
||||
results[0].IsMatch.Should().BeTrue();
|
||||
results[0].SourceRowCount.Should().Be(1000);
|
||||
results[0].TargetRowCount.Should().Be(1000);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ValidateRowCountsAsync_WhenCountsMismatch_ShouldReturnMismatch()
|
||||
{
|
||||
// Arrange
|
||||
var table = new TableDescriptor(
|
||||
"test_table",
|
||||
[new ColumnDescriptor("id", "id", NpgsqlDbType.Bigint, IsPrimaryKey: true)],
|
||||
"id");
|
||||
|
||||
_sqliteReaderMock
|
||||
.Setup(x => x.GetRowCountAsync("test_table", It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(1000);
|
||||
|
||||
_postgresWriterMock
|
||||
.Setup(x => x.GetRowCountAsync("test_table", It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(500);
|
||||
|
||||
var sut = CreateSut();
|
||||
|
||||
// Act
|
||||
var results = await sut.ValidateRowCountsAsync([table], CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
results.Should().HaveCount(1);
|
||||
results[0].IsMatch.Should().BeFalse();
|
||||
results[0].SourceRowCount.Should().Be(1000);
|
||||
results[0].TargetRowCount.Should().Be(500);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ValidateRowCountsAsync_InDryRunMode_ShouldAlwaysReturnMatch()
|
||||
{
|
||||
// Arrange
|
||||
var table = new TableDescriptor(
|
||||
"test_table",
|
||||
[new ColumnDescriptor("id", "id", NpgsqlDbType.Bigint, IsPrimaryKey: true)],
|
||||
"id");
|
||||
|
||||
_sqliteReaderMock
|
||||
.Setup(x => x.GetRowCountAsync("test_table", It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(1000);
|
||||
|
||||
var sut = CreateSut(dryRun: true);
|
||||
|
||||
// Act
|
||||
var results = await sut.ValidateRowCountsAsync([table], CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
results.Should().HaveCount(1);
|
||||
results[0].IsMatch.Should().BeTrue();
|
||||
results[0].TargetRowCount.Should().Be(0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ValidateRowCountsAsync_InDryRunMode_ShouldNotQueryPostgres()
|
||||
{
|
||||
// Arrange
|
||||
var table = new TableDescriptor(
|
||||
"test_table",
|
||||
[new ColumnDescriptor("id", "id", NpgsqlDbType.Bigint, IsPrimaryKey: true)],
|
||||
"id");
|
||||
|
||||
_sqliteReaderMock
|
||||
.Setup(x => x.GetRowCountAsync(It.IsAny<string>(), It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(100);
|
||||
|
||||
var sut = CreateSut(dryRun: true);
|
||||
|
||||
// Act
|
||||
await sut.ValidateRowCountsAsync([table], CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
_postgresWriterMock.Verify(
|
||||
x => x.GetRowCountAsync(It.IsAny<string>(), It.IsAny<CancellationToken>()),
|
||||
Times.Never);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ValidateRowCountsAsync_WithMultipleTables_ShouldReturnResultForEach()
|
||||
{
|
||||
// Arrange
|
||||
var table1 = new TableDescriptor(
|
||||
"table1",
|
||||
[new ColumnDescriptor("id", "id", NpgsqlDbType.Bigint, IsPrimaryKey: true)],
|
||||
"id");
|
||||
var table2 = new TableDescriptor(
|
||||
"table2",
|
||||
[new ColumnDescriptor("id", "id", NpgsqlDbType.Bigint, IsPrimaryKey: true)],
|
||||
"id");
|
||||
|
||||
_sqliteReaderMock
|
||||
.Setup(x => x.GetRowCountAsync("table1", It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(100);
|
||||
_sqliteReaderMock
|
||||
.Setup(x => x.GetRowCountAsync("table2", It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(200);
|
||||
|
||||
_postgresWriterMock
|
||||
.Setup(x => x.GetRowCountAsync("table1", It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(100);
|
||||
_postgresWriterMock
|
||||
.Setup(x => x.GetRowCountAsync("table2", It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(200);
|
||||
|
||||
var sut = CreateSut();
|
||||
|
||||
// Act
|
||||
var results = await sut.ValidateRowCountsAsync([table1, table2], CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
results.Should().HaveCount(2);
|
||||
results.Should().AllSatisfy(r => r.IsMatch.Should().BeTrue());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ValidateRowCountsAsync_WithEmptyTable_ShouldHandleZeroCounts()
|
||||
{
|
||||
// Arrange
|
||||
var table = new TableDescriptor(
|
||||
"empty_table",
|
||||
[new ColumnDescriptor("id", "id", NpgsqlDbType.Bigint, IsPrimaryKey: true)],
|
||||
"id");
|
||||
|
||||
_sqliteReaderMock
|
||||
.Setup(x => x.GetRowCountAsync("empty_table", It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(0);
|
||||
|
||||
_postgresWriterMock
|
||||
.Setup(x => x.GetRowCountAsync("empty_table", It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(0);
|
||||
|
||||
var sut = CreateSut();
|
||||
|
||||
// Act
|
||||
var results = await sut.ValidateRowCountsAsync([table], CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
results.Should().HaveCount(1);
|
||||
results[0].IsMatch.Should().BeTrue();
|
||||
results[0].SourceRowCount.Should().Be(0);
|
||||
results[0].TargetRowCount.Should().Be(0);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user