Skip to content

Commit

Permalink
add unit tests
Browse files Browse the repository at this point in the history
  • Loading branch information
MakMuftic committed May 23, 2024
1 parent 68483cc commit 8f1a597
Show file tree
Hide file tree
Showing 2 changed files with 72 additions and 0 deletions.
18 changes: 18 additions & 0 deletions internal/auth/auth.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package auth

import (
"net/http"
)

func UrlTokenAuth(token string) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
authToken := r.URL.Query().Get("auth_token")
if authToken == "" || authToken != token {
w.WriteHeader(http.StatusUnauthorized)
return
}
next.ServeHTTP(w, r)
})
}
}
54 changes: 54 additions & 0 deletions internal/auth/auth_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package auth

import (
"net/http"
"net/http/httptest"
"testing"
)

func TestUrlTokenAuth(t *testing.T) {
validToken := "valid_token"
middleware := UrlTokenAuth(validToken)

tests := []struct {
name string
url string
expectedStatus int
}{
{
name: "Valid token",
url: "/?auth_token=valid_token",
expectedStatus: http.StatusOK,
},
{
name: "Invalid token",
url: "/?auth_token=invalid_token",
expectedStatus: http.StatusUnauthorized,
},
{
name: "Missing token",
url: "/",
expectedStatus: http.StatusUnauthorized,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
req, err := http.NewRequest("GET", tt.url, nil)
if err != nil {
t.Fatalf("could not create request: %v", err)
}

rr := httptest.NewRecorder()
handler := middleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}))

handler.ServeHTTP(rr, req)

if rr.Code != tt.expectedStatus {
t.Errorf("expected status %v; got %v", tt.expectedStatus, rr.Code)
}
})
}
}

0 comments on commit 8f1a597

Please sign in to comment.