-
Notifications
You must be signed in to change notification settings - Fork 1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat: TestContainers 🚀 #578
Draft
trulshj
wants to merge
1
commit into
main
Choose a base branch
from
testcontainers
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
{ | ||
"AzureAd": { | ||
"DisableAuthAd": false, | ||
"Instance": "https://login.microsoftonline.com/", | ||
"ClientId": "7ef3a24e-7093-41dc-9163-9618415137fe", | ||
"TenantId": "0f16d077-bd82-4a6c-b498-52741239205f", | ||
"ApiScope": "api://7ef3a24e-7093-41dc-9163-9618415137fe/Vibes.ReadWrite" | ||
}, | ||
"ConnectionStrings": { | ||
"VibesDb": "Server=localhost;Database=AzureVibesDb;User Id=sa;Password=yourStrong(!)Password;;TrustServerCertificate=true" | ||
}, | ||
"InfrastructureConfig": { | ||
"EnableSensitiveDataLogging": true | ||
}, | ||
"TestContainersConfig": { | ||
"Enabled": true, | ||
"RunMigrations": true, | ||
"SeedDatabase": false | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
{ | ||
"TestContainersConfig": { | ||
"Enabled": true, | ||
"RunMigrations": true, | ||
"SeedDatabase": false | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
using Infrastructure.DatabaseContext; | ||
using Infrastructure.TestContainers; | ||
using Microsoft.Extensions.DependencyInjection; | ||
using Microsoft.Extensions.Hosting; | ||
|
||
namespace Infrastructure; | ||
|
||
public static class DependencyInjection | ||
{ | ||
public static IHostApplicationBuilder AddInfrastructure(this IHostApplicationBuilder builder) | ||
{ | ||
builder | ||
.AddConfig<InfrastructureConfig>(out _) | ||
.AddConfig<TestContainersConfig>(out var currentTestContainersConfig); | ||
|
||
if (currentTestContainersConfig.Enabled) | ||
builder.AddTestContainers(); | ||
|
||
builder.Services.AddDbContext<ApplicationContext>(); | ||
|
||
return builder; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
using Microsoft.Extensions.Configuration; | ||
using Microsoft.Extensions.DependencyInjection; | ||
using Microsoft.Extensions.Hosting; | ||
|
||
namespace Infrastructure; | ||
|
||
public sealed record InfrastructureConfig | ||
{ | ||
public required string ConnectionString { get; set; } | ||
public required bool EnableSensitiveDataLogging { get; set; } | ||
} | ||
|
||
internal static class ConfigExtensions | ||
{ | ||
internal static IHostApplicationBuilder AddConfig<T>(this IHostApplicationBuilder builder, out T currentConfig) | ||
where T : class | ||
{ | ||
var name = typeof(T); | ||
var configSection = builder.Configuration.GetSection(typeof(T).Name); | ||
builder.Services.Configure<T>(configSection); | ||
currentConfig = configSection.Get<T>()!; | ||
return builder; | ||
} | ||
} |
8 changes: 8 additions & 0 deletions
8
backend/Infrastructure/TestContainers/TestContainersConfig.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
namespace Infrastructure.TestContainers; | ||
|
||
public record TestContainersConfig | ||
{ | ||
public required bool Enabled { get; set; } | ||
public required bool RunMigrations { get; set; } | ||
public required bool SeedDatabase { get; set; } | ||
} |
82 changes: 82 additions & 0 deletions
82
backend/Infrastructure/TestContainers/TestContainersFactory.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,82 @@ | ||
using Infrastructure.DatabaseContext; | ||
using Microsoft.EntityFrameworkCore; | ||
using Microsoft.Extensions.Logging; | ||
using Microsoft.Extensions.Options; | ||
using Testcontainers.SqlEdge; | ||
|
||
namespace Infrastructure.TestContainers; | ||
|
||
public class TestContainersFactory(TestContainersConfig config, ILogger<TestContainersFactory> logger) | ||
{ | ||
private const string DbPassword = "test123!"; | ||
private const int DbHostPort = 14333; | ||
|
||
public static readonly string DefaultConnectionString = | ||
$"Server=127.0.0.1,{DbHostPort};Database=master;User Id=sa;Password={DbPassword};TrustServerCertificate=True"; | ||
|
||
private SqlEdgeContainer? _sqlEdgeContainer; | ||
|
||
public string? CurrentConnectionString => _sqlEdgeContainer?.GetConnectionString(); | ||
|
||
public async Task Start(CancellationToken cancellationToken = default, Overrides? overrides = null) | ||
{ | ||
try | ||
{ | ||
if (!config.Enabled) return; | ||
|
||
var dbHostPort = overrides?.DbHostPortOverride ?? DbHostPort; | ||
var dbContainerName = overrides?.DbContainerNameOverride ?? "testcontainers-api-db"; | ||
|
||
logger.LogInformation("Starting TestContainers"); | ||
|
||
_sqlEdgeContainer = new SqlEdgeBuilder() | ||
.WithName(dbContainerName) | ||
.WithReuse(true) | ||
.WithPassword(DbPassword) | ||
.WithPortBinding(dbHostPort, 1433) | ||
.Build(); | ||
|
||
await _sqlEdgeContainer.StartAsync(cancellationToken); | ||
|
||
var options = Options.Create(new InfrastructureConfig | ||
{ | ||
ConnectionString = _sqlEdgeContainer.GetConnectionString(), | ||
EnableSensitiveDataLogging = true | ||
}); | ||
|
||
await using var context = new ApplicationContext(options); | ||
|
||
if (config.RunMigrations) | ||
await MigrateDatabase(context, cancellationToken); | ||
|
||
if (config.SeedDatabase) logger.LogInformation("Seeding database with test data"); | ||
// TODO: DataBuilder | ||
} | ||
catch (Exception e) | ||
{ | ||
logger.LogError(e, "Error while starting TestContainers"); | ||
} | ||
} | ||
|
||
public Task Stop(CancellationToken cancellationToken = default) | ||
{ | ||
var stopTask = _sqlEdgeContainer?.StopAsync(cancellationToken) ?? Task.CompletedTask; | ||
return stopTask; | ||
} | ||
|
||
public record Overrides(string? DbContainerNameOverride, int? DbHostPortOverride); | ||
|
||
private async Task MigrateDatabase(DbContext context, CancellationToken cancellationToken) | ||
{ | ||
var retries = 0; | ||
while (!await context.Database.CanConnectAsync(cancellationToken) && retries < 10) | ||
{ | ||
retries++; | ||
logger.LogInformation("Attempt #{AttemptNumber} to connect to DB failed, retrying in 1 second.", retries); | ||
await Task.Delay(1000, cancellationToken); | ||
} | ||
|
||
logger.LogInformation("Running database migrations"); | ||
await context.Database.MigrateAsync(cancellationToken); | ||
} | ||
} |
26 changes: 26 additions & 0 deletions
26
backend/Infrastructure/TestContainers/TestContainersHostBuilder.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
using Microsoft.Extensions.DependencyInjection; | ||
using Microsoft.Extensions.Hosting; | ||
|
||
namespace Infrastructure.TestContainers; | ||
|
||
public static class TestContainersHostBuilder | ||
{ | ||
public static void AddTestContainers(this IHostApplicationBuilder builder) | ||
{ | ||
if (!builder.Environment.IsValidTestContainersEnvironment()) | ||
throw new InvalidOperationException( | ||
$"{nameof(AddTestContainers)} should only be called in dev environments. Current environment: {builder.Environment.EnvironmentName}"); | ||
|
||
builder.Services.AddHostedService<TestContainersService>(); | ||
|
||
builder.Services.Configure<InfrastructureConfig>(opts => | ||
{ | ||
opts.ConnectionString = TestContainersFactory.DefaultConnectionString; | ||
}); | ||
} | ||
|
||
private static bool IsValidTestContainersEnvironment(this IHostEnvironment environment) | ||
{ | ||
return environment.IsDevelopment() || environment.EnvironmentName == "Local"; | ||
} | ||
} |
43 changes: 43 additions & 0 deletions
43
backend/Infrastructure/TestContainers/TestContainersService.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
using Microsoft.Extensions.DependencyInjection; | ||
using Microsoft.Extensions.Hosting; | ||
using Microsoft.Extensions.Logging; | ||
using Microsoft.Extensions.Options; | ||
|
||
namespace Infrastructure.TestContainers; | ||
|
||
public class TestContainersService(IServiceProvider serviceProvider) : IHostedService | ||
{ | ||
private TestContainersFactory? _testContainersFactory; | ||
|
||
public async Task StartAsync(CancellationToken cancellationToken) | ||
{ | ||
using var scope = serviceProvider.CreateScope(); | ||
var logger = scope.ServiceProvider.GetRequiredService<ILogger<TestContainersService>>(); | ||
|
||
try | ||
{ | ||
logger.LogInformation("Running TestContainersService"); | ||
|
||
var config = scope.ServiceProvider.GetRequiredService<IOptions<TestContainersConfig>>().Value; | ||
if (config.Enabled) | ||
{ | ||
var testContainersLogger = scope.ServiceProvider.GetRequiredService<ILogger<TestContainersFactory>>(); | ||
_testContainersFactory = new TestContainersFactory(config, testContainersLogger); | ||
|
||
await _testContainersFactory.Start(cancellationToken); | ||
} | ||
} | ||
catch (Exception e) | ||
{ | ||
logger.LogError(e, "Failed to start test containers service"); | ||
throw; | ||
} | ||
|
||
logger.LogInformation("Finished running TestContainersService"); | ||
} | ||
|
||
public Task StopAsync(CancellationToken cancellationToken) | ||
{ | ||
return _testContainersFactory?.Stop(cancellationToken) ?? Task.CompletedTask; | ||
} | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Shouldn't this be gitignored?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Oops