git.sr.ht/~pingoo/stdx@v0.0.0-20240218134121-094174641f6e/token/token_test.go (about) 1 package token_test 2 3 import ( 4 "strings" 5 "testing" 6 7 "git.sr.ht/~pingoo/stdx/crypto" 8 "git.sr.ht/~pingoo/stdx/token" 9 "git.sr.ht/~pingoo/stdx/uuid" 10 ) 11 12 var emptyUUID = make([]byte, uuid.Size) 13 var emptySecret = make([]byte, token.SecretSize) 14 var emptyHash = make([]byte, token.HashSize) 15 16 func TestNew(t *testing.T) { 17 newToken, err := token.New("") 18 if err != nil { 19 t.Errorf("Generating new token: %v", err) 20 } 21 22 tokenIDByte, _ := newToken.ID().MarshalBinary() 23 if crypto.ConstantTimeCompare(tokenIDByte, emptyUUID) { 24 t.Error("token.ID is empty") 25 } 26 27 if len(newToken.Secret()) != token.SecretSize { 28 t.Errorf("Bad secret size. Expected: %d | Got: %d", token.SecretSize, len(newToken.Secret())) 29 } 30 31 if crypto.ConstantTimeCompare(newToken.Secret(), emptySecret) { 32 t.Error("token.Secret is empty") 33 } 34 35 if len(newToken.Hash()) != token.HashSize { 36 t.Errorf("Bad hash size. Expected: %d | Got: %d", token.HashSize, len(newToken.Hash())) 37 } 38 39 if crypto.ConstantTimeCompare(newToken.Hash(), emptyHash) { 40 t.Error("token.Hash is empty") 41 } 42 } 43 44 func TestNewWithPrefix(t *testing.T) { 45 prefix := "test_" 46 newToken, err := token.New(prefix) 47 if err != nil { 48 t.Errorf("Generating new token: %v", err) 49 } 50 51 if !strings.HasPrefix(newToken.String(), prefix) { 52 t.Errorf("Token doesn't have prefix. Expected: %s | Got: %s", prefix, newToken.String()) 53 } 54 } 55 56 func TestParse(t *testing.T) { 57 for i := 0; i < 1000; i += 1 { 58 newToken, err := token.New("") 59 if err != nil { 60 t.Errorf("Generating token: %v", err) 61 } 62 _, err = token.Parse("", newToken.String()) 63 if err != nil { 64 t.Errorf("parsing token: %v", err) 65 } 66 } 67 } 68 69 func TestVerify(t *testing.T) { 70 for i := 0; i < 1000; i += 1 { 71 newToken, err := token.New("") 72 if err != nil { 73 t.Errorf("Generating token: %v", err) 74 } 75 76 if err = newToken.Verify(newToken.Hash()); err != nil { 77 t.Errorf("verifying otken. expected: nil | got: %v", err) 78 } 79 } 80 81 newToken, err := token.New("") 82 if err != nil { 83 t.Errorf("Generating token: %v", err) 84 } 85 if err = newToken.Verify(nil); err == nil { 86 t.Errorf("verifying token against null. expected: %v | got: %v", token.ErrTokenIsNotValid, err) 87 } 88 if err = newToken.Verify([]byte{}); err == nil { 89 t.Errorf("verifying token against empty slice. expected: %v | got: %v", token.ErrTokenIsNotValid, err) 90 } 91 }