56 lines
1.7 KiB
Go
56 lines
1.7 KiB
Go
package blacktip
|
|
|
|
import "testing"
|
|
|
|
func TestClientIP(t *testing.T) {
|
|
for in, want := range map[string]string{
|
|
"203.0.113.9:5000": "203.0.113.9",
|
|
"[2001:db8::1]:443": "2001:db8::1",
|
|
"[::ffff:192.0.2.7]:1": "192.0.2.7",
|
|
"198.51.100.2": "198.51.100.2", // no port, as Traefik reports it
|
|
"[fe80::1%eth0]:80": "fe80::1",
|
|
"not an address": "",
|
|
"": "",
|
|
} {
|
|
if got := clientIP(in); got != want {
|
|
t.Errorf("clientIP(%q) = %q, want %q", in, got, want)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestStatsTakeAndRestore(t *testing.T) {
|
|
ms := &mapState{}
|
|
ms.record("203.0.113.1:1000", 1, 100, 400)
|
|
ms.record("203.0.113.1:1001", 1, 10, 40)
|
|
ms.record("203.0.113.2:2000", 1, 5, 5)
|
|
ms.record("garbage", 1, 1, 1) // counted in the totals but not named
|
|
|
|
st, any := ms.takeStats()
|
|
if !any || st.Conns != 4 || st.BytesIn != 116 || st.BytesOut != 446 {
|
|
t.Fatalf("totals: %+v", st)
|
|
}
|
|
if len(st.Sources) != 2 || st.Sources[0].IP != "203.0.113.1" || st.Sources[0].Conns != 2 || st.Sources[0].BytesOut != 440 {
|
|
t.Fatalf("sources: %+v", st.Sources)
|
|
}
|
|
if _, any := ms.takeStats(); any {
|
|
t.Fatal("counters were not reset")
|
|
}
|
|
|
|
ms.record("203.0.113.1:1", 1, 1, 1) // traffic that arrived before the failed report was retried
|
|
ms.restoreStats(st)
|
|
again, _ := ms.takeStats()
|
|
if again.Conns != 5 || again.BytesIn != 117 || again.Sources[0].Conns != 3 {
|
|
t.Fatalf("after restore: %+v", again)
|
|
}
|
|
}
|
|
|
|
func TestSourceTableIsBounded(t *testing.T) {
|
|
var tb sourceTable
|
|
for i := 0; i < maxTrackedSources+50; i++ {
|
|
tb.add(string(rune('a'+i%26))+"."+string(rune('0'+i/26%10))+"."+string(rune(i)), 1, 1, 1)
|
|
}
|
|
if n := len(tb.take()); n > maxTrackedSources {
|
|
t.Fatalf("tracked %d addresses", n)
|
|
}
|
|
}
|