Debian Codegraph @

compiler/natives/src/testing/example.go

raw
1 // +build js
2
3 package testing
4
5 import (
6 "fmt"
7 "os"
8 "strings"
9 "time"
10 )
11
12 func runExample(eg InternalExample) (ok bool) {
13 if *chatty {
14 fmt.Printf("=== RUN %s\n", eg.Name)
15 }
16
17 // Capture stdout.
18 stdout := os.Stdout
19 w, err := tempFile("." + eg.Name + ".stdout.")
20 if err != nil {
21 fmt.Fprintln(os.Stderr, err)
22 os.Exit(1)
23 }
24 os.Stdout = w
25
26 start := time.Now()
27 ok = true
28
29 // Clean up in a deferred call so we can recover if the example panics.
30 defer func() {
31 dstr := fmtDuration(time.Now().Sub(start))
32
33 // Close file, restore stdout, get output.
34 w.Close()
35 os.Stdout = stdout
36 out, readFileErr := readFile(w.Name())
37 _ = os.Remove(w.Name())
38 if readFileErr != nil {
39 fmt.Fprintf(os.Stderr, "testing: reading stdout file: %v\n", readFileErr)
40 os.Exit(1)
41 }
42
43 var fail string
44 err := recover()
45 got := strings.TrimSpace(out)
46 want := strings.TrimSpace(eg.Output)
47 if eg.Unordered {
48 if sortLines(got) != sortLines(want) && err == nil {
49 fail = fmt.Sprintf("got:\n%s\nwant (unordered):\n%s\n", out, eg.Output)
50 }
51 } else {
52 if got != want && err == nil {
53 fail = fmt.Sprintf("got:\n%s\nwant:\n%s\n", got, want)
54 }
55 }
56 if fail != "" || err != nil {
57 fmt.Printf("--- FAIL: %s (%s)\n%s", eg.Name, dstr, fail)
58 ok = false
59 } else if *chatty {
60 fmt.Printf("--- PASS: %s (%s)\n", eg.Name, dstr)
61 }
62 if err != nil {
63 panic(err)
64 }
65 }()
66
67 // Run example.
68 eg.F()
69 return
70 }