1// Copyright 2017 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 5package testing 6 7import ( 8 "bytes" 9 "regexp" 10 "strings" 11) 12 13func TestTBHelper(t *T) { 14 var buf bytes.Buffer 15 ctx := newTestContext(1, newMatcher(regexp.MatchString, "", "")) 16 t1 := &T{ 17 common: common{ 18 signal: make(chan bool), 19 w: &buf, 20 }, 21 context: ctx, 22 } 23 t1.Run("Test", testHelper) 24 25 want := `--- FAIL: Test (?s) 26helperfuncs_test.go:12: 0 27helperfuncs_test.go:33: 1 28helperfuncs_test.go:21: 2 29helperfuncs_test.go:35: 3 30helperfuncs_test.go:42: 4 31--- FAIL: Test/sub (?s) 32helperfuncs_test.go:45: 5 33helperfuncs_test.go:21: 6 34helperfuncs_test.go:44: 7 35helperfuncs_test.go:56: 8 36--- FAIL: Test/sub2 (?s) 37helperfuncs_test.go:71: 11 38helperfuncs_test.go:75: recover 12 39helperfuncs_test.go:64: 9 40helperfuncs_test.go:60: 10 41` 42 lines := strings.Split(buf.String(), "\n") 43 durationRE := regexp.MustCompile(`\(.*\)$`) 44 for i, line := range lines { 45 line = strings.TrimSpace(line) 46 line = durationRE.ReplaceAllString(line, "(?s)") 47 lines[i] = line 48 } 49 got := strings.Join(lines, "\n") 50 if got != want { 51 t.Errorf("got output:\n\n%s\nwant:\n\n%s", got, want) 52 } 53} 54 55func TestTBHelperParallel(t *T) { 56 var buf bytes.Buffer 57 ctx := newTestContext(1, newMatcher(regexp.MatchString, "", "")) 58 t1 := &T{ 59 common: common{ 60 signal: make(chan bool), 61 w: &buf, 62 }, 63 context: ctx, 64 } 65 t1.Run("Test", parallelTestHelper) 66 67 lines := strings.Split(strings.TrimSpace(buf.String()), "\n") 68 if len(lines) != 6 { 69 t.Fatalf("parallelTestHelper gave %d lines of output; want 6", len(lines)) 70 } 71 want := "helperfuncs_test.go:21: parallel" 72 if got := strings.TrimSpace(lines[1]); got != want { 73 t.Errorf("got output line %q; want %q", got, want) 74 } 75} 76 77type noopWriter int 78 79func (nw *noopWriter) Write(b []byte) (int, error) { return len(b), nil } 80 81func BenchmarkTBHelper(b *B) { 82 w := noopWriter(0) 83 ctx := newTestContext(1, newMatcher(regexp.MatchString, "", "")) 84 t1 := &T{ 85 common: common{ 86 signal: make(chan bool), 87 w: &w, 88 }, 89 context: ctx, 90 } 91 f1 := func() { 92 t1.Helper() 93 } 94 f2 := func() { 95 t1.Helper() 96 } 97 b.ResetTimer() 98 b.ReportAllocs() 99 for i := 0; i < b.N; i++ { 100 if i&1 == 0 { 101 f1() 102 } else { 103 f2() 104 } 105 } 106} 107