carlos / platform Public

Clone
git clone https://amadan.net/carlos/platform

Plain git — no account needed to clone.

Download

Download this file

1package analytics
2
3import "testing"
4
5func TestTopKExactBelowCapAndBoundedAbove(t *testing.T) {
6 k := NewTopK()
7 for i := 0; i < 100; i++ {
8 k.Add("/p"+itoa(i), int64(i+1))
9 }
10 f := k.Fold()
11 if len(f) != 100 || f["/p99"] != 100 || k.Approximate() {
12 t.Fatalf("below cap must be exact: len=%d p99=%d approx=%v", len(f), f["/p99"], k.Approximate())
13 }
14 for i := 0; i < 2000; i++ {
15 k.Add("/q"+itoa(i), 1)
16 }
17 f = k.Fold()
18 if len(f) > TopKSize+1 || !k.Approximate() || f[OtherKey] == 0 {
19 t.Fatalf("above cap: len=%d approx=%v other=%d", len(f), k.Approximate(), f[OtherKey])
20 }
21 // Total mass is conserved between counters and _other.
22 var total int64
23 for _, v := range f {
24 total += v
25 }
26 if total != 100*101/2+2000 {
27 t.Fatalf("mass %d", total)
28 }
29 // A heavy hitter survives.
30 if f["/p99"] < 100-2000/TopKSize {
31 t.Fatalf("heavy hitter undercounted: %d", f["/p99"])
32 }
33}
34
35func TestTopKMergeRefolds(t *testing.T) {
36 a, b := NewTopK(), NewTopK()
37 for i := 0; i < 400; i++ {
38 a.Add("/a"+itoa(i), 2)
39 b.Add("/b"+itoa(i), 3)
40 }
41 a.Merge(b)
42 f := a.Fold()
43 if len(f) > TopKSize+1 || f[OtherKey] == 0 {
44 t.Fatalf("merged 800 keys must fold to ≤501: %d", len(f))
45 }
46 r := TopKFrom(f)
47 if r.other != f[OtherKey] || len(r.counts) != len(f)-1 {
48 t.Fatal("TopKFrom must invert Fold")
49 }
50 long := NewTopK()
51 long.Add(string(make([]byte, 300)), 1)
52 for key := range long.Fold() {
53 if len(key) > MaxKeyLen {
54 t.Fatal("keys must be capped at 256 bytes")
55 }
56 }
57}
58