-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain_test.go
96 lines (85 loc) · 1.96 KB
/
main_test.go
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/*
* Author: Markus Stenberg <[email protected]>
*
* Copyright (c) 2024 Markus Stenberg
*
* Created: Thu May 16 07:24:25 2024 mstenber
* Last modified: Thu Oct 31 08:01:52 2024 mstenber
* Edit time: 33 min
*
*/
package main
import (
"context"
"errors"
"fmt"
"log"
"log/slog"
"net/http"
"strconv"
"testing"
"time"
"gotest.tools/v3/assert"
)
func retrieveURL(ctx context.Context, url string) (*http.Response, error) {
client := http.Client{}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return nil, fmt.Errorf("failed to create http request: %w", err)
}
return client.Do(req)
}
func waitForURL(ctx context.Context, url string) error {
for {
resp, err := retrieveURL(ctx, url)
if err != nil {
if errors.Is(err, context.DeadlineExceeded) {
return err
}
slog.Error("Error making request", "err", err)
continue
}
resp.Body.Close()
if resp.StatusCode == http.StatusOK {
return nil
}
select {
case <-ctx.Done():
return ctx.Err()
default:
time.Sleep(100 * time.Millisecond)
}
}
}
func TestMain(t *testing.T) {
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
t.Cleanup(cancel)
port := 18080
go func() {
err := run(ctx, []string{"lixie", "-port", strconv.Itoa(port), "-db", "testdata/db.json", "-log-source-file", "testdata/logs.json"})
if err != nil {
log.Panic(err)
}
}()
ctx2, cancel2 := context.WithTimeout(ctx, 1*time.Second)
t.Cleanup(cancel2)
baseURL := fmt.Sprintf("http://localhost:%d", port)
err := waitForURL(ctx2, baseURL)
if err != nil {
log.Panic(err)
}
t.Parallel()
for _, tli := range topLevelInfos {
t.Run(tli.Title, func(t *testing.T) {
ctx3, cancel3 := context.WithTimeout(ctx, 1*time.Second)
t.Cleanup(cancel3)
resp, err := retrieveURL(ctx3, fmt.Sprintf("%s%s", baseURL, tli.Path))
if err != nil {
log.Panic(err)
}
resp.Body.Close()
assert.Equal(t, resp.StatusCode, http.StatusOK)
})
}
}