Skip to content

Commit

Permalink
testing code coverage
Browse files Browse the repository at this point in the history
  • Loading branch information
nicobistolfi committed Sep 22, 2024
1 parent 4dfebe4 commit 1622d42
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 10 deletions.
2 changes: 0 additions & 2 deletions internal/api/middleware/rate_limiter.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package middleware

import (
"fmt"
"net/http"
"sync"

Expand Down Expand Up @@ -34,7 +33,6 @@ func RateLimiter(r rate.Limit, b int, keyPrefixes ...string) gin.HandlerFunc {
key = c.GetHeader("X-Forwarded-For")
}

fmt.Println("key", key)
if auth := c.GetHeader("Authorization"); auth != "" {
key += ":" + auth
}
Expand Down
9 changes: 3 additions & 6 deletions internal/api/middleware/token.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ func init() {

// Set cache expiry from environment variable or use default
cacheExpiryStr := os.Getenv("TOKEN_CACHE_EXPIRY")
fmt.Printf("Cache expiry: %v\n", cacheExpiryStr)
if cacheExpiryStr == "" {
cacheExpiry = 5 * time.Minute
} else {
Expand Down Expand Up @@ -59,7 +58,9 @@ func VerifyToken(customCacheExpiry ...string) gin.HandlerFunc {
if err != nil {
logger.Warn("Invalid cache expiry, using default", zap.Error(err))
} else {
fmt.Printf("Using custom cache expiry: %v\n", verifyCacheExpiryParsed)
verifyCacheExpiry = verifyCacheExpiryParsed
fmt.Printf("verifyCacheExpiry: %v\n", verifyCacheExpiry)
}
}
// Get the token from the context set by AuthMiddleware
Expand All @@ -85,6 +86,7 @@ func VerifyToken(customCacheExpiry ...string) gin.HandlerFunc {
}

tokenURL := os.Getenv("TOKEN_URL")
fmt.Printf("tokenURL: %v\n", tokenURL)

if tokenURL == "" {
c.JSON(http.StatusInternalServerError, gin.H{"error": "TOKEN_URL not set"})
Expand All @@ -97,11 +99,6 @@ func VerifyToken(customCacheExpiry ...string) gin.HandlerFunc {
entry, found := tokenCache[tokenString]
cacheMutex.RUnlock()

// print details of the entry and expiry times as well as the current time
fmt.Printf("Entry: %+v\n", entry)
fmt.Printf("Expiry: %v\n", entry.expiry)
fmt.Printf("Current time: %v\n", time.Now())

valid := time.Now().Before(entry.expiry)
fmt.Printf("Valid: %v\n", valid)

Expand Down
22 changes: 20 additions & 2 deletions internal/api/middleware/token_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,9 +81,17 @@ func TestVerifyToken(t *testing.T) {
func TestVerifyTokenCaching(t *testing.T) {
gin.SetMode(gin.TestMode)

callCount := 0
// Create a middleware to track call count
var callCount int
countMiddleware := func(c *gin.Context) {
if c.Writer.Header().Get("X-Token-Cache") == "MISS" {
callCount++
t.Logf("Mock server called. Count: %d", callCount)
}
c.Next()
}

mockServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
callCount++
profile := Profile{
ID: "123",
Email: "[email protected]",
Expand All @@ -106,6 +114,7 @@ func TestVerifyTokenCaching(t *testing.T) {
c.Next()
})
r.Use(VerifyToken(os.Getenv("TOKEN_CACHE_EXPIRY")))
r.Use(countMiddleware) // Add the count middleware
r.GET("/test", func(c *gin.Context) {
c.Status(http.StatusOK)
})
Expand All @@ -115,22 +124,31 @@ func TestVerifyTokenCaching(t *testing.T) {
req.Header.Set("Authorization", "Bearer valid_token")
resp := httptest.NewRecorder()
r.ServeHTTP(resp, req)
t.Logf("Request made. Status: %d", resp.Code)
}

t.Log("Making first request")
makeRequest() // First request, should call the mock server
if callCount != 1 {
t.Errorf("Expected 1 call to mock server, got %d", callCount)
}

// time.Sleep(100 * time.Millisecond) // Small delay

t.Log("Making second request")
makeRequest() // Second request, should use cache
if callCount != 1 {
t.Errorf("Expected still 1 call to mock server, got %d", callCount)
}

t.Log("Waiting for cache to expire")
time.Sleep(3 * time.Second) // Wait for cache to expire

t.Log("Making third request")
makeRequest() // Third request, should call the mock server again
if callCount != 2 {
t.Errorf("Expected 2 calls to mock server, got %d", callCount)
}

t.Logf("Final call count: %d", callCount)
}

0 comments on commit 1622d42

Please sign in to comment.