using Xunit.Abstractions;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.EntityFrameworkCore;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Hosting;
public class MigrationTests
[InlineData("true", true)]
[InlineData("false", false)]
public async Task ApplyMigrations_CurrentLogic_Behavior(string envValue, bool shouldMigrate)
Environment.SetEnvironmentVariable("ENABLE_DB_MIGRATION_IN_PRIMARY_REGION", envValue);
var migrateCalled = false;
var mockDbContext = new Mock<ApplicationDbContext>();
mockDbContext.Setup(db => db.Database.MigrateAsync(default))
.Callback(() => migrateCalled = true)
.Returns(Task.CompletedTask);
var services = new ServiceCollection()
.AddSingleton(mockDbContext.Object)
var mockHost = new Mock<IHost>();
mockHost.Setup(h => h.Services).Returns(services);
await ApplyMigrationsAsync(mockHost.Object);
Assert.Equal(shouldMigrate, migrateCalled);
public async Task AzureSecondary_NoFlagSet_ShouldSkipMigration_ButCurrentLogicIncorrectlyRunsMigration()
Environment.SetEnvironmentVariable("ENABLE_DB_MIGRATION_IN_PRIMARY_REGION", null);
var migrateCalled = false;
var mockDbContext = new Mock<ApplicationDbContext>();
mockDbContext.Setup(db => db.Database.MigrateAsync(default))
.Callback(() => migrateCalled = true)
.Returns(Task.CompletedTask);
var services = new ServiceCollection()
.AddSingleton(mockDbContext.Object)
var mockHost = new Mock<IHost>();
mockHost.Setup(h => h.Services).Returns(services);
await ApplyMigrationsAsync(mockHost.Object);
Assert.False(migrateCalled);
private static async Task ApplyMigrationsAsync(IHost host)
using var scope = host.Services.CreateScope();
var services = scope.ServiceProvider;
var logger = services.GetRequiredService<ILogger<MigrationTests>>();
var envValue = Environment.GetEnvironmentVariable("ENABLE_DB_MIGRATION_IN_PRIMARY_REGION");
if (envValue != null && bool.TryParse(envValue, out var isMigrationEnabled) && !isMigrationEnabled)
logger.LogInformation("Skipping database migration as it is explicitly disabled.");
var context = services.GetRequiredService<ApplicationDbContext>();
await context.Database.MigrateAsync();
logger.LogInformation("Database migration applied successfully in primary region.");
logger.LogError(ex, "An error occurred while applying database migrations in primary region.");
public static async Task Main()
var testAssembly = typeof(Program).Assembly;
var testRunner = AssemblyRunner.WithoutAppDomain(testAssembly.Location);
testRunner.OnTestFailed = info =>
Console.WriteLine($"[FAIL] {info.TestDisplayName}: {info.ExceptionMessage}");
testRunner.OnTestPassed = info =>
Console.WriteLine($"[PASS] {info.TestDisplayName}");
while (testRunner.Status != AssemblyRunnerStatus.Idle)