Debian Codegraph @

src/merger_test.go

raw
1 package fzf
2
3 import (
4 "fmt"
5 "math/rand"
6 "sort"
7 "testing"
8
9 "github.com/junegunn/fzf/src/util"
10 )
11
12 func assert(t *testing.T, cond bool, msg ...string) {
13 if !cond {
14 t.Error(msg)
15 }
16 }
17
18 func randResult() Result {
19 str := fmt.Sprintf("%d", rand.Uint32())
20 chars := util.ToChars([]byte(str))
21 chars.Index = rand.Int31()
22 return Result{item: &Item{text: chars}}
23 }
24
25 func TestEmptyMerger(t *testing.T) {
26 r := revision{}
27 assert(t, EmptyMerger(r).Length() == 0, "Not empty")
28 assert(t, EmptyMerger(r).count == 0, "Invalid count")
29 assert(t, len(EmptyMerger(r).lists) == 0, "Invalid lists")
30 assert(t, len(EmptyMerger(r).merged) == 0, "Invalid merged list")
31 }
32
33 func buildLists(partiallySorted bool) ([][]Result, []Result) {
34 numLists := 4
35 lists := make([][]Result, numLists)
36 cnt := 0
37 for i := range numLists {
38 numResults := rand.Int() % 20
39 cnt += numResults
40 lists[i] = make([]Result, numResults)
41 for j := range numResults {
42 item := randResult()
43 lists[i][j] = item
44 }
45 if partiallySorted {
46 sort.Sort(ByRelevance(lists[i]))
47 }
48 }
49 items := []Result{}
50 for _, list := range lists {
51 items = append(items, list...)
52 }
53 return lists, items
54 }
55
56 func TestMergerUnsorted(t *testing.T) {
57 lists, _ := buildLists(false)
58
59 // Sort each list by index to simulate real worker behavior
60 // (workers process chunks in ascending order via nextChunk.Add(1))
61 for _, list := range lists {
62 sort.Slice(list, func(i, j int) bool {
63 return list[i].item.Index() < list[j].item.Index()
64 })
65 }
66 items := []Result{}
67 for _, list := range lists {
68 items = append(items, list...)
69 }
70 sort.Slice(items, func(i, j int) bool {
71 return items[i].item.Index() < items[j].item.Index()
72 })
73 cnt := len(items)
74
75 // Not sorted: items in ascending index order
76 mg := NewMerger(nil, lists, false, false, revision{}, 0, 0)
77 assert(t, cnt == mg.Length(), "Invalid Length")
78 for i := range cnt {
79 assert(t, items[i] == mg.Get(i), "Invalid Get")
80 }
81 }
82
83 func TestMergerSorted(t *testing.T) {
84 lists, items := buildLists(true)
85 cnt := len(items)
86
87 // Sorted sorted order
88 mg := NewMerger(nil, lists, true, false, revision{}, 0, 0)
89 assert(t, cnt == mg.Length(), "Invalid Length")
90 sort.Sort(ByRelevance(items))
91 for i := range cnt {
92 if items[i] != mg.Get(i) {
93 t.Error("Not sorted", items[i], mg.Get(i))
94 }
95 }
96
97 // Inverse order
98 mg2 := NewMerger(nil, lists, true, false, revision{}, 0, 0)
99 for i := cnt - 1; i >= 0; i-- {
100 if items[i] != mg2.Get(i) {
101 t.Error("Not sorted", items[i], mg2.Get(i))
102 }
103 }
104 }