-
-
Notifications
You must be signed in to change notification settings - Fork 121
/
examples_test.go
94 lines (80 loc) · 2.09 KB
/
examples_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
//go:build unix
package statsviz_test
import (
"bytes"
"context"
"crypto/tls"
"io"
"net/http"
"os"
"testing"
"time"
"github.com/rogpeppe/go-internal/gotooltest"
"github.com/rogpeppe/go-internal/testscript"
)
func TestExamples(t *testing.T) {
if testing.Short() {
t.Skipf("TestExamples skipped in short mode")
}
p := testscript.Params{
Dir: "testdata",
Setup: func(env *testscript.Env) error {
// We want to run scripts with the local version of Statsviz.
// Provide scripts with statsviz root dir so we can use a
// 'go mod -edit replace' directive.
wd, err := os.Getwd()
if err != nil {
return err
}
env.Setenv("STATSVIZ_ROOT", wd)
return nil
},
Cmds: map[string]func(ts *testscript.TestScript, neg bool, args []string){
"checkui": checkui,
},
}
if err := gotooltest.Setup(&p); err != nil {
t.Fatal(err)
}
testscript.Run(t, p)
}
// checkui requests statsviz url from a script.
// In a script, run it with:
//
// checkui url [basic_auth_user basic_auth_pwd]
func checkui(ts *testscript.TestScript, neg bool, args []string) {
if len(args) != 1 && len(args) != 3 {
ts.Fatalf(`checkui: wrong number of arguments. Call with "checkui URL [BASIC_USER BASIC_PWD]`)
}
u := args[0]
ts.Logf("checkui: loading web page %s", args[0])
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
if err != nil {
ts.Fatalf("checkui: bad request: %v", err)
}
if len(args) == 3 {
ts.Logf("checkui: setting basic auth")
req.SetBasicAuth(args[1], args[2])
}
client := http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
},
},
Timeout: 5 * time.Second,
}
// Let 1 second for the server to start and listen.
time.Sleep(1 * time.Second)
resp, err := client.Do(req)
ts.Check(err)
body, err := io.ReadAll(resp.Body)
defer resp.Body.Close()
ts.Check(err)
want := []byte(`id="plots"`)
if !bytes.Contains(body, want) {
ts.Fatalf("checkui: response body doesn't contain %s\n\nbody;\n\n%s", want, body)
}
}