using Testcontainers.MsSql;
namespace JdeScoping.DataSync.IntegrationTests.Infrastructure;
///
/// Shared fixture that manages the SQL Server Testcontainer lifecycle.
/// Container is started once per test collection and shared across all tests.
///
public class SqlServerFixture : IAsyncLifetime
{
private readonly MsSqlContainer _container;
///
/// Gets the connection string to the test SQL Server instance.
///
public string ConnectionString => _container.GetConnectionString();
public SqlServerFixture()
{
_container = new MsSqlBuilder()
.WithImage("mcr.microsoft.com/mssql/server:2022-latest")
.WithPassword("Test@Password123!")
.Build();
}
///
/// Starts the container and initializes the test database schema.
///
public async Task InitializeAsync()
{
await _container.StartAsync();
await TestDatabaseInitializer.InitializeAsync(ConnectionString);
}
///
/// Stops and disposes the container.
///
public async Task DisposeAsync()
{
await _container.DisposeAsync();
}
///
/// Creates a new open connection to the test database.
/// Caller is responsible for disposing the connection.
///
public async Task CreateConnectionAsync()
{
var connection = new SqlConnection(ConnectionString);
await connection.OpenAsync();
return connection;
}
///
/// Truncates all test tables to ensure clean state between tests.
///
public async Task CleanupTablesAsync()
{
await using var connection = await CreateConnectionAsync();
await connection.ExecuteAsync(@"
TRUNCATE TABLE WorkOrder_Test;
TRUNCATE TABLE Item_Test;
TRUNCATE TABLE LotUsage_Test;
TRUNCATE TABLE DataUpdate_Test;
TRUNCATE TABLE BulkMergeTest;
");
}
///
/// Cleans up just the BulkMergeTest table.
///
public async Task CleanupBulkMergeTestTableAsync()
{
await using var connection = await CreateConnectionAsync();
await connection.ExecuteAsync("TRUNCATE TABLE BulkMergeTest;");
}
}
///
/// Collection definition for sharing the SQL Server fixture across test classes.
///
[CollectionDefinition("Database")]
public class DatabaseCollection : ICollectionFixture
{
// This class has no code, and is never created.
// Its purpose is to be the place to apply [CollectionDefinition]
// and all the ICollectionFixture<> interfaces.
}