1
0
mirror of https://github.com/golang/go synced 2024-10-03 05:11:21 -06:00
go/src/testing/helper_test.go
Caleb Spare bc29313722 testing: add TB.Helper to better support test helpers
This CL implements the proposal at
https://github.com/golang/proposal/blob/master/design/4899-testing-helper.md.

It's based on Josh's CL 79890043 from a few years ago:
https://codereview.appspot.com/79890043 but makes several changes,
most notably by using the new CallersFrames API so that it works with
mid-stack inlining.

Another detail came up while I was working on this: I didn't want the
user to be able to call t.Helper from inside their TestXxx function
directly (which would mean we'd print a file:line from inside the
testing package itself), so I explicitly prevented this from working.

Fixes #4899.

Change-Id: I37493edcfb63307f950442bbaf993d1589515310
Reviewed-on: https://go-review.googlesource.com/38796
Run-TryBot: Caleb Spare <cespare@gmail.com>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Ian Lance Taylor <iant@golang.org>
2017-04-14 16:47:25 +00:00

71 lines
1.6 KiB
Go

// Copyright 2017 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"
"regexp"
"strings"
)
func TestTBHelper(t *T) {
var buf bytes.Buffer
ctx := newTestContext(1, newMatcher(regexp.MatchString, "", ""))
t1 := &T{
common: common{
signal: make(chan bool),
w: &buf,
},
context: ctx,
}
t1.Run("Test", testHelper)
want := `--- FAIL: Test (?s)
helperfuncs_test.go:12: 0
helperfuncs_test.go:33: 1
helperfuncs_test.go:21: 2
helperfuncs_test.go:35: 3
helperfuncs_test.go:42: 4
helperfuncs_test.go:47: 5
--- FAIL: Test/sub (?s)
helperfuncs_test.go:50: 6
helperfuncs_test.go:21: 7
helperfuncs_test.go:53: 8
`
lines := strings.Split(buf.String(), "\n")
durationRE := regexp.MustCompile(`\(.*\)$`)
for i, line := range lines {
line = strings.TrimSpace(line)
line = durationRE.ReplaceAllString(line, "(?s)")
lines[i] = line
}
got := strings.Join(lines, "\n")
if got != want {
t.Errorf("got output:\n\n%s\nwant:\n\n%s", got, want)
}
}
func TestTBHelperParallel(t *T) {
var buf bytes.Buffer
ctx := newTestContext(1, newMatcher(regexp.MatchString, "", ""))
t1 := &T{
common: common{
signal: make(chan bool),
w: &buf,
},
context: ctx,
}
t1.Run("Test", parallelTestHelper)
lines := strings.Split(strings.TrimSpace(buf.String()), "\n")
if len(lines) != 6 {
t.Fatalf("parallelTestHelper gave %d lines of output; want 6", len(lines))
}
want := "helperfuncs_test.go:21: parallel"
if got := strings.TrimSpace(lines[1]); got != want {
t.Errorf("got output line %q; want %q", got, want)
}
}