...

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

View as plain text