11using System . Globalization ;
22using Microsoft . Extensions . Configuration ;
3+ using Testcontainers . PostgreSql ;
34
45namespace Microsoft . EntityFrameworkCore . TestUtilities ;
56
67public static class TestEnvironment
78{
89 public static IConfiguration Config { get ; }
910
11+ public static string ConnectionString { get ; }
12+
13+ // Keep a reference to prevent GC from collecting (and finalizing/stopping) the container while tests are running.
14+ private static readonly PostgreSqlContainer ? _postgreSqlContainer ;
15+
1016 static TestEnvironment ( )
1117 {
1218 var configBuilder = new ConfigurationBuilder ( )
@@ -18,13 +24,37 @@ static TestEnvironment()
1824 Config = configBuilder . Build ( )
1925 . GetSection ( "Test:Npgsql" ) ;
2026
21- Thread . CurrentThread . CurrentCulture = new CultureInfo ( "en-US" ) ;
22- }
27+ if ( Config [ "DefaultConnection" ] is { } connectionString )
28+ {
29+ Console . WriteLine ( "Using connection string configured via Test:Npgsql:DefaultConnection: " + connectionString ) ;
2330
24- private const string DefaultConnectionString = "Server=localhost;Username=npgsql_tests;Password=npgsql_tests;Port=5432" ;
31+ ConnectionString = connectionString ;
32+ }
33+ else
34+ {
35+ Console . WriteLine ( "No connection string configured via Test:Npgsql:DefaultConnection, starting up testcontainer..." ) ;
2536
26- public static string DefaultConnection
27- => Config [ "DefaultConnection" ] ?? DefaultConnectionString ;
37+ _postgreSqlContainer = new PostgreSqlBuilder ( "postgres:latest" )
38+ . WithCommand ( "-c" , "max_connections=200" )
39+ . Build ( ) ;
40+ _postgreSqlContainer . StartAsync ( ) . GetAwaiter ( ) . GetResult ( ) ;
41+ ConnectionString = _postgreSqlContainer . GetConnectionString ( ) ;
42+
43+ AppDomain . CurrentDomain . ProcessExit += ( _ , _ ) =>
44+ {
45+ try
46+ {
47+ _postgreSqlContainer ? . DisposeAsync ( ) . AsTask ( ) . GetAwaiter ( ) . GetResult ( ) ;
48+ }
49+ catch
50+ {
51+ // Ignore exceptions during process-exit cleanup.
52+ }
53+ } ;
54+ }
55+
56+ Thread . CurrentThread . CurrentCulture = new CultureInfo ( "en-US" ) ;
57+ }
2858
2959 private static Version ? _postgresVersion ;
3060
0 commit comments