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