github.com/haraldrudell/parl@v0.4.176/nil-error_test.go (about)

     1  /*
     2  © 2022–present Harald Rudell <harald.rudell@gmail.com> (https://haraldrudell.github.io/haraldrudell/)
     3  ISC License
     4  */
     5  
     6  package parl
     7  
     8  import (
     9  	"errors"
    10  	"fmt"
    11  	"strings"
    12  	"testing"
    13  
    14  	"github.com/haraldrudell/parl/perrors"
    15  	"github.com/haraldrudell/parl/pruntime"
    16  )
    17  
    18  func TestNilError(t *testing.T) {
    19  	var argName = "xValue"
    20  	var suffix = " cannot be nil"
    21  	type iface interface{ NilValueError() }
    22  
    23  	// get NilErr error value
    24  	packFunc, err := newX(argName)
    25  	if err == nil {
    26  		t.Error("expected error missing")
    27  		t.FailNow()
    28  	}
    29  	if packFunc == "" {
    30  		t.Error("packFunc empty")
    31  	}
    32  
    33  	// error chain:
    34  	// err: *errorglue.errorStack “parl.newX xValue cannot be nil” isErrNil: false
    35  	// err: *parl.nilValue “parl.newX xValue cannot be nil” isErrNil: true
    36  	var eList []string
    37  	for e := err; e != nil; e = errors.Unwrap(e) {
    38  		_, isErrNil := e.(iface)
    39  		eList = append(eList, fmt.Sprintf("err: %T “%+[1]v” isErrNil: %t",
    40  			e,
    41  			isErrNil,
    42  		))
    43  	}
    44  	t.Logf("error chain:\n%s", strings.Join(eList, "\n"))
    45  
    46  	var expMessage = packFunc + "\x20" + argName + suffix
    47  
    48  	// error should be ErrNil
    49  	if !errors.Is(err, ErrNil) {
    50  
    51  		_, errIs := err.(iface)
    52  		var errNilErr error = ErrNil
    53  		_, errNilIs := errNilErr.(iface)
    54  		t.Errorf("err not ErrNil: err: %t ErrNil: %t", errIs, errNilIs)
    55  	}
    56  	if err.Error() != expMessage {
    57  		t.Errorf("error message:\n%q exp\n%q",
    58  			err.Error(),
    59  			expMessage,
    60  		)
    61  	}
    62  
    63  	// non-nill error should return false
    64  	var err2 = perrors.New("x")
    65  	if errors.Is(err2, ErrNil) {
    66  		t.Error("err2 is ErrNil")
    67  	}
    68  }
    69  
    70  // newX generates a NilError similar to a new function
    71  func newX(argName string) (packFunc string, err error) {
    72  	packFunc = pruntime.NewCodeLocation(0).PackFunc()
    73  	err = NilError(argName)
    74  	return
    75  }