diff --git a/parser_test.go b/parser_test.go index 58efa37..11cc82c 100644 --- a/parser_test.go +++ b/parser_test.go @@ -4,12 +4,12 @@ import ( "crypto/rsa" "encoding/json" "fmt" - "io/ioutil" "reflect" "testing" "time" "github.com/dgrijalva/jwt-go" + "github.com/dgrijalva/jwt-go/test" ) var ( @@ -20,6 +20,10 @@ var ( nilKeyFunc jwt.Keyfunc = nil ) +func init() { + jwtTestDefaultKey = test.LoadRSAPublicKeyFromDisk("test/sample_key.pub") +} + var jwtTestData = []struct { name string tokenString string @@ -130,40 +134,12 @@ var jwtTestData = []struct { }, } -func init() { - if keyData, e := ioutil.ReadFile("test/sample_key.pub"); e == nil { - if jwtTestDefaultKey, e = jwt.ParseRSAPublicKeyFromPEM(keyData); e != nil { - panic(e) - } - } else { - panic(e) - } -} - -func makeSample(c jwt.MapClaims) string { - keyData, e := ioutil.ReadFile("test/sample_key") - if e != nil { - panic(e.Error()) - } - key, e := jwt.ParseRSAPrivateKeyFromPEM(keyData) - if e != nil { - panic(e.Error()) - } - - token := jwt.NewWithClaims(jwt.SigningMethodRS256, c) - s, e := token.SignedString(key) - - if e != nil { - panic(e.Error()) - } - - return s -} - func TestParser_Parse(t *testing.T) { + privateKey := test.LoadRSAPrivateKeyFromDisk("test/sample_key") + for _, data := range jwtTestData { if data.tokenString == "" { - data.tokenString = makeSample(data.claims) + data.tokenString = test.MakeSampleToken(data.claims, privateKey) } var token *jwt.Token diff --git a/test/helpers.go b/test/helpers.go new file mode 100644 index 0000000..39b5208 --- /dev/null +++ b/test/helpers.go @@ -0,0 +1,42 @@ +package test + +import ( + "crypto/rsa" + "github.com/dgrijalva/jwt-go" + "io/ioutil" +) + +func LoadRSAPrivateKeyFromDisk(location string) *rsa.PrivateKey { + keyData, e := ioutil.ReadFile(location) + if e != nil { + panic(e.Error()) + } + key, e := jwt.ParseRSAPrivateKeyFromPEM(keyData) + if e != nil { + panic(e.Error()) + } + return key +} + +func LoadRSAPublicKeyFromDisk(location string) *rsa.PublicKey { + keyData, e := ioutil.ReadFile(location) + if e != nil { + panic(e.Error()) + } + key, e := jwt.ParseRSAPublicKeyFromPEM(keyData) + if e != nil { + panic(e.Error()) + } + return key +} + +func MakeSampleToken(c jwt.MapClaims, key interface{}) string { + token := jwt.NewWithClaims(jwt.SigningMethodRS256, c) + s, e := token.SignedString(key) + + if e != nil { + panic(e.Error()) + } + + return s +}