converge/pkg/testsupport/utils.go
Erik Brakkee d3d4c7242a restructuring test code by introducing a testsupport package
Making it easy 6to start a porof server in tests.
2024-09-08 11:16:49 +02:00

58 lines
1.1 KiB
Go

package testsupport
import (
"context"
"git.wamblee.org/converge/pkg/support/pprof"
"github.com/stretchr/testify/suite"
"log"
"net/http"
_ "runtime/pprof"
"sync"
)
type TestFunction func() any
func runAndWait(suite *suite.Suite, functions ...TestFunction) []any {
wg := sync.WaitGroup{}
wg.Add(len(functions))
res := make([]any, len(functions))
for i, function := range functions {
go func() {
defer func() {
wg.Done()
}()
res[i] = function()
}()
}
wg.Wait()
return res
}
func startPprof(port string) *http.Server {
if port == "" {
port = ":9000"
}
mux := http.NewServeMux()
pprof.RegisterPprof(mux, "/debug/pprof")
srv := http.Server{
Addr: port,
Handler: mux,
}
go func() {
if err := srv.ListenAndServe(); err != http.ErrServerClosed {
log.Fatalf("Could not start pprof listener: %v", err)
}
log.Println("Test pprof server started")
}()
return &srv
}
func stopPprof(ctx context.Context, server *http.Server) {
err := server.Shutdown(ctx)
if err != nil {
log.Println("Error shutting down test pprof server")
return
}
log.Println("Test pprof server stopped")
}