Source file src/testing/run_example.go

     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  
     7  // TODO(@musiol, @odeke-em): re-unify this entire file back into
     8  // example.go when js/wasm gets an os.Pipe implementation
     9  // and no longer needs this separation.
    10  
    11  package testing
    12  
    13  import (
    14  	"fmt"
    15  	"io"
    16  	"os"
    17  	"strings"
    18  	"time"
    19  )
    20  
    21  func runExample(eg InternalExample) (ok bool) {
    22  	if *chatty {
    23  		fmt.Printf("=== RUN   %s\n", eg.Name)
    24  	}
    25  
    26  	// Capture stdout.
    27  	stdout := os.Stdout
    28  	r, w, err := os.Pipe()
    29  	if err != nil {
    30  		fmt.Fprintln(os.Stderr, err)
    31  		os.Exit(1)
    32  	}
    33  	os.Stdout = w
    34  	outC := make(chan string)
    35  	go func() {
    36  		var buf strings.Builder
    37  		_, err := io.Copy(&buf, r)
    38  		r.Close()
    39  		if err != nil {
    40  			fmt.Fprintf(os.Stderr, "testing: copying pipe: %v\n", err)
    41  			os.Exit(1)
    42  		}
    43  		outC <- buf.String()
    44  	}()
    45  
    46  	finished := false
    47  	start := time.Now()
    48  
    49  	// Clean up in a deferred call so we can recover if the example panics.
    50  	defer func() {
    51  		timeSpent := time.Since(start)
    52  
    53  		// Close pipe, restore stdout, get output.
    54  		w.Close()
    55  		os.Stdout = stdout
    56  		out := <-outC
    57  
    58  		err := recover()
    59  		ok = eg.processRunResult(out, timeSpent, finished, err)
    60  	}()
    61  
    62  	// Run example.
    63  	eg.F()
    64  	finished = true
    65  	return
    66  }
    67  

View as plain text