github.com/sunrise-zone/sunrise-node@v0.13.1-sr2/share/sharetest/testing.go (about) 1 package sharetest 2 3 import ( 4 "bytes" 5 "math/rand" 6 "sort" 7 "sync" 8 "time" 9 10 "github.com/stretchr/testify/require" 11 12 "github.com/sunrise-zone/sunrise-app/pkg/namespace" 13 14 "github.com/sunrise-zone/sunrise-node/share" 15 ) 16 17 // RandShares generate 'total' amount of shares filled with random data. It uses require.TestingT 18 // to be able to take both a *testing.T and a *testing.B. 19 func RandShares(t require.TestingT, total int) []share.Share { 20 if total&(total-1) != 0 { 21 t.Errorf("total must be power of 2: %d", total) 22 t.FailNow() 23 } 24 25 shares := make([]share.Share, total) 26 for i := range shares { 27 shr := make([]byte, share.Size) 28 copy(share.GetNamespace(shr), RandV0Namespace()) 29 rndMu.Lock() 30 _, err := rnd.Read(share.GetData(shr)) 31 rndMu.Unlock() 32 require.NoError(t, err) 33 shares[i] = shr 34 } 35 sort.Slice(shares, func(i, j int) bool { return bytes.Compare(shares[i], shares[j]) < 0 }) 36 37 return shares 38 } 39 40 // RandSharesWithNamespace is same the as RandShares, but sets same namespace for all shares. 41 func RandSharesWithNamespace(t require.TestingT, namespace share.Namespace, total int) []share.Share { 42 if total&(total-1) != 0 { 43 t.Errorf("total must be power of 2: %d", total) 44 t.FailNow() 45 } 46 47 shares := make([]share.Share, total) 48 rnd := rand.New(rand.NewSource(time.Now().Unix())) //nolint:gosec 49 for i := range shares { 50 shr := make([]byte, share.Size) 51 copy(share.GetNamespace(shr), namespace) 52 _, err := rnd.Read(share.GetData(shr)) 53 require.NoError(t, err) 54 shares[i] = shr 55 } 56 sort.Slice(shares, func(i, j int) bool { return bytes.Compare(shares[i], shares[j]) < 0 }) 57 return shares 58 } 59 60 // RandV0Namespace generates random valid data namespace for testing purposes. 61 func RandV0Namespace() share.Namespace { 62 rb := make([]byte, namespace.NamespaceVersionZeroIDSize) 63 rndMu.Lock() 64 rnd.Read(rb) 65 rndMu.Unlock() 66 for { 67 namespace, _ := share.NewBlobNamespaceV0(rb) 68 if err := namespace.ValidateForData(); err != nil { 69 continue 70 } 71 return namespace 72 } 73 } 74 75 var ( 76 rnd = rand.New(rand.NewSource(time.Now().Unix())) //nolint:gosec 77 rndMu sync.Mutex 78 )