Files
http_logger/request_test.go

59 lines
1.5 KiB
Go

package main
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
)
func TestGetRemoteAddr(t *testing.T) {
tests := []struct {
name string
set func(r *http.Request)
want string
}{
{"xff", func(r *http.Request) { r.Header.Set("X-Forwarded-For", "1.1.1.1, 2.2.2.2") }, "1.1.1.1"},
{"realip", func(r *http.Request) { r.Header.Set("X-Real-IP", "3.3.3.3") }, "3.3.3.3"},
{"remoteaddr", func(r *http.Request) { r.RemoteAddr = "4.4.4.4:5678" }, "4.4.4.4"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
r := httptest.NewRequest("GET", "/telegram", nil)
r.RemoteAddr = ""
tt.set(r)
if got := GetRemoteAddr(r); got != tt.want {
t.Fatalf("got %q want %q", got, tt.want)
}
})
}
}
func TestExtractRequest(t *testing.T) {
r := httptest.NewRequest("POST", "http://example.com/telegram?x=1", strings.NewReader("hello"))
r.Header.Set("X-Real-IP", "9.9.9.9")
data := ExtractRequest(r)
if data.Method != "POST" {
t.Errorf("method = %q", data.Method)
}
if data.RemoteAddr != "9.9.9.9" {
t.Errorf("remoteaddr = %q", data.RemoteAddr)
}
if data.Body != "hello" {
t.Errorf("body = %q", data.Body)
}
if data.URL != "/telegram?x=1" {
t.Errorf("url = %q", data.URL)
}
}
func TestExtractRequestBodyLimit(t *testing.T) {
big := strings.Repeat("a", 2000)
r := httptest.NewRequest("POST", "/telegram", strings.NewReader(big))
r.ContentLength = int64(len(big))
data := ExtractRequest(r)
if data.Body != "too long" {
t.Errorf("expected 'too long', got len %d", len(data.Body))
}
}