jwt_test.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package jwtwrapper
  2. import (
  3. "github.com/dgrijalva/jwt-go"
  4. "reflect"
  5. "testing"
  6. "time"
  7. )
  8. func Test_JwtGenToken(t *testing.T) {
  9. SetSecret("12345678abcdefg")
  10. type args struct {
  11. id string
  12. issuer string
  13. subject string
  14. seconds time.Duration
  15. }
  16. tests := []struct {
  17. name string
  18. args args
  19. want string
  20. wantErr bool
  21. }{
  22. {
  23. name:"Test_JwtGenToken",
  24. args:args{
  25. id:"1",
  26. issuer:"ycl",
  27. subject:"ycl",
  28. seconds:60*time.Second,
  29. },
  30. want:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1ODY1Njk0NTgsImp0aSI6IjEiLCJpc3MiOiJ5Y2wiLCJzdWIiOiJ5Y2wifQ.Sl4QXE_DrNX8JmF_TSl9atorkLys64Dvss_bdsAlCe8",
  31. wantErr:false,
  32. },
  33. }
  34. for _, tt := range tests {
  35. t.Run(tt.name, func(t *testing.T) {
  36. got, err := GenToken(tt.args.id, tt.args.issuer, tt.args.subject, tt.args.seconds)
  37. if (err != nil) != tt.wantErr {
  38. t.Errorf("GenToken() error = %v, wantErr %v", err, tt.wantErr)
  39. return
  40. }
  41. if got != tt.want {
  42. t.Errorf("GenToken() got = %v, want %v", got, tt.want)
  43. }
  44. })
  45. }
  46. }
  47. func Test_JwtParseToken(t *testing.T) {
  48. SetSecret("12345678abcdefg")
  49. add := time.Now().Add(60*time.Second).Unix()
  50. token, _ := GenToken("1","ycl","ycl",60*time.Second)
  51. type args struct {
  52. token string
  53. }
  54. tests := []struct {
  55. name string
  56. args args
  57. want *jwt.StandardClaims
  58. wantErr bool
  59. }{
  60. {
  61. name:"Test_JwtParseToken",
  62. args:args{
  63. token:token,
  64. },
  65. want:&jwt.StandardClaims{
  66. Audience:"",
  67. ExpiresAt:add,
  68. Id:"1",
  69. IssuedAt:0,
  70. Issuer:"ycl",
  71. NotBefore:0,
  72. Subject:"ycl",
  73. },
  74. wantErr:false,
  75. },
  76. }
  77. for _, tt := range tests {
  78. t.Run(tt.name, func(t *testing.T) {
  79. got, err := ParseToken(tt.args.token)
  80. if (err != nil) != tt.wantErr {
  81. t.Errorf("ParseToken() error = %v, wantErr %v", err, tt.wantErr)
  82. return
  83. }
  84. if !reflect.DeepEqual(got, tt.want) {
  85. t.Errorf("ParseToken() got = %v, want %v", got, tt.want)
  86. }
  87. })
  88. }
  89. }