gopkg.in/hedzr/errors.v3@v3.3.1/join_go1.20_test.go (about)

     1  // Copyright © 2023 Hedzr Yeh.
     2  
     3  //go:build go1.20
     4  // +build go1.20
     5  
     6  package errors_test
     7  
     8  import (
     9  	"errors"
    10  	"fmt"
    11  	"io"
    12  	"testing"
    13  
    14  	v3 "gopkg.in/hedzr/errors.v3"
    15  )
    16  
    17  func TestJoinErrorsStd(t *testing.T) {
    18  	err1 := errors.New("err1")
    19  	err2 := errors.New("err2")
    20  	err := v3.Join(err1, err2)
    21  	fmt.Printf("%T, %v\n", err, err)
    22  	if v3.Is(err, err1) {
    23  		t.Log("err is err1")
    24  	} else {
    25  		t.Fatal("expecting err is err1")
    26  	}
    27  	if v3.Is(err, err2) {
    28  		t.Log("err is err2")
    29  	} else {
    30  		t.Fatal("expecting err is err2")
    31  	}
    32  
    33  	err3 := fmt.Errorf("error3: %w", err)
    34  	fmt.Printf("%T, %v\n", err3, v3.Unwrap(err3))
    35  	if v3.Is(err3, err1) {
    36  		t.Log("err3 is err1")
    37  	} else {
    38  		t.Fatal("expecting err3 is err1")
    39  	}
    40  	if v3.Is(err3, err2) {
    41  		t.Log("err3 is err2")
    42  	} else {
    43  		t.Fatal("expecting err3 is err1")
    44  	}
    45  }
    46  
    47  func dummyV3(t *testing.T) error {
    48  	a, b := 10, 0
    49  	result, err := Divide(a, b)
    50  	if err != nil {
    51  		var divErr *DivisionError
    52  		switch {
    53  		case v3.As(err, &divErr):
    54  			fmt.Printf("%d / %d is not mathematically valid: %s\n",
    55  				divErr.IntA, divErr.IntB, divErr.Error())
    56  		default:
    57  			fmt.Printf("unexpected division error: %s\n", err)
    58  			t.Fail()
    59  		}
    60  		return err
    61  	}
    62  
    63  	fmt.Printf("%d / %d = %d\n", a, b, result)
    64  	return err
    65  }
    66  
    67  func TestCauses2_errorsV3(t *testing.T) {
    68  	err := io.EOF
    69  
    70  	if !v3.Is(err, io.EOF) {
    71  		t.Fatal("FAILED: expecting err is io.EOF")
    72  	}
    73  
    74  	err = dummyV3(t)
    75  	err = fmt.Errorf("wrapped: %w", err)
    76  	t.Logf("divide: %v", err)
    77  	t.Logf("Unwrap: %v", v3.Unwrap(err))
    78  }