fork of https://github.com/sourcegraph/zoekt
1package index
2
3import (
4 "strconv"
5 "testing"
6)
7
8func TestDocMatchTreeCache_Basic(t *testing.T) {
9 cache := newDocMatchTreeCache(2)
10
11 mt1 := &docMatchTree{}
12 mt2 := &docMatchTree{}
13 mt3 := &docMatchTree{}
14
15 // Add and Get
16 cache.Add("f1", "v1", mt1)
17 cache.Add("f2", "v2", mt2)
18 if v, ok := cache.Get("f1", "v1"); !ok || v != mt1 {
19 t.Errorf("expected mt1, got %v", v)
20 }
21 if v, ok := cache.Get("f2", "v2"); !ok || v != mt2 {
22 t.Errorf("expected mt2, got %v", v)
23 }
24
25 // Add triggers eviction (random, so one of the two should be evicted)
26 cache.Add("f3", "v3", mt3)
27 v1, ok1 := cache.Get("f1", "v1")
28 v2, ok2 := cache.Get("f2", "v2")
29 v3, ok3 := cache.Get("f3", "v3")
30
31 // Should have exactly 2 items
32 present := 0
33 if ok1 {
34 present++
35 if v1 != mt1 {
36 t.Errorf("expected mt1, got %v", v1)
37 }
38 }
39 if ok2 {
40 present++
41 if v2 != mt2 {
42 t.Errorf("expected mt2, got %v", v2)
43 }
44 }
45 if ok3 {
46 present++
47 if v3 != mt3 {
48 t.Errorf("expected mt3, got %v", v3)
49 }
50 }
51 if present != 2 {
52 t.Errorf("expected exactly 2 items in cache, got %d", present)
53 }
54}
55
56func TestDocMatchTreeCache_Concurrent(t *testing.T) {
57 cache := newDocMatchTreeCache(100)
58
59 // Create some test data
60 trees := make([]*docMatchTree, 50)
61 for i := range trees {
62 trees[i] = &docMatchTree{}
63 }
64
65 // Start multiple goroutines doing concurrent reads and writes
66 const numGoroutines = 10
67 const numOperations = 1000
68
69 done := make(chan bool, numGoroutines)
70
71 // Reader goroutines (should be majority of operations)
72 for i := 0; i < numGoroutines-1; i++ {
73 go func(id int) {
74 for j := 0; j < numOperations; j++ {
75 field := "field" + strconv.Itoa(j%10)
76 value := "value" + strconv.Itoa(j%20)
77 cache.Get(field, value)
78 }
79 done <- true
80 }(i)
81 }
82
83 // Writer goroutine (fewer write operations)
84 go func() {
85 for j := 0; j < numOperations/10; j++ {
86 field := "field" + strconv.Itoa(j%10)
87 value := "value" + strconv.Itoa(j%20)
88 tree := trees[j%len(trees)]
89 cache.Add(field, value, tree)
90 }
91 done <- true
92 }()
93
94 // Wait for all goroutines to complete
95 for i := 0; i < numGoroutines; i++ {
96 <-done
97 }
98}