@@ -5,8 +5,10 @@ import (
55 "database/sql"
66 "errors"
77 "fmt"
8+ "io"
89 "os"
910 "path/filepath"
11+ "strings"
1012 "testing"
1113 "time"
1214
@@ -19,6 +21,7 @@ import (
1921 "github.com/stretchr/testify/require"
2022
2123 "github.com/testcontainers/testcontainers-go"
24+ tcexec "github.com/testcontainers/testcontainers-go/exec"
2225 "github.com/testcontainers/testcontainers-go/modules/postgres"
2326 "github.com/testcontainers/testcontainers-go/wait"
2427)
@@ -288,6 +291,58 @@ func TestWithInitScript(t *testing.T) {
288291 require .NotNil (t , result )
289292}
290293
294+ func TestWithOrderedInitScript (t * testing.T ) {
295+ ctx := context .Background ()
296+
297+ ctr , err := postgres .Run (ctx ,
298+ "postgres:15.2-alpine" ,
299+ // Executes first the init-user-db shell-script, then the do-insert-user SQL script
300+ // Using WithInitScripts, this would not work as
301+ postgres .WithOrderedInitScripts (
302+ filepath .Join ("testdata" , "init-user-db.sh" ),
303+ filepath .Join ("testdata" , "aaaa-insert-user.sql" ),
304+ ),
305+ postgres .WithDatabase (dbname ),
306+ postgres .WithUsername (user ),
307+ postgres .WithPassword (password ),
308+ postgres .BasicWaitStrategies (),
309+ )
310+ testcontainers .CleanupContainer (t , ctr )
311+ require .NoError (t , err )
312+
313+ // Test that init scripts have been correctly renamed
314+ c , reader , err := ctr .Exec (ctx , []string {"ls" , "-l" , "/docker-entrypoint-initdb.d" }, tcexec .Multiplexed ())
315+ require .NoError (t , err )
316+ require .Equal (t , 0 , c , "Expected to read init scripts from the container" )
317+
318+ buf := new (strings.Builder )
319+ _ , err = io .Copy (buf , reader )
320+ require .NoError (t , err )
321+
322+ initScripts := buf .String ()
323+ strings .Contains (initScripts , "000000-init-user-db.sh" )
324+ strings .Contains (initScripts , "000001-aaaa-insert-user.sql" )
325+
326+ // explicitly set sslmode=disable because the container is not configured to use TLS
327+ connStr , err := ctr .ConnectionString (ctx , "sslmode=disable" )
328+ require .NoError (t , err )
329+
330+ db , err := sql .Open ("postgres" , connStr )
331+ require .NoError (t , err )
332+ require .NotNil (t , db )
333+ defer db .Close ()
334+
335+ // database created in init script. See testdata/init-user-db.sh
336+ rows , err := db .Query ("SELECT COUNT(*) FROM testdb;" )
337+ require .NoError (t , err )
338+ require .NotNil (t , rows )
339+ for rows .Next () {
340+ var count int
341+ rows .Scan (& count )
342+ require .Equal (t , 2 , count )
343+ }
344+ }
345+
291346func TestSnapshot (t * testing.T ) {
292347 tests := []struct {
293348 name string
0 commit comments