-
Notifications
You must be signed in to change notification settings - Fork 22
/
main.go
228 lines (207 loc) · 5.65 KB
/
main.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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
package main
import (
"bytes"
"context"
"errors"
"flag"
"fmt"
"io"
"log"
"os"
"os/signal"
"path"
"runtime"
"strconv"
"strings"
"github.com/chromedp/cdproto/inspector"
"github.com/chromedp/cdproto/profiler"
cdpruntime "github.com/chromedp/cdproto/runtime"
"github.com/chromedp/cdproto/target"
"github.com/chromedp/chromedp"
)
func main() {
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt)
defer cancel()
err := run(ctx, os.Args, os.Stderr, flag.CommandLine)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
func run(ctx context.Context, args []string, errOutput io.Writer, flagSet *flag.FlagSet) (returnedErr error) {
logger := log.New(errOutput, "[wasmbrowsertest]: ", log.LstdFlags|log.Lshortfile)
defer func() {
r := recover()
if r != nil {
returnedErr = fmt.Errorf("Panicked: %+v", r)
}
}()
if len(args) < 2 {
return errors.New("Please pass a wasm file as a parameter")
}
cpuProfile := flagSet.String("test.cpuprofile", "", "")
coverageProfile := flagSet.String("test.coverprofile", "", "")
wasmFile := args[1]
ext := path.Ext(wasmFile)
// net/http code does not take js/wasm path if it is a .test binary.
if ext == ".test" {
wasmFile = strings.Replace(wasmFile, ext, ".wasm", -1)
err := copyFile(args[1], wasmFile)
if err != nil {
return err
}
defer os.Remove(wasmFile)
args[1] = wasmFile
}
passon, err := gentleParse(flagSet, args[2:])
if err != nil {
return err
}
passon = append([]string{wasmFile}, passon...)
if *coverageProfile != "" {
passon = append(passon, "-test.coverprofile="+*coverageProfile)
}
// Setup web server.
handler, err := NewWASMServer(wasmFile, passon, *coverageProfile, logger)
if err != nil {
return err
}
url, shutdownHTTPServer, err := startHTTPServer(ctx, handler, logger)
if err != nil {
return err
}
defer shutdownHTTPServer()
opts := chromedp.DefaultExecAllocatorOptions[:]
if os.Getenv("WASM_HEADLESS") == "off" {
opts = append(opts,
chromedp.Flag("headless", false),
)
}
// WSL needs the GPU disabled. See issue #10
if runtime.GOOS == "linux" && isWSL() {
opts = append(opts,
chromedp.DisableGPU,
)
}
// create chrome instance
allocCtx, cancelAllocCtx := chromedp.NewExecAllocator(ctx, opts...)
defer cancelAllocCtx()
ctx, cancelCtx := chromedp.NewContext(allocCtx)
defer cancelCtx()
chromedp.ListenTarget(ctx, func(ev interface{}) {
handleEvent(ctx, ev, logger)
})
var exitCode int
tasks := []chromedp.Action{
chromedp.Navigate(url),
chromedp.WaitEnabled(`#doneButton`),
chromedp.Evaluate(`exitCode;`, &exitCode),
}
if *cpuProfile != "" {
// Prepend and append profiling tasks
tasks = append([]chromedp.Action{
profiler.Enable(),
profiler.Start(),
}, tasks...)
tasks = append(tasks, chromedp.ActionFunc(func(ctx context.Context) error {
profile, err := profiler.Stop().Do(ctx)
if err != nil {
return err
}
outF, err := os.Create(*cpuProfile)
if err != nil {
return err
}
defer func() {
err = outF.Close()
if err != nil {
logger.Println(err)
}
}()
funcMap, err := getFuncMap(wasmFile)
if err != nil {
return err
}
return WriteProfile(profile, outF, funcMap)
}))
}
err = chromedp.Run(ctx, tasks...)
if err != nil {
// Browser did not exit cleanly. Likely failed with an uncaught error.
return err
}
if exitCode != 0 {
return fmt.Errorf("exit with status %d", exitCode)
}
return nil
}
func copyFile(src, dst string) error {
srdFd, err := os.Open(src)
if err != nil {
return fmt.Errorf("error in copying %s to %s: %v", src, dst, err)
}
defer srdFd.Close()
dstFd, err := os.Create(dst)
if err != nil {
return fmt.Errorf("error in copying %s to %s: %v", src, dst, err)
}
defer dstFd.Close()
_, err = io.Copy(dstFd, srdFd)
if err != nil {
return fmt.Errorf("error in copying %s to %s: %v", src, dst, err)
}
return nil
}
// handleEvent responds to different events from the browser and takes
// appropriate action.
func handleEvent(ctx context.Context, ev interface{}, logger *log.Logger) {
switch ev := ev.(type) {
case *cdpruntime.EventConsoleAPICalled:
for _, arg := range ev.Args {
line := string(arg.Value)
if line == "" { // If Value is not found, look for Description.
line = arg.Description
}
// Any string content is quoted with double-quotes.
// So need to treat it specially.
s, err := strconv.Unquote(line)
if err != nil {
// Probably some numeric content, print it as is.
fmt.Printf("%s\n", line)
continue
}
fmt.Printf("%s\n", s)
}
case *cdpruntime.EventExceptionThrown:
if ev.ExceptionDetails != nil {
details := ev.ExceptionDetails
fmt.Printf("%s:%d:%d %s\n", details.URL, details.LineNumber, details.ColumnNumber, details.Text)
if details.Exception != nil {
fmt.Printf("%s\n", details.Exception.Description)
}
}
case *target.EventTargetCrashed:
fmt.Printf("target crashed: status: %s, error code:%d\n", ev.Status, ev.ErrorCode)
err := chromedp.Cancel(ctx)
if err != nil {
logger.Printf("error in cancelling context: %v\n", err)
}
case *inspector.EventDetached:
fmt.Println("inspector detached: ", ev.Reason)
err := chromedp.Cancel(ctx)
if err != nil {
logger.Printf("error in cancelling context: %v\n", err)
}
}
}
// isWSL returns true if the OS is WSL, false otherwise.
// This method of checking for WSL has worked since mid 2016:
// https://github.com/microsoft/WSL/issues/423#issuecomment-328526847
func isWSL() bool {
buf, err := os.ReadFile("/proc/sys/kernel/osrelease")
if err != nil {
return false
}
// if there was an error opening the file it must not be WSL, so ignore the error
return bytes.Contains(buf, []byte("Microsoft"))
}