server.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package test
  2. import (
  3. "fmt"
  4. "heckel.io/ntfy/server"
  5. "math/rand"
  6. "net/http"
  7. "path/filepath"
  8. "testing"
  9. "time"
  10. )
  11. func init() {
  12. rand.Seed(time.Now().UnixMilli())
  13. }
  14. // StartServer starts a server.Server with a random port and waits for the server to be up
  15. func StartServer(t *testing.T) (*server.Server, int) {
  16. return StartServerWithConfig(t, server.NewConfig())
  17. }
  18. // StartServerWithConfig starts a server.Server with a random port and waits for the server to be up
  19. func StartServerWithConfig(t *testing.T, conf *server.Config) (*server.Server, int) {
  20. port := 10000 + rand.Intn(20000)
  21. conf.ListenHTTP = fmt.Sprintf(":%d", port)
  22. conf.AttachmentCacheDir = t.TempDir()
  23. conf.CacheFile = filepath.Join(t.TempDir(), "cache.db")
  24. s, err := server.New(conf)
  25. if err != nil {
  26. t.Fatal(err)
  27. }
  28. go func() {
  29. if err := s.Run(); err != nil && err != http.ErrServerClosed {
  30. panic(err) // 'go vet' complains about 't.Fatal(err)'
  31. }
  32. }()
  33. WaitForPortUp(t, port)
  34. return s, port
  35. }
  36. // StopServer stops the test server and waits for the port to be down
  37. func StopServer(t *testing.T, s *server.Server, port int) {
  38. s.Stop()
  39. WaitForPortDown(t, port)
  40. }