Source file src/testing/run_example.go

Documentation: testing

     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  // 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  	start := time.Now()
    47  
    48  	// Clean up in a deferred call so we can recover if the example panics.
    49  	defer func() {
    50  		timeSpent := time.Since(start)
    51  
    52  		// Close pipe, restore stdout, get output.
    53  		w.Close()
    54  		os.Stdout = stdout
    55  		out := <-outC
    56  
    57  		err := recover()
    58  		ok = eg.processRunResult(out, timeSpent, err)
    59  	}()
    60  
    61  	// Run example.
    62  	eg.F()
    63  	return
    64  }
    65  

View as plain text