package middlewares import ( "bytes" "gosimplenpm/internal/config" "io" "net/http" "net/http/httptest" "testing" "github.com/gorilla/mux" "github.com/stretchr/testify/assert" ) func TestUnitMAuthMiddleware(t *testing.T) { router := mux.NewRouter() handlerStr := []byte("Logic\n") hFunc := func(w http.ResponseWriter, e *http.Request) { _, err := w.Write(handlerStr) if err != nil { t.Fatalf("Failed writing HTTP response: %v", err) } } cfg := config.Config{ RepoDir: "", Token: "MyToken", } router.HandleFunc("/", AuthMiddleware(cfg)(hFunc)) t.Run("return `Status Foribben` if there is no token", func(t *testing.T) { req := httptest.NewRequest(http.MethodGet, "/", nil) wrt := httptest.NewRecorder() req.Header.Set("Authorization", "") router.ServeHTTP(wrt, req) rs := wrt.Result() assert.Equal(t, rs.StatusCode, http.StatusForbidden) defer rs.Body.Close() body, err := io.ReadAll(rs.Body) if err != nil { t.Fatal(err) } bytes.TrimSpace(body) assert.Equal(t, string(body), "Authentication Error\n") }) t.Run("return `Status Foribben` if the Authorization field is not set properly", func(t *testing.T) { req := httptest.NewRequest(http.MethodGet, "/", nil) wrt := httptest.NewRecorder() req.Header.Set("Authorization", "Secret other") router.ServeHTTP(wrt, req) rs := wrt.Result() assert.Equal(t, rs.StatusCode, http.StatusForbidden) defer rs.Body.Close() body, err := io.ReadAll(rs.Body) if err != nil { t.Fatal(err) } bytes.TrimSpace(body) assert.Equal(t, string(body), "Authentication Error\n") }) t.Run("return `Status Foribben` if the token is incorrect", func(t *testing.T) { req := httptest.NewRequest(http.MethodGet, "/", nil) wrt := httptest.NewRecorder() req.Header.Set("Authorization", "Bearer incorrectToken") router.ServeHTTP(wrt, req) rs := wrt.Result() assert.Equal(t, rs.StatusCode, http.StatusForbidden) defer rs.Body.Close() body, err := io.ReadAll(rs.Body) if err != nil { t.Fatal(err) } bytes.TrimSpace(body) assert.Equal(t, string(body), "Authentication Error\n") }) }