moved some of the test helpers into a shared location so they can be reused

This commit is contained in:
Dave Grijalva 2016-04-08 13:01:55 -07:00
parent bc13ee82c3
commit e3cd52238a
2 changed files with 50 additions and 32 deletions

View File

@ -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

42
test/helpers.go Normal file
View File

@ -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
}