88 lines
2.0 KiB
Go
88 lines
2.0 KiB
Go
package handler
|
|
|
|
import (
|
|
"encoding/json"
|
|
"net/http/httptest"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/golang-jwt/jwt/v5"
|
|
)
|
|
|
|
func TestHealth(t *testing.T) {
|
|
r := gin.New()
|
|
r.GET("/health", Health)
|
|
|
|
req := httptest.NewRequest("GET", "/health", nil)
|
|
w := httptest.NewRecorder()
|
|
r.ServeHTTP(w, req)
|
|
if w.Code != 200 {
|
|
t.Fatalf("expected 200 got %d", w.Code)
|
|
}
|
|
var body map[string]string
|
|
if err := json.NewDecoder(w.Body).Decode(&body); err != nil {
|
|
t.Fatalf("decode: %v", err)
|
|
}
|
|
if body["status"] != "ok" {
|
|
t.Fatalf("unexpected body: %#v", body)
|
|
}
|
|
}
|
|
|
|
func TestHello(t *testing.T) {
|
|
r := gin.New()
|
|
r.GET("/hello", Hello)
|
|
|
|
req := httptest.NewRequest("GET", "/hello", nil)
|
|
w := httptest.NewRecorder()
|
|
r.ServeHTTP(w, req)
|
|
if w.Code != 200 {
|
|
t.Fatalf("expected 200 got %d", w.Code)
|
|
}
|
|
var body map[string]string
|
|
if err := json.NewDecoder(w.Body).Decode(&body); err != nil {
|
|
t.Fatalf("decode: %v", err)
|
|
}
|
|
if body["message"] == "" {
|
|
t.Fatalf("unexpected body: %#v", body)
|
|
}
|
|
}
|
|
|
|
func TestLoginAndProtected(t *testing.T) {
|
|
secret := "testsecret"
|
|
// create token
|
|
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
|
|
"sub": "tester",
|
|
"exp": time.Now().Add(time.Hour).Unix(),
|
|
})
|
|
signed, err := token.SignedString([]byte(secret))
|
|
if err != nil {
|
|
t.Fatalf("sign token: %v", err)
|
|
}
|
|
|
|
// test protected route
|
|
r := gin.New()
|
|
// use middleware inline for test
|
|
r.Use(func(c *gin.Context) {
|
|
c.Request.Header.Set("Authorization", "Bearer "+signed)
|
|
})
|
|
r.GET("/protected", func(c *gin.Context) {
|
|
c.Set("claims", jwt.MapClaims{"sub": "tester"})
|
|
Protected(c)
|
|
})
|
|
|
|
req := httptest.NewRequest("GET", "/protected", nil)
|
|
w := httptest.NewRecorder()
|
|
r.ServeHTTP(w, req)
|
|
if w.Code != 200 {
|
|
t.Fatalf("expected 200 got %d", w.Code)
|
|
}
|
|
var body map[string]interface{}
|
|
if err := json.NewDecoder(w.Body).Decode(&body); err != nil {
|
|
t.Fatalf("decode: %v", err)
|
|
}
|
|
if body["claims"] == nil {
|
|
t.Fatalf("expected claims in response")
|
|
}
|
|
}
|