Tests for cliet package

This commit is contained in:
Philipp Heckel 2021-12-22 23:20:43 +01:00
parent 6a7e9071b6
commit fe5734d9f0
8 changed files with 162 additions and 43 deletions

38
test/server.go Normal file
View file

@ -0,0 +1,38 @@
package test
import (
"fmt"
"heckel.io/ntfy/server"
"math/rand"
"net/http"
"testing"
"time"
)
func init() {
rand.Seed(time.Now().Unix())
}
// StartServer starts a server.Server with a random port and waits for the server to be up
func StartServer(t *testing.T) (*server.Server, int) {
port := 10000 + rand.Intn(20000)
conf := server.NewConfig()
conf.ListenHTTP = fmt.Sprintf(":%d", port)
s, err := server.New(conf)
if err != nil {
t.Fatal(err)
}
go func() {
if err := s.Run(); err != nil && err != http.ErrServerClosed {
panic(err) // 'go vet' complains about 't.Fatal(err)'
}
}()
WaitForPortUp(t, port)
return s, port
}
// StopServer stops the test server and waits for the port to be down
func StopServer(t *testing.T, s *server.Server, port int) {
s.Stop()
WaitForPortDown(t, port)
}

3
test/test.go Normal file
View file

@ -0,0 +1,3 @@
// Package test provides test helpers for unit and integration tests.
// This code is not meant to be used outside of tests.
package test

44
test/util.go Normal file
View file

@ -0,0 +1,44 @@
package test
import (
"net"
"strconv"
"testing"
"time"
)
// WaitForPortUp waits up to 7s for a port to come up and fails t if that fails
func WaitForPortUp(t *testing.T, port int) {
success := false
for i := 0; i < 500; i++ {
startTime := time.Now()
conn, _ := net.DialTimeout("tcp", net.JoinHostPort("127.0.0.1", strconv.Itoa(port)), 10*time.Millisecond)
if conn != nil {
success = true
conn.Close()
break
}
if time.Since(startTime) < 10*time.Millisecond {
time.Sleep(10*time.Millisecond - time.Since(startTime))
}
}
if !success {
t.Fatalf("Failed waiting for port %d to be UP", port)
}
}
// WaitForPortDown waits up to 5s for a port to come down and fails t if that fails
func WaitForPortDown(t *testing.T, port int) {
success := false
for i := 0; i < 100; i++ {
conn, _ := net.DialTimeout("tcp", net.JoinHostPort("", strconv.Itoa(port)), 50*time.Millisecond)
if conn == nil {
success = true
break
}
conn.Close()
}
if !success {
t.Fatalf("Failed waiting for port %d to be DOWN", port)
}
}