github.com/gnolang/gno@v0.0.0-20240520182011-228e9d0192ce/tm2/pkg/iavl/common/random_test.go (about)

     1  package common
     2  
     3  import (
     4  	"bytes"
     5  	"encoding/json"
     6  	"fmt"
     7  	mrand "math/rand"
     8  	"testing"
     9  
    10  	"github.com/stretchr/testify/assert"
    11  )
    12  
    13  func TestRandStr(t *testing.T) {
    14  	t.Parallel()
    15  
    16  	l := 243
    17  	s := RandStr(l)
    18  	assert.Equal(t, l, len(s))
    19  }
    20  
    21  func TestRandBytes(t *testing.T) {
    22  	t.Parallel()
    23  
    24  	l := 243
    25  	b := RandBytes(l)
    26  	assert.Equal(t, l, len(b))
    27  }
    28  
    29  // Test to make sure that we never call math.rand().
    30  // We do this by ensuring that outputs are deterministic.
    31  func TestDeterminism(t *testing.T) {
    32  	var firstOutput string
    33  
    34  	// Set math/rand's seed for the sake of debugging this test.
    35  	// (It isn't strictly necessary).
    36  	mrand.Seed(1)
    37  
    38  	for i := 0; i < 100; i++ {
    39  		output := testThemAll()
    40  		if i == 0 {
    41  			firstOutput = output
    42  		} else if firstOutput != output {
    43  			t.Errorf("Run #%d's output was different from first run.\nfirst: %v\nlast: %v",
    44  				i, firstOutput, output)
    45  		}
    46  	}
    47  }
    48  
    49  func testThemAll() string {
    50  	// Such determinism.
    51  	grand.reset(1)
    52  
    53  	// Use it.
    54  	out := new(bytes.Buffer)
    55  	perm := RandPerm(10)
    56  	blob, _ := json.Marshal(perm)
    57  	fmt.Fprintf(out, "perm: %s\n", blob)
    58  	fmt.Fprintf(out, "randInt: %d\n", RandInt())
    59  	fmt.Fprintf(out, "randInt31: %d\n", RandInt31())
    60  	return out.String()
    61  }
    62  
    63  func BenchmarkRandBytes10B(b *testing.B) {
    64  	benchmarkRandBytes(b, 10)
    65  }
    66  
    67  func BenchmarkRandBytes100B(b *testing.B) {
    68  	benchmarkRandBytes(b, 100)
    69  }
    70  
    71  func BenchmarkRandBytes1KiB(b *testing.B) {
    72  	benchmarkRandBytes(b, 1024)
    73  }
    74  
    75  func BenchmarkRandBytes10KiB(b *testing.B) {
    76  	benchmarkRandBytes(b, 10*1024)
    77  }
    78  
    79  func BenchmarkRandBytes100KiB(b *testing.B) {
    80  	benchmarkRandBytes(b, 100*1024)
    81  }
    82  
    83  func BenchmarkRandBytes1MiB(b *testing.B) {
    84  	benchmarkRandBytes(b, 1024*1024)
    85  }
    86  
    87  func benchmarkRandBytes(b *testing.B, n int) {
    88  	b.Helper()
    89  
    90  	for i := 0; i < b.N; i++ {
    91  		_ = RandBytes(n)
    92  	}
    93  	b.ReportAllocs()
    94  }