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