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

     1  // Copyright © 2023 Hedzr Yeh.
     2  
     3  //go:build go1.13
     4  // +build go1.13
     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 TestJoinErrorsStdFormat(t *testing.T) {
    18  	err1 := errors.New("err1")
    19  	err2 := errors.New("err2")
    20  
    21  	err := v3.Join(err1, err2)
    22  
    23  	fmt.Printf("%T, %v\n", err, err)
    24  
    25  	if v3.Is(err, err1) {
    26  		t.Log("err is err1")
    27  	} else {
    28  		t.Fatal("FAILED: expecting err is err1")
    29  	}
    30  
    31  	if v3.Is(err, err2) {
    32  		t.Log("err is err2")
    33  	} else {
    34  		t.Fatal("FAILED: expecting err is err2")
    35  	}
    36  
    37  	err3 := fmt.Errorf("error3: %w", err)
    38  	fmt.Printf("%T, %v\n", err3, v3.Unwrap(err3))
    39  
    40  	if v3.Is(err3, err1) {
    41  		t.Log("err3 is err1")
    42  	} else {
    43  		t.Fatal("FAILED: expecting err3 is err1")
    44  	}
    45  
    46  	if v3.Is(err3, err2) {
    47  		t.Log("err3 is err2")
    48  	} else {
    49  		t.Fatal("FAILED: expecting err3 is err2")
    50  	}
    51  
    52  	if !v3.Is(err2, err3) {
    53  		t.Log("err2 isn't err3")
    54  	} else {
    55  		t.Fatal("FAILED: expecting err2 is err3")
    56  	}
    57  }
    58  
    59  func dummy(t *testing.T) error {
    60  	a, b := 10, 0
    61  	result, err := Divide(a, b)
    62  	if err != nil {
    63  		var divErr *DivisionError
    64  		switch {
    65  		case errors.As(err, &divErr):
    66  			fmt.Printf("%d / %d is not mathematically valid: %s\n",
    67  				divErr.IntA, divErr.IntB, divErr.Error())
    68  		default:
    69  			fmt.Printf("unexpected division error: %s\n", err)
    70  			t.Fail()
    71  		}
    72  		return err
    73  	}
    74  
    75  	fmt.Printf("%d / %d = %d\n", a, b, result)
    76  	return err
    77  }
    78  
    79  func TestCauses2_errors(t *testing.T) {
    80  	err := io.EOF
    81  
    82  	if !errors.Is(err, io.EOF) {
    83  		t.Fail()
    84  	}
    85  
    86  	err = dummy(t)
    87  	err = fmt.Errorf("wrapped: %w", err)
    88  	t.Logf("divide: %v", err)
    89  	t.Logf("Unwrap: %v", errors.Unwrap(err))
    90  }