2023-01-27 21:37:20 +00:00
|
|
|
// Copyright (c) Tailscale Inc & AUTHORS
|
|
|
|
// SPDX-License-Identifier: BSD-3-Clause
|
2021-01-11 20:46:45 +00:00
|
|
|
|
|
|
|
package flowtrack
|
|
|
|
|
|
|
|
import (
|
2022-07-26 03:55:44 +00:00
|
|
|
"net/netip"
|
2021-01-11 20:46:45 +00:00
|
|
|
"testing"
|
|
|
|
|
2021-10-27 23:21:44 +00:00
|
|
|
"tailscale.com/tstest"
|
2021-01-11 20:46:45 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
func TestCache(t *testing.T) {
|
2023-01-11 21:45:34 +00:00
|
|
|
c := &Cache[int]{MaxEntries: 2}
|
2021-01-11 20:46:45 +00:00
|
|
|
|
2022-07-26 03:55:44 +00:00
|
|
|
k1 := Tuple{Src: netip.MustParseAddrPort("1.1.1.1:1"), Dst: netip.MustParseAddrPort("1.1.1.1:1")}
|
|
|
|
k2 := Tuple{Src: netip.MustParseAddrPort("1.1.1.1:1"), Dst: netip.MustParseAddrPort("2.2.2.2:2")}
|
|
|
|
k3 := Tuple{Src: netip.MustParseAddrPort("1.1.1.1:1"), Dst: netip.MustParseAddrPort("3.3.3.3:3")}
|
|
|
|
k4 := Tuple{Src: netip.MustParseAddrPort("1.1.1.1:1"), Dst: netip.MustParseAddrPort("4.4.4.4:4")}
|
2021-01-11 20:46:45 +00:00
|
|
|
|
|
|
|
wantLen := func(want int) {
|
|
|
|
t.Helper()
|
|
|
|
if got := c.Len(); got != want {
|
|
|
|
t.Fatalf("Len = %d; want %d", got, want)
|
|
|
|
}
|
|
|
|
}
|
2023-01-11 21:45:34 +00:00
|
|
|
wantVal := func(key Tuple, want int) {
|
2021-01-11 20:46:45 +00:00
|
|
|
t.Helper()
|
|
|
|
got, ok := c.Get(key)
|
|
|
|
if !ok {
|
|
|
|
t.Fatalf("Get(%q) failed; want value %v", key, want)
|
|
|
|
}
|
2023-01-11 21:45:34 +00:00
|
|
|
if *got != want {
|
2021-01-11 20:46:45 +00:00
|
|
|
t.Fatalf("Get(%q) = %v; want %v", key, got, want)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
wantMissing := func(key Tuple) {
|
|
|
|
t.Helper()
|
|
|
|
if got, ok := c.Get(key); ok {
|
|
|
|
t.Fatalf("Get(%q) = %v; want absent from cache", key, got)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
wantLen(0)
|
|
|
|
c.RemoveOldest() // shouldn't panic
|
|
|
|
c.Remove(k4) // shouldn't panic
|
|
|
|
|
|
|
|
c.Add(k1, 1)
|
|
|
|
wantLen(1)
|
|
|
|
c.Add(k2, 2)
|
|
|
|
wantLen(2)
|
|
|
|
c.Add(k3, 3)
|
|
|
|
wantLen(2) // hit the max
|
|
|
|
|
|
|
|
wantMissing(k1)
|
|
|
|
c.Remove(k1)
|
|
|
|
wantLen(2) // no change; k1 should've been the deleted one per LRU
|
|
|
|
|
|
|
|
wantVal(k3, 3)
|
|
|
|
|
|
|
|
wantVal(k2, 2)
|
|
|
|
c.Remove(k2)
|
|
|
|
wantLen(1)
|
|
|
|
wantMissing(k2)
|
|
|
|
|
|
|
|
c.Add(k3, 30)
|
|
|
|
wantVal(k3, 30)
|
|
|
|
wantLen(1)
|
|
|
|
|
2021-10-27 23:21:44 +00:00
|
|
|
err := tstest.MinAllocsPerRun(t, 0, func() {
|
2021-01-11 20:46:45 +00:00
|
|
|
got, ok := c.Get(k3)
|
|
|
|
if !ok {
|
|
|
|
t.Fatal("missing k3")
|
|
|
|
}
|
2023-01-11 21:45:34 +00:00
|
|
|
if *got != 30 {
|
2021-01-11 20:46:45 +00:00
|
|
|
t.Fatalf("got = %d; want 30", got)
|
|
|
|
}
|
2021-10-27 23:21:44 +00:00
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
t.Error(err)
|
2021-01-11 20:46:45 +00:00
|
|
|
}
|
|
|
|
}
|