example.go 1.88 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package testing

import (
	"bytes"
	"fmt"
	"io"
	"os"
12
	"strings"
13 14 15 16 17 18 19 20 21
	"time"
)

type InternalExample struct {
	Name   string
	F      func()
	Output string
}

22
func RunExamples(matchString func(pat, str string) (bool, error), examples []InternalExample) (ok bool) {
23 24
	ok = true

25 26 27
	var eg InternalExample

	for _, eg = range examples {
28 29 30 31 32 33 34 35
		matched, err := matchString(*match, eg.Name)
		if err != nil {
			fmt.Fprintf(os.Stderr, "testing: invalid regexp for -test.run: %s\n", err)
			os.Exit(1)
		}
		if !matched {
			continue
		}
36 37
		if !runExample(eg) {
			ok = false
38
		}
39 40 41 42 43 44 45 46 47
	}

	return
}

func runExample(eg InternalExample) (ok bool) {
	if *chatty {
		fmt.Printf("=== RUN: %s\n", eg.Name)
	}
48

49 50 51 52 53 54 55 56 57 58 59 60 61
	// Capture stdout.
	stdout := os.Stdout
	r, w, err := os.Pipe()
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	os.Stdout = w
	outC := make(chan string)
	go func() {
		buf := new(bytes.Buffer)
		_, err := io.Copy(buf, r)
		r.Close()
62
		if err != nil {
63
			fmt.Fprintf(os.Stderr, "testing: copying pipe: %v\n", err)
64 65
			os.Exit(1)
		}
66 67 68 69 70
		outC <- buf.String()
	}()

	start := time.Now()
	ok = true
71

72 73
	// Clean up in a deferred call so we can recover if the example panics.
	defer func() {
74
		dstr := fmtDuration(time.Now().Sub(start))
75

76
		// Close pipe, restore stdout, get output.
77
		w.Close()
78
		os.Stdout = stdout
79 80
		out := <-outC

81 82 83 84 85 86
		var fail string
		err := recover()
		if g, e := strings.TrimSpace(out), strings.TrimSpace(eg.Output); g != e && err == nil {
			fail = fmt.Sprintf("got:\n%s\nwant:\n%s\n", g, e)
		}
		if fail != "" || err != nil {
87
			fmt.Printf("--- FAIL: %s (%s)\n%s", eg.Name, dstr, fail)
88 89
			ok = false
		} else if *chatty {
90
			fmt.Printf("--- PASS: %s (%s)\n", eg.Name, dstr)
91
		}
92 93 94 95
		if err != nil {
			panic(err)
		}
	}()
96

97 98
	// Run example.
	eg.F()
99 100
	return
}