94 lines
2.1 KiB
Go
94 lines
2.1 KiB
Go
package reqctx
|
|
|
|
import (
|
|
"strings"
|
|
"testing"
|
|
)
|
|
|
|
func TestParseHTTPRealIP(t *testing.T) {
|
|
got := ParseHTTPRealIP(" 203.0.113.10 ", "198.51.100.1, 192.0.2.1", "192.0.2.1:1234")
|
|
if got != "203.0.113.10" {
|
|
t.Fatalf("x-real-ip %q", got)
|
|
}
|
|
got = ParseHTTPRealIP("", "198.51.100.1, 192.0.2.1", "192.0.2.1:1234")
|
|
if got != "198.51.100.1" {
|
|
t.Fatalf("xff %q", got)
|
|
}
|
|
got = ParseHTTPRealIP("", "", "192.0.2.1:1234")
|
|
if got != "192.0.2.1" {
|
|
t.Fatalf("remote %q", got)
|
|
}
|
|
}
|
|
|
|
func TestRealIPFromContext(t *testing.T) {
|
|
ctx := With(t.Context(), &RequestContext{RealIP: "203.0.113.10"})
|
|
if RealIP(ctx) != "203.0.113.10" {
|
|
t.Fatalf("got %q", RealIP(ctx))
|
|
}
|
|
if RealIP(t.Context()) != "" {
|
|
t.Fatal("empty ctx")
|
|
}
|
|
}
|
|
|
|
func TestNewIDLength(t *testing.T) {
|
|
id := NewID()
|
|
if len(id) != 11 {
|
|
t.Fatalf("len %d %q", len(id), id)
|
|
}
|
|
for i := 0; i < len(id); i++ {
|
|
if !strings.ContainsRune(base62Alphabet, rune(id[i])) {
|
|
t.Fatalf("char %q in %q", id[i], id)
|
|
}
|
|
}
|
|
if id == NewID() {
|
|
t.Fatal("not unique")
|
|
}
|
|
}
|
|
|
|
func TestNewObjectNameLength(t *testing.T) {
|
|
id := NewObjectName()
|
|
if len(id) != 16 {
|
|
t.Fatalf("len %d %q", len(id), id)
|
|
}
|
|
for i := 0; i < len(id); i++ {
|
|
if !strings.ContainsRune(base62Alphabet, rune(id[i])) {
|
|
t.Fatalf("char %q in %q", id[i], id)
|
|
}
|
|
}
|
|
if id == NewObjectName() {
|
|
t.Fatal("not unique")
|
|
}
|
|
}
|
|
|
|
func TestEncodeBase62(t *testing.T) {
|
|
if got := encodeBase62(0); got != "00000000000" {
|
|
t.Fatalf("%q", got)
|
|
}
|
|
if got := encodeBase62(61); got != "0000000000z" {
|
|
t.Fatalf("%q", got)
|
|
}
|
|
if got := encodeBase62(62); got != "00000000010" {
|
|
t.Fatalf("%q", got)
|
|
}
|
|
}
|
|
|
|
func TestRequestIDFromContext(t *testing.T) {
|
|
ctx := With(t.Context(), &RequestContext{RequestID: "abc"})
|
|
if RequestID(ctx) != "abc" {
|
|
t.Fatalf("got %q", RequestID(ctx))
|
|
}
|
|
if RequestID(t.Context()) != "" {
|
|
t.Fatal("empty ctx")
|
|
}
|
|
}
|
|
|
|
func TestLangFromContext(t *testing.T) {
|
|
ctx := With(t.Context(), &RequestContext{Language: "en-US"})
|
|
if Language(ctx) != "en" {
|
|
t.Fatalf("got %q", Language(ctx))
|
|
}
|
|
if Language(t.Context()) != "zh-CN" {
|
|
t.Fatalf("default %q", Language(t.Context()))
|
|
}
|
|
}
|