-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain_test.go
More file actions
81 lines (71 loc) · 1.68 KB
/
main_test.go
File metadata and controls
81 lines (71 loc) · 1.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package main
import (
"fmt"
"io"
"math/rand"
"net"
"net/http"
"os"
"strconv"
"syscall"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func Test_Main(t *testing.T) {
if _, ok := os.LookupEnv("ENABLE_MONGO_TESTS"); !ok {
t.Skip("ENABLE_MONGO_TESTS env variable is not set")
}
port := chooseRandomUnusedPort()
os.Args = []string{"test", "--port=" + strconv.Itoa(port), "--dbg",
"--mongo-uri=mongodb://localhost:27017/",
"--mongo-db=test_ureadability",
"--frontend-dir=web",
}
done := make(chan struct{})
go func() {
<-done
e := syscall.Kill(syscall.Getpid(), syscall.SIGTERM)
assert.NoError(t, e)
}()
finished := make(chan struct{})
go func() {
main()
close(finished)
}()
// defer cleanup because assert check below can fail
defer func() {
close(done)
<-finished
}()
waitForHTTPServerStart(port)
resp, err := http.Get(fmt.Sprintf("http://localhost:%d/api/ping", port))
require.NoError(t, err)
defer resp.Body.Close()
assert.Equal(t, 200, resp.StatusCode)
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
assert.Equal(t, "pong", string(body))
}
func chooseRandomUnusedPort() (port int) {
for range 10 {
port = 40000 + int(rand.Int31n(10000))
if ln, err := net.Listen("tcp", fmt.Sprintf(":%d", port)); err == nil {
_ = ln.Close()
break
}
}
return port
}
func waitForHTTPServerStart(port int) {
// wait for up to 10 seconds for server to start before returning it
client := http.Client{Timeout: time.Second}
for range 100 {
time.Sleep(time.Millisecond * 100)
if resp, err := client.Get(fmt.Sprintf("http://localhost:%d", port)); err == nil {
_ = resp.Body.Close()
return
}
}
}