github.com/cockroachdb/cockroach@v20.2.0-alpha.1+incompatible/pkg/util/randutil/rand_test.go (about)

     1  // Copyright 2014 The Cockroach Authors.
     2  //
     3  // Use of this software is governed by the Business Source License
     4  // included in the file licenses/BSL.txt.
     5  //
     6  // As of the Change Date specified in that file, in accordance with
     7  // the Business Source License, use of this software will be governed
     8  // by the Apache License, Version 2.0, included in the file
     9  // licenses/APL.txt.
    10  
    11  package randutil_test
    12  
    13  import (
    14  	"testing"
    15  
    16  	_ "github.com/cockroachdb/cockroach/pkg/util/log" // for flags
    17  	"github.com/cockroachdb/cockroach/pkg/util/randutil"
    18  )
    19  
    20  func TestPseudoRand(t *testing.T) {
    21  	numbers := make(map[int]bool)
    22  	// Make two random number generators and pull two numbers from each.
    23  	rand1, _ := randutil.NewPseudoRand()
    24  	rand2, _ := randutil.NewPseudoRand()
    25  	numbers[rand1.Int()] = true
    26  	numbers[rand1.Int()] = true
    27  	numbers[rand2.Int()] = true
    28  	numbers[rand2.Int()] = true
    29  	// All four numbers should be distinct; no seed state is shared.
    30  	if len(numbers) != 4 {
    31  		t.Errorf("expected 4 unique numbers; got %d", len(numbers))
    32  	}
    33  }
    34  
    35  func TestRandIntInRange(t *testing.T) {
    36  	rand, _ := randutil.NewPseudoRand()
    37  	for i := 0; i < 100; i++ {
    38  		x := randutil.RandIntInRange(rand, 20, 40)
    39  		if x < 20 || x >= 40 {
    40  			t.Errorf("got result out of range: %d", x)
    41  		}
    42  	}
    43  }
    44  
    45  func TestRandBytes(t *testing.T) {
    46  	rand, _ := randutil.NewPseudoRand()
    47  	for i := 0; i < 100; i++ {
    48  		x := randutil.RandBytes(rand, i)
    49  		if len(x) != i {
    50  			t.Errorf("got array with unexpected length: %d (expected %d)", len(x), i)
    51  		}
    52  	}
    53  }