-
Notifications
You must be signed in to change notification settings - Fork 54
/
Copy pathmain_test.go
106 lines (90 loc) · 2.29 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
97
98
99
100
101
102
103
104
105
106
package main
import (
"bytes"
"context"
"encoding/json"
"net/http"
"net/url"
"strings"
"syscall"
"testing"
"github.com/ooni/probe-cli/v3/internal/model"
"github.com/ooni/probe-cli/v3/internal/netxlite"
"github.com/ooni/probe-cli/v3/internal/runtimex"
)
type (
ctrlRequest = model.THRequest
ctrlResponse = model.THResponse
)
func TestMainRunServerWorkingAsIntended(t *testing.T) {
if testing.Short() {
t.Skip("skip test in short mode")
}
// let the kernel pick a random free port
*apiEndpoint = "127.0.0.1:0"
// run the main function in a background goroutine
go main()
// prepare the HTTP request body
jsonReq := ctrlRequest{
HTTPRequest: "https://dns.google",
HTTPRequestHeaders: map[string][]string{
"Accept": {model.HTTPHeaderAccept},
"Accept-Language": {model.HTTPHeaderAcceptLanguage},
"User-Agent": {model.HTTPHeaderUserAgent},
},
TCPConnect: []string{
"8.8.8.8:443",
"8.8.4.4:443",
},
}
data, err := json.Marshal(jsonReq)
runtimex.PanicOnError(err, "cannot marshal request")
// construct the test helper's URL
endpoint := <-srvAddr
URL := &url.URL{
Scheme: "http",
Host: endpoint,
Path: "/",
}
req, err := http.NewRequest("POST", URL.String(), bytes.NewReader(data))
runtimex.PanicOnError(err, "cannot create new HTTP request")
// issue the request and get the response
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
t.Fatal("unexpected status code", resp.StatusCode)
}
// read the response body
data, err = netxlite.ReadAllContext(context.Background(), resp.Body)
if err != nil {
t.Fatal(err)
}
// parse the response
var jsonResp ctrlResponse
if err := json.Unmarshal(data, &jsonResp); err != nil {
t.Fatal(err)
}
// very simple correctness check
if !strings.Contains(jsonResp.HTTPRequest.Title, "Google") {
t.Fatal("expected the response title to contain the string Google")
}
// tear down the TH
sigs <- syscall.SIGINT
// wait for the background goroutine to join
srvWg.Wait()
}
func TestMainReplaceWorkingAsIntended(t *testing.T) {
replaceDryRun = true
*replace = true
main()
*replace = false
replaceDryRun = false
}
func TestMainVersionWorkingAsIntended(t *testing.T) {
*versionFlag = true
main()
*versionFlag = false
}