errors_test.mx raw

   1  package errors
   2  
   3  import (
   4  	"fmt"
   5  	"testing"
   6  )
   7  
   8  func TestValidationError(t *testing.T) {
   9  	e := ErrInvalidEventID
  10  	if string(e.Code()) != "INVALID_ID" {
  11  		t.Fatal("wrong code")
  12  	}
  13  	if string(e.Category()) != "validation" {
  14  		t.Fatal("wrong category")
  15  	}
  16  	if e.IsRetryable() {
  17  		t.Fatal("should not be retryable")
  18  	}
  19  	if string(e.Field) != "id" {
  20  		t.Fatal("wrong field")
  21  	}
  22  }
  23  
  24  func TestAuthorizationError(t *testing.T) {
  25  	e := ErrAuthRequired
  26  	if !e.NeedsAuth() {
  27  		t.Fatal("should need auth")
  28  	}
  29  	if string(e.Code()) != "AUTH_REQUIRED" {
  30  		t.Fatal("wrong code")
  31  	}
  32  	e2 := e.WithPubkey([]byte("abc"))
  33  	if string(e2.Pubkey) != "abc" {
  34  		t.Fatal("wrong pubkey")
  35  	}
  36  }
  37  
  38  func TestProcessingError(t *testing.T) {
  39  	e := ErrDuplicate
  40  	if string(e.Code()) != "DUPLICATE" {
  41  		t.Fatal("wrong code")
  42  	}
  43  	e2 := e.WithKind(1)
  44  	if e2.Kind != 1 {
  45  		t.Fatal("wrong kind")
  46  	}
  47  }
  48  
  49  func TestWithCause(t *testing.T) {
  50  	cause := fmt.Errorf("disk full")
  51  	e := ErrStorageFull.WithCause(cause)
  52  	if e.Unwrap() != cause {
  53  		t.Fatal("cause not set")
  54  	}
  55  	s := e.Error()
  56  	if !containsStr(s, "disk full") {
  57  		t.Fatalf("cause not in error string: %s", s)
  58  	}
  59  }
  60  
  61  func TestHelpers(t *testing.T) {
  62  	if !Is(ErrDuplicate, ErrDuplicate) {
  63  		t.Fatal("Is should match same code")
  64  	}
  65  	if Is(ErrDuplicate, ErrRateLimited) {
  66  		t.Fatal("Is should not match different code")
  67  	}
  68  	if !IsValidation(ErrInvalidJSON) {
  69  		t.Fatal("should be validation")
  70  	}
  71  	if !IsAuthorization(ErrBanned) {
  72  		t.Fatal("should be authorization")
  73  	}
  74  	if !IsProcessing(ErrDuplicate) {
  75  		t.Fatal("should be processing")
  76  	}
  77  	if !IsPolicy(ErrKindBlocked) {
  78  		t.Fatal("should be policy")
  79  	}
  80  	if !IsStorage(ErrStorageFull) {
  81  		t.Fatal("should be storage")
  82  	}
  83  	if !IsRetryable(ErrRateLimited) {
  84  		t.Fatal("rate limited should be retryable")
  85  	}
  86  	if IsRetryable(ErrDuplicate) {
  87  		t.Fatal("duplicate should not be retryable")
  88  	}
  89  	if !NeedsAuth(ErrAuthRequired) {
  90  		t.Fatal("auth required should need auth")
  91  	}
  92  	if NeedsAuth(ErrBanned) {
  93  		t.Fatal("banned should not need auth")
  94  	}
  95  }
  96  
  97  func TestCodeNil(t *testing.T) {
  98  	c := Code(fmt.Errorf("plain"))
  99  	if c != nil {
 100  		t.Fatal("non-domain error should return nil code")
 101  	}
 102  }
 103  
 104  func containsStr(s, sub string) bool {
 105  	for i := 0; i <= len(s)-len(sub); i++ {
 106  		if s[i:i+len(sub)] == sub {
 107  			return true
 108  		}
 109  	}
 110  	return false
 111  }
 112