github.com/keybase/client/go@v0.0.0-20241007131713-f10651d043c8/kbfs/libkbfs/safe_test_reporter_test.go (about)

     1  // Copyright 2016 Keybase Inc. All rights reserved.
     2  // Use of this source code is governed by a BSD
     3  // license that can be found in the LICENSE file.
     4  
     5  package libkbfs
     6  
     7  import (
     8  	"fmt"
     9  	"runtime"
    10  	"strings"
    11  	"testing"
    12  )
    13  
    14  // SafeTestReporter logs failures as they happen, but ferries failure
    15  // calls back to the main test goroutine, to avoid violating
    16  // testing.T's FailNow() semantics.
    17  type SafeTestReporter struct {
    18  	t *testing.T
    19  }
    20  
    21  func NewSafeTestReporter(t *testing.T) *SafeTestReporter {
    22  	return &SafeTestReporter{t: t}
    23  }
    24  
    25  // makePrefix() returns a string with the file and line of the call site.
    26  //
    27  // This function was adapted from decorate() in testing/testing.go.
    28  func makePrefix() string {
    29  	// makePrefix + error + Errorf or Fatalf + function.
    30  	_, file, line, ok := runtime.Caller(4)
    31  	if ok {
    32  		// Truncate file name at last file name separator.
    33  		if index := strings.LastIndex(file, "/"); index >= 0 {
    34  			file = file[index+1:]
    35  		} else if index = strings.LastIndex(file, "\\"); index >= 0 {
    36  			file = file[index+1:]
    37  		}
    38  	} else {
    39  		file = "???"
    40  		line = 1
    41  	}
    42  	return fmt.Sprintf("%s:%d", file, line)
    43  }
    44  
    45  func (ctr *SafeTestReporter) error(s string) {
    46  	// Use \r to clear out testing.T's prefix (at least on a terminal).
    47  	ctr.t.Errorf("\r%s: %s", makePrefix(), s)
    48  }
    49  
    50  func (ctr *SafeTestReporter) Errorf(format string, args ...interface{}) {
    51  	ctr.error(fmt.Sprintf(format, args...))
    52  }
    53  
    54  // Fatalf errors and then panics.
    55  func (ctr *SafeTestReporter) Fatalf(format string, args ...interface{}) {
    56  	s := fmt.Sprintf(format, args...)
    57  	ctr.error(s)
    58  	// panic here, since a Goexit() might leave the main thread
    59  	// waiting for results.
    60  	panic(s)
    61  }
    62  
    63  func (ctr *SafeTestReporter) CheckForFailures() {
    64  	// Empty for now, since any fatal failure will have panic'd the
    65  	// test.  In the future, we may have a better strategy.
    66  }