github.com/songzhibin97/gkit@v1.2.13/errors/error_test.go (about)

     1  package errors
     2  
     3  import (
     4  	"errors"
     5  	"fmt"
     6  	"net/http"
     7  	"testing"
     8  )
     9  
    10  func TestError(t *testing.T) {
    11  	var base *Error
    12  	err := Errorf(http.StatusBadRequest, "reason", "message")
    13  	err2 := Errorf(http.StatusBadRequest, "reason", "message")
    14  	err3 := err.AddMetadata(map[string]string{
    15  		"foo": "bar",
    16  	})
    17  	werr := fmt.Errorf("wrap %w", err)
    18  
    19  	if errors.Is(err, new(Error)) {
    20  		t.Errorf("should not be equal: %v", err)
    21  	}
    22  	if !errors.Is(werr, err) {
    23  		t.Errorf("should be equal: %v", err)
    24  	}
    25  	if !errors.Is(werr, err2) {
    26  		t.Errorf("should be equal: %v", err)
    27  	}
    28  
    29  	if !errors.As(err, &base) {
    30  		t.Errorf("should be matchs: %v", err)
    31  	}
    32  	if !IsBadRequest(err) {
    33  		t.Errorf("should be matchs: %v", err)
    34  	}
    35  
    36  	if reason := Reason(err); reason != err3.Reason {
    37  		t.Errorf("got %s want: %s", reason, err)
    38  	}
    39  
    40  	if err3.Metadata["foo"] != "bar" {
    41  		t.Error("not expected metadata")
    42  	}
    43  
    44  	gs := err.GRPCStatus()
    45  	se := FromError(gs.Err())
    46  	if se.Reason != se.Reason {
    47  		t.Errorf("got %+v want %+v", se, err)
    48  	}
    49  }
    50  
    51  func TestCode(t *testing.T) {
    52  	var (
    53  		input = []error{
    54  			BadRequest("reason_400", "message_400"),
    55  			Unauthorized("reason_401", "message_401"),
    56  			Forbidden("reason_403", "message_403"),
    57  			NotFound("reason_404", "message_404"),
    58  			Conflict("reason_409", "message_409"),
    59  			InternalServer("reason_500", "message_500"),
    60  			ServiceUnavailable("reason_503", "message_503"),
    61  		}
    62  		output = []func(error) bool{
    63  			IsBadRequest,
    64  			IsUnauthorized,
    65  			IsForbidden,
    66  			IsNotFound,
    67  			IsConflict,
    68  			IsInternalServer,
    69  			IsServiceUnavailable,
    70  		}
    71  	)
    72  
    73  	for i, in := range input {
    74  		if !output[i](in) {
    75  			t.Errorf("not expect: %v", in)
    76  		}
    77  	}
    78  }