forked from PhenX/PhenX.EntityFrameworkCore.BulkInsert
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTestDbContainer.cs
More file actions
67 lines (52 loc) · 2.47 KB
/
TestDbContainer.cs
File metadata and controls
67 lines (52 loc) · 2.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
using System.Data.Common;
using System.Reflection;
using DotNet.Testcontainers.Builders;
using DotNet.Testcontainers.Configurations;
using DotNet.Testcontainers.Containers;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging.Abstractions;
using PhenX.EntityFrameworkCore.BulkInsert.Tests.DbContext;
using Testcontainers.Xunit;
using Xunit.Abstractions;
namespace PhenX.EntityFrameworkCore.BulkInsert.Tests.DbContainer;
public abstract class TestDbContainer<TBuilderEntity, TContainerEntity>(IMessageSink messageSink) : DbContainerFixture<TBuilderEntity, TContainerEntity>(messageSink), IDbContextFactory
where TBuilderEntity : IContainerBuilder<TBuilderEntity, TContainerEntity, IContainerConfiguration>, new()
where TContainerEntity : IContainer, IDatabaseContainer
{
protected abstract void Configure(DbContextOptionsBuilder optionsBuilder, string databaseName);
protected abstract TBuilderEntity CreateBuilder();
protected virtual string DbmsName => typeof(TContainerEntity).Name.Replace("Container", "");
protected override TBuilderEntity Configure()
{
var targetFramework = GetType().Assembly.GetCustomAttributes<AssemblyMetadataAttribute>().FirstOrDefault(e => e.Key == "TargetFramework")?.Value ?? "NA";
return CreateBuilder()
.WithReuse(true)
.WithName($"PhenX.EntityFrameworkCore.BulkInsert.Tests.{DbmsName}-{targetFramework}")
.WithWaitStrategy(Wait.ForUnixContainer().UntilDatabaseIsAvailable(DbProviderFactory));
}
protected virtual string GetConnectionString(string databaseName)
{
var builder = DbProviderFactory.CreateConnectionStringBuilder() ?? new DbConnectionStringBuilder();
builder.ConnectionString = ConnectionString;
builder["database"] = databaseName;
return builder.ToString();
}
protected virtual async Task EnsureDatabaseCreatedAsync(Microsoft.EntityFrameworkCore.DbContext dbContext)
{
await dbContext.Database.EnsureCreatedAsync();
}
public async Task<TDbContext> CreateContextAsync<TDbContext>(string databaseName)
where TDbContext : TestDbContextBase, new()
{
var dbContext = new TDbContext
{
ConfigureOptions = (builder) =>
{
builder.UseLoggerFactory(NullLoggerFactory.Instance);
Configure(builder, databaseName);
}
};
await EnsureDatabaseCreatedAsync(dbContext);
return dbContext;
}
}