~tsileo/blobsfile

ref: 76a89107299fb76b273d92e13602ab1822aa4f76 blobsfile/index_test.go -rw-r--r-- 2.4 KiB
76a89107Thomas Sileo Bugfixes 2 years ago
                                                                                
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package blobsfile

import (
	"fmt"
	"os"
	"sync"
	"testing"

	"golang.org/x/crypto/blake2b"
)

func TestBlobsIndexBasic(t *testing.T) {
	index, err := newIndex("tmp_test_index")
	check(err)
	defer index.Close()
	defer os.RemoveAll("tmp_test_index")

	bp := &blobPos{n: 1, offset: 5, size: 10, blobSize: 10}
	h := fmt.Sprintf("%x", blake2b.Sum256([]byte("fakehash")))
	err = index.setPos(h, bp)
	check(err)
	bp3, err := index.getPos(h)
	if bp.n != bp3.n || bp.offset != bp3.offset || bp.size != bp3.size || bp.blobSize != bp3.blobSize {
		t.Errorf("index.GetPos error, expected:%q, got:%q", bp, bp3)
	}

	err = index.setN(5)
	check(err)
	n2, err := index.getN()
	check(err)
	if n2 != 5 {
		t.Errorf("Error GetN, got %v, expected 5", n2)
	}
	err = index.setN(100)
	check(err)
	n2, err = index.getN()
	check(err)
	if n2 != 100 {
		t.Errorf("Error GetN, got %v, expected 100", n2)
	}
}

func TestBlobsIndex(t *testing.T) {
	index, err := newIndex("tmp_test_index")
	check(err)
	defer index.Close()
	defer os.RemoveAll("tmp_test_index")
	var wg sync.WaitGroup
	var mu sync.Mutex
	expected := map[string]*blobPos{}
	for i := 0; i < 50000; i++ {
		wg.Add(1)
		go func(i int) {
			defer wg.Done()
			data := fmt.Sprintf("fakehash %d", i)
			h := fmt.Sprintf("%x", blake2b.Sum256([]byte(data)))
			bp := &blobPos{n: 1, offset: 100, size: len(data), blobSize: len(data)}
			if err := index.setPos(h, bp); err != nil {
				panic(fmt.Errorf("failed to index.setPos a i=%d: %v", i, err))
			}
			mu.Lock()
			expected[h] = bp
			mu.Unlock()
		}(i)
	}

	wg.Wait()

	for h, ebp := range expected {
		bp, err := index.getPos(h)
		if err != nil {
			panic(fmt.Errorf("failed to index.getPos(\"%s\"): %v", h, err))
		}
		if bp.n != ebp.n || bp.offset != ebp.offset || bp.size != ebp.size || bp.blobSize != ebp.blobSize {
			t.Errorf("index.getPos error, expected:%q, got:%q", bp, ebp)
		}
	}
}

func BenchmarkBlobsIndex(b *testing.B) {
	index, err := newIndex("tmp_test_index")
	check(err)
	defer index.Close()
	defer os.RemoveAll("tmp_test_index")
	b.ResetTimer()
	b.StopTimer()
	for i := 0; i < b.N; i++ {
		b.StopTimer()
		data := fmt.Sprintf("fakehash %d", i)
		h := fmt.Sprintf("%x", blake2b.Sum256([]byte(data)))
		bp := &blobPos{n: 1, offset: int64(100 + (i * len(data))), size: len(data), blobSize: len(data)}
		b.StartTimer()
		if err := index.setPos(h, bp); err != nil {
			panic(fmt.Errorf("failed to index.setPos a i=%d: %v", i, err))
		}
		b.StopTimer()
	}
}