-
Notifications
You must be signed in to change notification settings - Fork 894
/
testing.go
78 lines (67 loc) · 2.02 KB
/
testing.go
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
package sharetest
import (
"bytes"
"math/rand"
"sort"
"sync"
"time"
"github.com/stretchr/testify/require"
"github.com/celestiaorg/celestia-app/pkg/namespace"
"github.com/celestiaorg/celestia-node/share"
)
// RandShares generate 'total' amount of shares filled with random data. It uses require.TestingT
// to be able to take both a *testing.T and a *testing.B.
func RandShares(t require.TestingT, total int) []share.Share {
if total&(total-1) != 0 {
t.Errorf("total must be power of 2: %d", total)
t.FailNow()
}
shares := make([]share.Share, total)
for i := range shares {
shr := make([]byte, share.Size)
copy(share.GetNamespace(shr), RandV0Namespace())
rndMu.Lock()
_, err := rnd.Read(share.GetData(shr))
rndMu.Unlock()
require.NoError(t, err)
shares[i] = shr
}
sort.Slice(shares, func(i, j int) bool { return bytes.Compare(shares[i], shares[j]) < 0 })
return shares
}
// RandSharesWithNamespace is same the as RandShares, but sets same namespace for all shares.
func RandSharesWithNamespace(t require.TestingT, namespace share.Namespace, total int) []share.Share {
if total&(total-1) != 0 {
t.Errorf("total must be power of 2: %d", total)
t.FailNow()
}
shares := make([]share.Share, total)
rnd := rand.New(rand.NewSource(time.Now().Unix())) //nolint:gosec
for i := range shares {
shr := make([]byte, share.Size)
copy(share.GetNamespace(shr), namespace)
_, err := rnd.Read(share.GetData(shr))
require.NoError(t, err)
shares[i] = shr
}
sort.Slice(shares, func(i, j int) bool { return bytes.Compare(shares[i], shares[j]) < 0 })
return shares
}
// RandV0Namespace generates random valid data namespace for testing purposes.
func RandV0Namespace() share.Namespace {
rb := make([]byte, namespace.NamespaceVersionZeroIDSize)
rndMu.Lock()
rnd.Read(rb)
rndMu.Unlock()
for {
namespace, _ := share.NewBlobNamespaceV0(rb)
if err := namespace.ValidateForData(); err != nil {
continue
}
return namespace
}
}
var (
rnd = rand.New(rand.NewSource(time.Now().Unix())) //nolint:gosec
rndMu sync.Mutex
)