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,28 @@ 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 ) ;
30+
31+ ConnectionString = connectionString ;
32+ }
33+ else
34+ {
35+ Console . WriteLine ( "No connection string configured via Test:Npgsql:DefaultConnection, starting up testcontainer..." ) ;
36+
37+ _postgreSqlContainer = new PostgreSqlBuilder ( "postgres:latest" )
38+ . WithCommand ( "-c" , "max_connections=200" )
39+ . Build ( ) ;
40+ _postgreSqlContainer . StartAsync ( ) . GetAwaiter ( ) . GetResult ( ) ;
41+ ConnectionString = _postgreSqlContainer . GetConnectionString ( ) ;
2342
24- private const string DefaultConnectionString = "Server=localhost;Username=npgsql_tests;Password=npgsql_tests;Port=5432" ;
43+ AppDomain . CurrentDomain . ProcessExit += ( _ , _ ) =>
44+ _postgreSqlContainer . DisposeAsync ( ) . AsTask ( ) . GetAwaiter ( ) . GetResult ( ) ;
45+ }
2546
26- public static string DefaultConnection
27- => Config [ "DefaultConnection" ] ?? DefaultConnectionString ;
47+ Thread . CurrentThread . CurrentCulture = new CultureInfo ( "en-US" ) ;
48+ }
2849
2950 private static Version ? _postgresVersion ;
3051
0 commit comments