This repository has been archived by the owner on Mar 18, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
algorithm_test.go
99 lines (90 loc) · 2.37 KB
/
algorithm_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package jwt
import (
"errors"
"testing"
)
// Defining an algorithm for testing
type TestAlgorithm string
func (alg TestAlgorithm) Sign(data []byte) ([]byte, error) {
if string(alg) == "error" {
return nil, errors.New("Here's the error you requested")
}
return append([]byte(alg), data...), nil
}
func (alg TestAlgorithm) Verify(data, hash []byte, h Header) error {
if len(hash) == len(data)+len(alg) {
return nil
}
return errors.New("token invalid")
}
func (alg TestAlgorithm) Header(h *Header) {
h.Alg = string(alg)
}
func TestRegisterAlgorithm(t *testing.T) {
type args struct {
name string
alg SignatureProvider
}
tests := []struct {
name string
args args
wantErr bool
}{
{"Normal", args{"test", TestAlgorithm("test1")}, false},
{"Already exists", args{"test", TestAlgorithm("test2")}, true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if err := AddSignatureProvider(tt.args.name, tt.args.alg); (err != nil) != tt.wantErr {
t.Errorf("RegisterAlgorithm() error = %v, wantErr %v", err, tt.wantErr)
}
if a, ok := signatureProviders[tt.args.name]; !tt.wantErr && (!ok || a != tt.args.alg) {
t.Errorf("RegisterAlgorithm() failed - want %v but got %v", tt.args.alg, a)
}
})
}
}
func TestSetAlgorithm(t *testing.T) {
type args struct {
name string
alg SignatureProvider
}
tests := []struct {
name string
args args
}{
{"Normal", args{"test", TestAlgorithm("test")}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
SetSignatureProvider(tt.args.name, tt.args.alg)
if a, ok := signatureProviders[tt.args.name]; !ok || a != tt.args.alg {
t.Errorf("SetAlgorithm() failed - want %v but got %v", tt.args.alg, a)
}
})
}
}
func TestDefaultAlgorithm(t *testing.T) {
SetSignatureProvider("test", TestAlgorithm("test"))
type args struct {
name string
}
tests := []struct {
name string
args args
wantErr bool
}{
{"Normal", args{"test"}, false},
{"Invalid", args{"sample"}, true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if err := SetSigningAlgorithm(tt.args.name); (err != nil) != tt.wantErr {
t.Errorf("DefaultAlgorithm() error = %v, wantErr %v", err, tt.wantErr)
}
if !tt.wantErr && defaultAlgorithm != tt.args.name {
t.Errorf("DefaultAlgorithm() failed - want %v but got %v", tt.args.name, defaultAlgorithm)
}
})
}
}