Skip to content

Commit bf4f644

Browse files
committed
fix(tests): avoid EnsureDeletedAsync on master with Testcontainers; use dedicated DB name and skip drop when using container
1 parent ac36a46 commit bf4f644

1 file changed

Lines changed: 11 additions & 4 deletions

File tree

.NET/EcoLens.Tests/Migrations/MigrationCoverageTests.cs

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
using System.Threading.Tasks;
22
using EcoLens.Api.Data;
3+
using Microsoft.Data.SqlClient;
34
using Microsoft.EntityFrameworkCore;
45
using Testcontainers.MsSql;
56
using Xunit;
@@ -48,7 +49,10 @@ private static bool LocalDbAvailable()
4849
{
4950
var container = new MsSqlBuilder().Build();
5051
await container.StartAsync();
51-
return (container.GetConnectionString(), container);
52+
// Use a dedicated database name; container default is 'master' and EnsureDeletedAsync cannot run on master.
53+
var dbName = "EcoLensMigrationCoverage_" + Guid.NewGuid().ToString("N")[..8];
54+
var builder = new SqlConnectionStringBuilder(container.GetConnectionString()) { InitialCatalog = dbName };
55+
return (builder.ConnectionString, container);
5256
}
5357
catch (Exception)
5458
{
@@ -81,9 +85,11 @@ public async Task ApplyAllMigrations_InitialCreate_And_AddPointAwardLogsEf_Execu
8185
Assert.NotEmpty(applied);
8286
}
8387

84-
await using (var context = new ApplicationDbContext(options))
88+
// Only drop DB when using LocalDB; with container, disposing the container removes everything (cannot run EnsureDeleted on master).
89+
if (container == null)
8590
{
86-
await context.Database.EnsureDeletedAsync();
91+
await using (var context = new ApplicationDbContext(options))
92+
await context.Database.EnsureDeletedAsync();
8793
}
8894
}
8995
finally
@@ -113,7 +119,8 @@ public async Task ApplyAllMigrations_Then_EnsureDatabase_CanBeUsed()
113119
Assert.Contains(migrations, m => m.Contains("InitialCreate"));
114120
Assert.Contains(migrations, m => m.Contains("AddPointAwardLogsEf"));
115121

116-
await context.Database.EnsureDeletedAsync();
122+
if (container == null)
123+
await context.Database.EnsureDeletedAsync();
117124
}
118125
finally
119126
{

0 commit comments

Comments
 (0)