aboutsummaryrefslogtreecommitdiff
path: root/internal/kwcache/fuzz_test.go
blob: 8ac6c95de4f7dd901fec4ca269c9012bbe6cf70f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// SPDX-License-Identifier: GPL-3.0-or-later

package kwcache

import (
	"os"
	"path/filepath"
	"testing"
)

// FuzzLoad: a cache file of any content loads as a usable cache - never
// nil, never a panic - and one that reports an error answers nothing. Its
// answers can then be saved again.
func FuzzLoad(f *testing.F) {
	seed := New("fp")
	seed.Store(a, map[string]bool{"k:acme": true, "k:x": false})
	path := filepath.Join(f.TempDir(), "seed.cache")
	if err := seed.Save(path, []ID{a}, allKeys); err != nil {
		f.Fatal(err)
	}
	good, err := os.ReadFile(path)
	if err != nil {
		f.Fatal(err)
	}
	f.Add(good)
	f.Add([]byte(`{"version":1,"fingerprint":"fp","keywords":[["b","a"]],"files":[{"dev":1,"ino":10,"size":100,"mtime":1000,"keywords":0,"hits":[5]}]}`))
	f.Add([]byte(`{"version":1,"fingerprint":"fp","keywords":[],"files":[{"dev":1,"ino":10,"size":100,"mtime":1000,"keywords":-1,"hits":[]}]}`))
	f.Add([]byte("{}"))
	f.Add([]byte("null"))
	f.Fuzz(func(t *testing.T, data []byte) {
		p := filepath.Join(t.TempDir(), "dl.cache")
		if err := os.WriteFile(p, data, 0o600); err != nil {
			t.Fatal(err)
		}
		c, err := Load(p, "fp")
		if c == nil {
			t.Fatal("Load returned a nil cache")
		}
		hits, ok := c.Lookup(a, []string{"k:acme", "k:x"})
		if ok && len(hits) != 2 {
			t.Fatalf("Lookup answered %d of 2 keywords", len(hits))
		}
		if err != nil && ok {
			t.Fatalf("a cache that failed to load (%v) answered", err)
		}
		if err := c.Save(filepath.Join(t.TempDir(), "out.cache"), []ID{a, b}, allKeys); err != nil {
			t.Fatal(err)
		}
	})
}