| 1 |
package test |
| 2 |
|
| 3 |
import ( |
| 4 |
"fmt" |
| 5 |
"heckel.io/ntfy/v2/server" |
| 6 |
"net" |
| 7 |
"net/http" |
| 8 |
"path/filepath" |
| 9 |
"testing" |
| 10 |
) |
| 11 |
|
| 12 |
// StartServer starts a server.Server with a random port and waits for the server to be up |
| 13 |
func StartServer(t *testing.T) (*server.Server, int) { |
| 14 |
return StartServerWithConfig(t, server.NewConfig()) |
| 15 |
} |
| 16 |
|
| 17 |
// StartServerWithConfig starts a server.Server with a random port and waits for the server to be up |
| 18 |
func StartServerWithConfig(t *testing.T, conf *server.Config) (*server.Server, int) { |
| 19 |
port := findAvailablePort(t) |
| 20 |
conf.ListenHTTP = fmt.Sprintf(":%d", port) |
| 21 |
conf.AttachmentCacheDir = t.TempDir() |
| 22 |
conf.CacheFile = filepath.Join(t.TempDir(), "cache.db") |
| 23 |
s, err := server.New(conf) |
| 24 |
if err != nil { |
| 25 |
t.Fatal(err) |
| 26 |
} |
| 27 |
go func() { |
| 28 |
if err := s.Run(); err != nil && err != http.ErrServerClosed { |
| 29 |
panic(err) // 'go vet' complains about 't.Fatal(err)' |
| 30 |
} |
| 31 |
}() |
| 32 |
WaitForPortUp(t, port) |
| 33 |
return s, port |
| 34 |
} |
| 35 |
|
| 36 |
// findAvailablePort asks the OS for a free port by binding to :0 |
| 37 |
func findAvailablePort(t *testing.T) int { |
| 38 |
listener, err := net.Listen("tcp", ":0") |
| 39 |
if err != nil { |
| 40 |
t.Fatal(err) |
| 41 |
} |
| 42 |
port := listener.Addr().(*net.TCPAddr).Port |
| 43 |
listener.Close() |
| 44 |
return port |
| 45 |
} |
| 46 |
|
| 47 |
// StopServer stops the test server and waits for the port to be down |
| 48 |
func StopServer(t *testing.T, s *server.Server, port int) { |
| 49 |
s.Stop() |
| 50 |
WaitForPortDown(t, port) |
| 51 |
} |