example.go 2.23 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
	"sort"
13
	"strings"
14 15 16 17
	"time"
)

type InternalExample struct {
18 19 20 21
	Name      string
	F         func()
	Output    string
	Unordered bool
22 23
}

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

27 28 29
	var eg InternalExample

	for _, eg = range examples {
30 31 32 33 34 35 36 37
		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
		}
38 39
		if !runExample(eg) {
			ok = false
40
		}
41 42 43 44 45
	}

	return
}

46 47 48 49 50 51
func sortLines(output string) string {
	lines := strings.Split(output, "\n")
	sort.Strings(lines)
	return strings.Join(lines, "\n")
}

52 53
func runExample(eg InternalExample) (ok bool) {
	if *chatty {
54
		fmt.Printf("=== RUN   %s\n", eg.Name)
55
	}
56

57 58 59 60 61 62 63 64 65 66
	// 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() {
67 68
		var buf bytes.Buffer
		_, err := io.Copy(&buf, r)
69
		r.Close()
70
		if err != nil {
71
			fmt.Fprintf(os.Stderr, "testing: copying pipe: %v\n", err)
72 73
			os.Exit(1)
		}
74 75 76 77 78
		outC <- buf.String()
	}()

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

80 81
	// Clean up in a deferred call so we can recover if the example panics.
	defer func() {
82
		dstr := fmtDuration(time.Now().Sub(start))
83

84
		// Close pipe, restore stdout, get output.
85
		w.Close()
86
		os.Stdout = stdout
87 88
		out := <-outC

89 90
		var fail string
		err := recover()
91 92 93 94 95 96 97 98 99 100
		got := strings.TrimSpace(out)
		want := strings.TrimSpace(eg.Output)
		if eg.Unordered {
			if sortLines(got) != sortLines(want) && err == nil {
				fail = fmt.Sprintf("got:\n%s\nwant (unordered):\n%s\n", out, eg.Output)
			}
		} else {
			if got != want && err == nil {
				fail = fmt.Sprintf("got:\n%s\nwant:\n%s\n", got, want)
			}
101 102
		}
		if fail != "" || err != nil {
103
			fmt.Printf("--- FAIL: %s (%s)\n%s", eg.Name, dstr, fail)
104 105
			ok = false
		} else if *chatty {
106
			fmt.Printf("--- PASS: %s (%s)\n", eg.Name, dstr)
107
		}
108 109 110 111
		if err != nil {
			panic(err)
		}
	}()
112

113 114
	// Run example.
	eg.F()
115 116
	return
}