github.com/516108736/tendermint@v0.36.0/libs/rand/random_test.go (about) 1 package rand 2 3 import ( 4 "bytes" 5 "encoding/json" 6 "fmt" 7 mrand "math/rand" 8 "sync" 9 "testing" 10 "time" 11 12 "github.com/stretchr/testify/assert" 13 ) 14 15 func TestRandStr(t *testing.T) { 16 l := 243 17 s := Str(l) 18 assert.Equal(t, l, len(s)) 19 } 20 21 func TestRandBytes(t *testing.T) { 22 l := 243 23 b := Bytes(l) 24 assert.Equal(t, l, len(b)) 25 } 26 27 func TestRandIntn(t *testing.T) { 28 n := 243 29 for i := 0; i < 100; i++ { 30 x := Intn(n) 31 assert.True(t, x < n) 32 } 33 } 34 35 // Test to make sure that we never call math.rand(). 36 // We do this by ensuring that outputs are deterministic. 37 func TestDeterminism(t *testing.T) { 38 var firstOutput string 39 40 // Set math/rand's seed for the sake of debugging this test. 41 // (It isn't strictly necessary). 42 mrand.Seed(1) 43 44 for i := 0; i < 100; i++ { 45 output := testThemAll() 46 if i == 0 { 47 firstOutput = output 48 } else if firstOutput != output { 49 t.Errorf("run #%d's output was different from first run.\nfirst: %v\nlast: %v", 50 i, firstOutput, output) 51 } 52 } 53 } 54 55 func testThemAll() string { 56 57 // Such determinism. 58 grand.reset(1) 59 60 // Use it. 61 out := new(bytes.Buffer) 62 perm := Perm(10) 63 blob, _ := json.Marshal(perm) 64 fmt.Fprintf(out, "perm: %s\n", blob) 65 fmt.Fprintf(out, "randInt: %d\n", Int()) 66 fmt.Fprintf(out, "randUint: %d\n", Uint()) 67 fmt.Fprintf(out, "randIntn: %d\n", Intn(97)) 68 fmt.Fprintf(out, "randInt31: %d\n", Int31()) 69 fmt.Fprintf(out, "randInt32: %d\n", Int32()) 70 fmt.Fprintf(out, "randInt63: %d\n", Int63()) 71 fmt.Fprintf(out, "randInt64: %d\n", Int64()) 72 fmt.Fprintf(out, "randUint32: %d\n", Uint32()) 73 fmt.Fprintf(out, "randUint64: %d\n", Uint64()) 74 return out.String() 75 } 76 77 func TestRngConcurrencySafety(t *testing.T) { 78 var wg sync.WaitGroup 79 for i := 0; i < 100; i++ { 80 wg.Add(1) 81 go func() { 82 defer wg.Done() 83 84 _ = Uint64() 85 <-time.After(time.Millisecond * time.Duration(Intn(100))) 86 _ = Perm(3) 87 }() 88 } 89 wg.Wait() 90 } 91 92 func BenchmarkRandBytes10B(b *testing.B) { 93 benchmarkRandBytes(b, 10) 94 } 95 func BenchmarkRandBytes100B(b *testing.B) { 96 benchmarkRandBytes(b, 100) 97 } 98 func BenchmarkRandBytes1KiB(b *testing.B) { 99 benchmarkRandBytes(b, 1024) 100 } 101 func BenchmarkRandBytes10KiB(b *testing.B) { 102 benchmarkRandBytes(b, 10*1024) 103 } 104 func BenchmarkRandBytes100KiB(b *testing.B) { 105 benchmarkRandBytes(b, 100*1024) 106 } 107 func BenchmarkRandBytes1MiB(b *testing.B) { 108 benchmarkRandBytes(b, 1024*1024) 109 } 110 111 func benchmarkRandBytes(b *testing.B, n int) { 112 for i := 0; i < b.N; i++ { 113 _ = Bytes(n) 114 } 115 b.ReportAllocs() 116 }