97 lines
2.1 KiB
Go
97 lines
2.1 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"io"
|
|
"log/slog"
|
|
"net"
|
|
"os"
|
|
"testing"
|
|
"time"
|
|
|
|
"messenger/internal/platform/config"
|
|
"messenger/internal/testenv"
|
|
)
|
|
|
|
var (
|
|
db *testenv.DB
|
|
kv *testenv.KV
|
|
)
|
|
|
|
func TestMain(m *testing.M) {
|
|
ctx := context.Background()
|
|
var err error
|
|
if db, err = testenv.StartPostgres(ctx); err != nil {
|
|
fmt.Fprintln(os.Stderr, err)
|
|
os.Exit(1)
|
|
}
|
|
if kv, err = testenv.StartValkey(ctx); err != nil {
|
|
db.Close()
|
|
fmt.Fprintln(os.Stderr, err)
|
|
os.Exit(1)
|
|
}
|
|
code := m.Run()
|
|
kv.Close()
|
|
db.Close()
|
|
os.Exit(code)
|
|
}
|
|
|
|
// A start-up failure after the background work began must still end the
|
|
// process with an error, not leave it waiting for a signal.
|
|
func TestRunFailsFastWhenTheDebugListenerCannotStart(t *testing.T) {
|
|
if err := runWithBusyDebugAddr(t, 0); err == nil {
|
|
t.Fatal("run succeeded on a busy debug address")
|
|
}
|
|
}
|
|
|
|
func TestFailedStartReleasesTheAPIPort(t *testing.T) {
|
|
probe, err := net.Listen("tcp", "127.0.0.1:0")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
port := probe.Addr().(*net.TCPAddr).Port
|
|
probe.Close()
|
|
|
|
if err := runWithBusyDebugAddr(t, port); err == nil {
|
|
t.Fatal("run succeeded on a busy debug address")
|
|
}
|
|
ln, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", port))
|
|
if err != nil {
|
|
t.Fatalf("the API port is still taken after the failed start: %v", err)
|
|
}
|
|
ln.Close()
|
|
}
|
|
|
|
func runWithBusyDebugAddr(t *testing.T, port int) error {
|
|
t.Helper()
|
|
busy, err := net.Listen("tcp", "127.0.0.1:0")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer busy.Close()
|
|
cfg := config.Config{
|
|
Host: "127.0.0.1",
|
|
Port: port,
|
|
ShutdownTimeout: time.Second,
|
|
MaxBodyBytes: 1024,
|
|
DatabaseURL: db.DSN,
|
|
SessionStoreURL: kv.URL,
|
|
SessionTTL: time.Hour,
|
|
IdempotencyTTL: time.Hour,
|
|
DBMaxConns: 2,
|
|
DebugAddr: busy.Addr().String(),
|
|
}
|
|
done := make(chan error, 1)
|
|
go func() {
|
|
done <- run(context.Background(), slog.New(slog.NewTextHandler(io.Discard, nil)), cfg, "alias")
|
|
}()
|
|
select {
|
|
case err := <-done:
|
|
return err
|
|
case <-time.After(10 * time.Second):
|
|
t.Fatal("run hung instead of returning the listen error")
|
|
return nil
|
|
}
|
|
}
|