github.com/code-reading/golang@v0.0.0-20220303082512-ba5bc0e589a3/go/src/testing/run_example_js.go (about) 1 // Copyright 2019 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 //go:build js 6 // +build js 7 8 package testing 9 10 import ( 11 "fmt" 12 "io" 13 "os" 14 "strings" 15 "time" 16 ) 17 18 // TODO(@musiol, @odeke-em): unify this code back into 19 // example.go when js/wasm gets an os.Pipe implementation. 20 func runExample(eg InternalExample) (ok bool) { 21 if *chatty { 22 fmt.Printf("=== RUN %s\n", eg.Name) 23 } 24 25 // Capture stdout to temporary file. We're not using 26 // os.Pipe because it is not supported on js/wasm. 27 stdout := os.Stdout 28 f := createTempFile(eg.Name) 29 os.Stdout = f 30 finished := false 31 start := time.Now() 32 33 // Clean up in a deferred call so we can recover if the example panics. 34 defer func() { 35 timeSpent := time.Since(start) 36 37 // Restore stdout, get output and remove temporary file. 38 os.Stdout = stdout 39 var buf strings.Builder 40 _, seekErr := f.Seek(0, os.SEEK_SET) 41 _, readErr := io.Copy(&buf, f) 42 out := buf.String() 43 f.Close() 44 os.Remove(f.Name()) 45 if seekErr != nil { 46 fmt.Fprintf(os.Stderr, "testing: seek temp file: %v\n", seekErr) 47 os.Exit(1) 48 } 49 if readErr != nil { 50 fmt.Fprintf(os.Stderr, "testing: read temp file: %v\n", readErr) 51 os.Exit(1) 52 } 53 54 err := recover() 55 ok = eg.processRunResult(out, timeSpent, finished, err) 56 }() 57 58 // Run example. 59 eg.F() 60 finished = true 61 return 62 } 63 64 func createTempFile(exampleName string) *os.File { 65 for i := 0; ; i++ { 66 name := fmt.Sprintf("%s/go-example-stdout-%s-%d.txt", os.TempDir(), exampleName, i) 67 f, err := os.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0600) 68 if err != nil { 69 if os.IsExist(err) { 70 continue 71 } 72 fmt.Fprintf(os.Stderr, "testing: open temp file: %v\n", err) 73 os.Exit(1) 74 } 75 return f 76 } 77 }