package main import ( "errors" "os" "path/filepath" "strings" "testing" "github.com/phishingclub/phishingclub/database" "github.com/phishingclub/phishingclub/testdb" ) // TestAcquireLockForRun checks which one shot commands run while a server // holds the instance lock: recovery runs next to it, a named migration and a // second server are refused func TestAcquireLockForRun(t *testing.T) { db, err := testdb.Open(t, filepath.Join(t.TempDir(), "lock.db")) if err != nil { t.Fatalf("open: %v", err) } server, mode, err := acquireLockForRun(db, false, "") if err != nil || mode != lockHeld { t.Fatalf("server: %v %v", mode, err) } defer func() { _ = server.Release() }() if !testdb.IsPostgres() { // sqlite has no lock, every command runs as before for _, c := range []struct { recovery bool migration string }{{false, ""}, {true, ""}, {false, "lowercase-recipient-emails"}} { if _, mode, err := acquireLockForRun(db, c.recovery, c.migration); err != nil || mode != lockHeld { t.Fatalf("sqlite %+v: %v %v", c, mode, err) } } return } // another connection of the pool is another session, like another process if _, _, err := acquireLockForRun(db, false, ""); !errors.Is(err, database.ErrOtherInstanceRunning) { t.Fatalf("second server: want ErrOtherInstanceRunning, got %v", err) } lock, mode, err := acquireLockForRun(db, true, "") if err != nil || mode != lockNextToServer || lock != nil { t.Fatalf("recovery: %v %v %v", lock, mode, err) } _, _, err = acquireLockForRun(db, false, "lowercase-recipient-emails") if !errors.Is(err, database.ErrOtherInstanceRunning) || !strings.Contains(err.Error(), "stop the server first") { t.Fatalf("migration: %v", err) } // with the server stopped, recovery and the migration take the lock if err := server.Release(); err != nil { t.Fatal(err) } for _, migration := range []string{"", "lowercase-recipient-emails"} { lock, mode, err := acquireLockForRun(db, migration == "", migration) if err != nil || mode != lockHeld { t.Fatalf("stopped server %q: %v %v", migration, mode, err) } if err := lock.Release(); err != nil { t.Fatal(err) } } } // TestMainIsTheOnlySourceFile fails when package main has a source file // other than main.go. The dev build (.air.docker.toml), build_scripts/build.sh // and the release and test build workflows run "go build ... main.go", which // compiles main.go alone: code in another file of package main is missing // from those builds and they fail with undefined names, while go test still // passes as it compiles the whole package. Put such code in its own package. func TestMainIsTheOnlySourceFile(t *testing.T) { entries, err := os.ReadDir(".") if err != nil { t.Fatal(err) } for _, e := range entries { name := e.Name() if e.IsDir() || !strings.HasSuffix(name, ".go") || strings.HasSuffix(name, "_test.go") || name == "main.go" { continue } t.Errorf("%s is in package main next to main.go; the builds compile main.go only, move its code to another package", name) } }