test: add tests for middleware
All checks were successful
/ build-and-push-image (push) Successful in 37s

This commit is contained in:
log101 2024-06-13 13:56:27 +03:00
parent 464d93a99f
commit 1f76bb7f1a
3 changed files with 69 additions and 3 deletions

View File

@ -64,7 +64,6 @@ func TestPostEmojiForm(t *testing.T) {
assert.Equal(t, http.StatusOK, w.Code)
assert.Contains(t, w.Body.String(), "👍  1")
assert.Contains(t, w.Body.String(), "😑")
}
func TestPostEmojiFormMissingParams(t *testing.T) {

View File

@ -33,14 +33,14 @@ func anonymizeIP(ip string) string {
return ip
}
return ipPrefix.Masked().String()
return ipPrefix.Masked().Addr().String()
} else if parsedIP.Is6() {
// Mask the last 80 bits for IPv6
ipPrefix, err := parsedIP.Prefix(48)
if err != nil {
return ip
}
return ipPrefix.Masked().String()
return ipPrefix.Masked().Addr().String()
}
// If it's neither IPv4 nor IPv6, return the original IP

View File

@ -0,0 +1,67 @@
package middleware
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
)
func TestAnonymizeIPMiddlewareIPv4(t *testing.T) {
gin.SetMode(gin.TestMode)
r := gin.New()
r.Use(AnonymizeIPMiddleware())
r.GET("/test", func(c *gin.Context) {
c.String(http.StatusOK, "OK")
})
req, _ := http.NewRequest(http.MethodGet, "/test", nil)
req.RemoteAddr = "192.168.1.1:1234"
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code)
assert.Equal(t, "192.168.1.0", req.RemoteAddr)
}
func TestAnonymizeIPMiddlewareIPv6(t *testing.T) {
gin.SetMode(gin.TestMode)
r := gin.New()
r.Use(AnonymizeIPMiddleware())
r.GET("/test", func(c *gin.Context) {
c.String(http.StatusOK, "OK")
})
req, _ := http.NewRequest(http.MethodGet, "/test", nil)
req.RemoteAddr = "[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:1234"
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code)
assert.Equal(t, "2001:db8:85a3::", req.RemoteAddr)
}
func TestAnonymizeIP(t *testing.T) {
tests := []struct {
name string
ip string
expected string
}{
{"IPv4", "192.168.1.1", "192.168.1.0"},
{"IPv6", "2001:0db8:85a3:0000:0000:8a2e:0370:7334", "2001:db8:85a3::"},
{"InvalidIP", "invalid_ip", "invalid_ip"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := anonymizeIP(tt.ip)
assert.Equal(t, tt.expected, result)
})
}
}