Files

46 lines
1.2 KiB
Go

package auth
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
)
func status(t *testing.T, configured, provided string) int {
t.Setenv("ADMIN_TOKEN", configured)
gin.SetMode(gin.TestMode)
r := gin.New()
r.POST("/admin", AdminAuth(), func(c *gin.Context) { c.Status(http.StatusOK) })
req := httptest.NewRequest(http.MethodPost, "/admin", nil)
if provided != "" {
req.Header.Set("X-Admin-Token", provided)
}
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
return w.Code
}
func TestAdminAuth(t *testing.T) {
cases := []struct {
name, configured, provided string
want int
}{
{"no token configured refuses requests without a header", "", "", http.StatusUnauthorized},
{"no token configured refuses any header", "", "anything", http.StatusUnauthorized},
{"wrong token", "secret", "nope", http.StatusUnauthorized},
{"missing header", "secret", "", http.StatusUnauthorized},
{"correct token", "secret", "secret", http.StatusOK},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
if got := status(t, tc.configured, tc.provided); got != tc.want {
t.Fatalf("got %d, want %d", got, tc.want)
}
})
}
}