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,23 @@ 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+ ConnectionString = connectionString ;
30+ }
31+ else
32+ {
33+ _postgreSqlContainer = new PostgreSqlBuilder ( "postgis/postgis:latest" )
34+ . Build ( ) ;
35+ _postgreSqlContainer . StartAsync ( ) . GetAwaiter ( ) . GetResult ( ) ;
36+ ConnectionString = _postgreSqlContainer . GetConnectionString ( ) ;
2337
24- private const string DefaultConnectionString = "Server=localhost;Username=npgsql_tests;Password=npgsql_tests;Port=5432" ;
38+ AppDomain . CurrentDomain . ProcessExit += ( _ , _ ) =>
39+ _postgreSqlContainer . DisposeAsync ( ) . AsTask ( ) . GetAwaiter ( ) . GetResult ( ) ;
40+ }
2541
26- public static string DefaultConnection
27- => Config [ "DefaultConnection" ] ?? DefaultConnectionString ;
42+ Thread . CurrentThread . CurrentCulture = new CultureInfo ( "en-US" ) ;
43+ }
2844
2945 private static Version ? _postgresVersion ;
3046
0 commit comments