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