package main
import (
"net"
"net/http/httptest"
"strings"
"testing"
)
func TestValidBranch(t *testing.T) {
for _, ok := range []string{"main", "feature/x", "v1.2", "a_b-c"} {
if !validBranch(ok) {
t.Errorf("%q rejected", ok)
}
}
for _, bad := range []string{"", "-x", "a..b", "a b", "a:b", "a~1", "a^", "x.lock", "a//b", "/a", "a/", ".a", "a/.b", "a@{1}", "@", "a\nb", "a\x00b", "a*", "a?", "a[", "a\\b"} {
if validBranch(bad) {
t.Errorf("%q accepted", bad)
}
}
}
func TestCleanPath(t *testing.T) {
cases := map[string]bool{"a/b.txt": true, "": true, "../x": false, "a/../b": false, "-rf": false, "a\nb": false, "a\x00": false, "a\tb": false, "a//b": false}
for in, want := range cases {
if _, got := cleanPath(in); got != want {
t.Errorf("cleanPath(%q) = %v", in, got)
}
}
}
func TestClientIP(t *testing.T) {
r := httptest.NewRequest("GET", "/", nil)
r.RemoteAddr = "203.0.113.9:4000"
r.Header.Set("X-Forwarded-For", "1.1.1.1")
if got := clientIP(r); got != "203.0.113.9" {
t.Errorf("direct client spoofed its address as %s", got)
}
r.RemoteAddr = "127.0.0.1:4000"
r.Header.Set("X-Forwarded-For", "6.6.6.6, 198.51.100.7")
if got := clientIP(r); got != "198.51.100.7" {
t.Errorf("proxied address %s, want the last hop", got)
}
}
func TestParseQuery(t *testing.T) {
text, quals := parseQuery(`kernel language:"Standard ML" user:~james tag:sel4`)
if text != "kernel" || quals["language"] != "Standard ML" || quals["user"] != "james" || quals["tag"] != "sel4" {
t.Errorf("got %q %v", text, quals)
}
if got := stripLanguage(`x lang:go tag:"a b"`); got != `x tag:"a b"` {
t.Errorf("stripLanguage = %q", got)
}
}
func TestBuckets(t *testing.T) {
b := newBuckets(0.001, 3)
for i := 0; i < 3; i++ {
if !b.allow("k") {
t.Fatal("burst refused early")
}
}
if b.allow("k") {
t.Error("bucket did not run dry")
}
if !b.allow("other") {
t.Error("keys are not independent")
}
}
func TestCappedBuffer(t *testing.T) {
var b cappedBuffer
if _, err := b.Write(make([]byte, maxOutput)); err != nil {
t.Fatal(err)
}
if _, err := b.Write([]byte{1}); err == nil || !b.over {
t.Error("cap not enforced")
}
}
func TestMarkdownSanitised(t *testing.T) {
s, _ := testServer(t)
for _, in := range []string{
``,
`
`,
`[x](javascript:alert(1))`,
`x`,
``,
``,
`