github.com/Finschia/finschia-sdk@v0.48.1/types/errors/stacktrace_test.go (about)

     1  package errors
     2  
     3  import (
     4  	"errors"
     5  	"fmt"
     6  	"reflect"
     7  	"strings"
     8  )
     9  
    10  func (s *errorsTestSuite) TestStackTrace() {
    11  	cases := map[string]struct {
    12  		err       error
    13  		wantError string
    14  	}{
    15  		"New gives us a stacktrace": {
    16  			err:       Wrap(ErrNoSignatures, "name"),
    17  			wantError: "name: no signatures supplied",
    18  		},
    19  		"Wrapping stderr gives us a stacktrace": {
    20  			err:       Wrap(fmt.Errorf("foo"), "standard"),
    21  			wantError: "standard: foo",
    22  		},
    23  		"Wrapping pkg/errors gives us clean stacktrace": {
    24  			err:       Wrap(errors.New("bar"), "pkg"),
    25  			wantError: "pkg: bar",
    26  		},
    27  		"Wrapping inside another function is still clean": {
    28  			err:       Wrap(fmt.Errorf("indirect"), "do the do"),
    29  			wantError: "do the do: indirect",
    30  		},
    31  	}
    32  
    33  	// Wrapping code is unwanted in the errors stack trace.
    34  	unwantedSrc := []string{
    35  		"github.com/Finschia/finschia-sdk/types/errors.Wrap\n",
    36  		"github.com/Finschia/finschia-sdk/types/errors.Wrapf\n",
    37  		"runtime.goexit\n",
    38  	}
    39  	const thisTestSrc = "types/errors/stacktrace_test.go"
    40  
    41  	for _, tc := range cases {
    42  		s.Require().True(reflect.DeepEqual(tc.err.Error(), tc.wantError))
    43  		s.Require().NotNil(stackTrace(tc.err))
    44  		fullStack := fmt.Sprintf("%+v", tc.err)
    45  		s.Require().True(strings.Contains(fullStack, thisTestSrc))
    46  		s.Require().True(strings.Contains(fullStack, tc.wantError))
    47  
    48  		for _, src := range unwantedSrc {
    49  			if strings.Contains(fullStack, src) {
    50  				s.T().Logf("Stack trace below\n----%s\n----", fullStack)
    51  				s.T().Logf("full stack contains unwanted source file path: %q", src)
    52  			}
    53  		}
    54  
    55  		tinyStack := fmt.Sprintf("%v", tc.err)
    56  		s.Require().True(strings.HasPrefix(tinyStack, tc.wantError))
    57  		s.Require().False(strings.Contains(tinyStack, "\n"))
    58  		// contains a link to where it was created, which must
    59  		// be here, not the Wrap() function
    60  		s.Require().True(strings.Contains(tinyStack, thisTestSrc))
    61  	}
    62  }