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