Debian Codegraph @

tools/tester/main.go

raw symbols SCIP
1 // Command tester automates the ability to download a suite of JavaScript libraries from a CDN and check if otto can handle them.
2 //
3 // It provides two commands via flags:
4 // * -fetch = Fetch all libraries from the CDN and store them in local testdata directory.
5 // * -report [file1 file2 ... fileN] = Report the results of trying to run the given or if empty all libraries in the testdata directory.
6 package main
7
8 import (
9 "context"
10 "encoding/json"
11 "errors"
12 "flag"
13 "fmt"
14 "io"
15 "io/fs"
16 "net/http"
17 "os"
18 "path/filepath"
19 "regexp"
20 "runtime"
21 "strings"
22 "sync"
23 "text/tabwriter"
24 "time"
25
26 "github.com/robertkrimen/otto"
27 "github.com/robertkrimen/otto/parser"
28 )
29
30 const (
31 // dataDir is where the libraries are downloaded to.
32 dataDir = "testdata"
33
34 // downloadWorkers is the number of workers that process downloads.
35 downloadWorkers = 40
36
37 // librariesURL is the source for JavaScript libraries for testing.
38 librariesURL = "http://api.cdnjs.com/libraries"
39
40 // requestTimeout is the maximum time we wait for a request to complete.
41 requestTimeout = time.Second * 20
42 )
43
44 var (
45 // testWorkers is the number of workers that process report.
46 testWorkers = min(10, runtime.GOMAXPROCS(0))
47
48 // noopConsole is a noopConsole which ignore log requests.
49 noopConsole = map[string]interface{}{
50 "log": func(call otto.FunctionCall) otto.Value {
51 return otto.UndefinedValue()
52 },
53 }
54 )
55
56 var (
57 matchReferenceErrorNotDefined = regexp.MustCompile(`^ReferenceError: \S+ is not defined$`)
58 matchLookahead = regexp.MustCompile(`Invalid regular expression: re2: Invalid \(\?[=!]\) <lookahead>`)
59 matchBackReference = regexp.MustCompile(`Invalid regular expression: re2: Invalid \\\d <backreference>`)
60 matchTypeErrorUndefined = regexp.MustCompile(`^TypeError: Cannot access member '[^']+' of undefined$`)
61 )
62
63 // broken identifies libraries which fail with a fatal error, so must be skipped.
64 var broken = map[string]string{
65 "lets-plot.js": "stack overflow",
66 "knockout-es5.js": "stack overflow",
67 "sendbird-calls.js": "runtime: out of memory",
68 }
69
70 // libraries represents fetch all libraries response.
71 type libraries struct {
72 Results []library `json:"results"`
73 }
74
75 // library represents a single library in a libraries response.
76 type library struct {
77 Name string `json:"name"`
78 Latest string `json:"latest"`
79 }
80
81 // fetch fetches itself and stores it in the dataDir.
82 func (l library) fetch() error {
83 if !strings.HasSuffix(l.Latest, ".js") {
84 return nil
85 }
86
87 ctx, cancel := context.WithTimeout(context.Background(), requestTimeout)
88 defer cancel()
89
90 req, err := http.NewRequestWithContext(ctx, http.MethodGet, l.Latest, nil)
91 if err != nil {
92 return fmt.Errorf("request library %q: %w", l.Name, err)
93 }
94
95 resp, err := http.DefaultClient.Do(req)
96 if err != nil {
97 return fmt.Errorf("get library %q: %w", l.Name, err)
98 }
99 defer resp.Body.Close() //nolint:errcheck
100
101 name := l.Name
102 if !strings.HasSuffix(name, ".js") {
103 name += ".js"
104 }
105
106 f, err := os.Create(filepath.Join(dataDir, name)) //nolint:gosec
107 if err != nil {
108 return fmt.Errorf("create library %q: %w", l.Name, err)
109 }
110
111 if _, err = io.Copy(f, resp.Body); err != nil {
112 return fmt.Errorf("write library %q: %w", l.Name, err)
113 }
114
115 return nil
116 }
117
118 // test runs the code from filename returning the time it took and any error
119 // encountered when running a full parse without IgnoreRegExpErrors in parseError.
120 func test(filename string) (took time.Duration, parseError, err error) { //nolint:nonamedreturns
121 defer func() {
122 if r := recover(); r != nil {
123 err = fmt.Errorf("panic on %q: %v", filename, r)
124 }
125 }()
126 now := time.Now()
127 defer func() {
128 // Always set took.
129 took = time.Since(now)
130 }()
131
132 if val := broken[filepath.Base(filename)]; val != "" {
133 return 0, nil, fmt.Errorf("fatal %q", val)
134 }
135
136 script, err := os.ReadFile(filename) //nolint:gosec
137 if err != nil {
138 return 0, nil, err
139 }
140
141 vm := otto.New()
142 if err = vm.Set("console", noopConsole); err != nil {
143 return 0, nil, fmt.Errorf("set console: %w", err)
144 }
145
146 prog, err := parser.ParseFile(nil, filename, string(script), 0)
147 if err != nil {
148 val := err.Error()
149 switch {
150 case matchReferenceErrorNotDefined.MatchString(val),
151 matchTypeErrorUndefined.MatchString(val),
152 matchLookahead.MatchString(val),
153 matchBackReference.MatchString(val):
154 // RegExp issues, retry with IgnoreRegExpErrors.
155 parseError = err
156 if _, err = parser.ParseFile(nil, filename, string(script), parser.IgnoreRegExpErrors); err != nil {
157 return 0, nil, err
158 }
159 return 0, parseError, nil
160 default:
161 return 0, nil, err
162 }
163 }
164
165 _, err = vm.Run(prog)
166 return 0, nil, err
167 }
168
169 // fetchAll fetches all files from src.
170 func fetchAll(src string) error {
171 ctx, cancel := context.WithTimeout(context.Background(), requestTimeout)
172 defer cancel()
173
174 req, err := http.NewRequestWithContext(ctx, http.MethodGet, librariesURL, nil)
175 if err != nil {
176 return fmt.Errorf("request libraries %q: %w", src, err)
177 }
178
179 resp, err := http.DefaultClient.Do(req)
180 if err != nil {
181 return fmt.Errorf("get libraries %q: %w", src, err)
182 }
183 defer resp.Body.Close() //nolint:errcheck
184
185 var libs libraries
186 dec := json.NewDecoder(resp.Body)
187 if err = dec.Decode(&libs); err != nil {
188 return fmt.Errorf("json decode: %w", err)
189 }
190
191 if err = os.Mkdir(dataDir, 0o750); err != nil && !errors.Is(err, fs.ErrExist) {
192 return fmt.Errorf("mkdir: %w", err)
193 }
194
195 var wg sync.WaitGroup
196 work := make(chan library, downloadWorkers)
197 errs := make(chan error, len(libs.Results))
198 wg.Add(downloadWorkers)
199 for range downloadWorkers {
200 go func() {
201 defer wg.Done()
202 for lib := range work {
203 fmt.Fprint(os.Stdout, ".")
204 errs <- lib.fetch()
205 }
206 }()
207 }
208
209 fmt.Fprintf(os.Stdout, "Downloading %d libraries with %d workers ...", len(libs.Results), downloadWorkers)
210 wg.Add(1)
211 go func() {
212 defer wg.Done()
213 for _, lib := range libs.Results {
214 work <- lib
215 }
216 close(work)
217 }()
218
219 wg.Wait()
220 close(errs)
221 fmt.Fprintln(os.Stdout, " done")
222
223 for e := range errs {
224 if e != nil {
225 fmt.Fprintln(os.Stderr, e)
226 err = e
227 }
228 }
229
230 return err
231 }
232
233 // result represents the result from a test.
234 type result struct {
235 err error
236 parseError error
237 filename string
238 took time.Duration
239 }
240
241 // report runs test for all specified files, if none a specified all
242 // JavaScript files in our dataDir, outputting the results.
243 func report(files []string) error {
244 if len(files) == 0 {
245 var err error
246 files, err = filepath.Glob(filepath.Join(dataDir, "*.js"))
247 if err != nil {
248 return fmt.Errorf("read dir: %w", err)
249 }
250 }
251
252 var wg sync.WaitGroup
253 workers := min(testWorkers, len(files))
254 work := make(chan string, workers)
255 results := make(chan result, len(files))
256 wg.Add(workers)
257 for range workers {
258 go func() {
259 defer wg.Done()
260 for f := range work {
261 fmt.Fprint(os.Stdout, ".")
262 took, parseError, err := test(f)
263 results <- result{
264 filename: f,
265 err: err,
266 parseError: parseError,
267 took: took,
268 }
269 }
270 }()
271 }
272
273 fmt.Fprintf(os.Stdout, "Reporting on %d libs with %d workers...", len(files), workers)
274 wg.Add(1)
275 go func() {
276 defer wg.Done()
277 for _, f := range files {
278 work <- f
279 }
280 close(work)
281 }()
282
283 wg.Wait()
284 close(results)
285 fmt.Fprintln(os.Stdout, " done")
286
287 var fail, pass, parse int
288 writer := tabwriter.NewWriter(os.Stdout, 0, 8, 0, '\t', 0)
289 fmt.Fprintln(writer, "Library", "\t| Took", "\t| Status")
290 fmt.Fprintln(writer, "-------", "\t| ----", "\t| ------")
291
292 for res := range results {
293 switch {
294 case res.err != nil:
295 fmt.Fprintf(writer, "%s\t| %v\t| fail: %v\n", res.filename, res.took, res.err)
296 fail++
297 case res.parseError != nil:
298 fmt.Fprintf(writer, "%s\t| %v\t| pass parse: %v\n", res.filename, res.took, res.parseError)
299 parse++
300 default:
301 fmt.Fprintf(writer, "%s\t| %v\t| pass\n", res.filename, res.took)
302 pass++
303 }
304 }
305
306 if err := writer.Flush(); err != nil {
307 return fmt.Errorf("flush: %w", err)
308 }
309
310 fmt.Fprintf(os.Stdout, "\nSummary:\n - %d passes\n - %d parse passes\n - %d fails\n", pass, parse, fail)
311
312 return nil
313 }
314
315 func main() {
316 flagFetch := flag.Bool("fetch", false, "fetch all libraries for testing")
317 flagReport := flag.Bool("report", false, "test and report the named files or all libraries if non specified")
318 flag.Parse()
319
320 var err error
321 switch {
322 case *flagFetch:
323 err = fetchAll(librariesURL)
324 case *flagReport:
325 err = report(flag.Args())
326 default:
327 flag.PrintDefaults()
328 err = errors.New("missing flag")
329 }
330 if err != nil {
331 fmt.Fprintln(os.Stderr, err)
332 os.Exit(64)
333 }
334 }