github.com/slayercat/go@v0.0.0-20170428012452-c51559813f61/src/crypto/rand/util_test.go (about)

     1  // Copyright 2013 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package rand_test
     6  
     7  import (
     8  	"crypto/rand"
     9  	"math/big"
    10  	mathrand "math/rand"
    11  	"testing"
    12  	"time"
    13  )
    14  
    15  // https://golang.org/issue/6849.
    16  func TestPrimeSmall(t *testing.T) {
    17  	for n := 2; n < 10; n++ {
    18  		p, err := rand.Prime(rand.Reader, n)
    19  		if err != nil {
    20  			t.Fatalf("Can't generate %d-bit prime: %v", n, err)
    21  		}
    22  		if p.BitLen() != n {
    23  			t.Fatalf("%v is not %d-bit", p, n)
    24  		}
    25  		if !p.ProbablyPrime(32) {
    26  			t.Fatalf("%v is not prime", p)
    27  		}
    28  	}
    29  }
    30  
    31  // Test that passing bits < 2 causes Prime to return nil, error
    32  func TestPrimeBitsLt2(t *testing.T) {
    33  	if p, err := rand.Prime(rand.Reader, 1); p != nil || err == nil {
    34  		t.Errorf("Prime should return nil, error when called with bits < 2")
    35  	}
    36  }
    37  
    38  func TestInt(t *testing.T) {
    39  	// start at 128 so the case of (max.BitLen() % 8) == 0 is covered
    40  	for n := 128; n < 140; n++ {
    41  		b := new(big.Int).SetInt64(int64(n))
    42  		if i, err := rand.Int(rand.Reader, b); err != nil {
    43  			t.Fatalf("Can't generate random value: %v, %v", i, err)
    44  		}
    45  	}
    46  }
    47  
    48  func testIntPanics(t *testing.T, b *big.Int) {
    49  	defer func() {
    50  		if err := recover(); err == nil {
    51  			t.Errorf("Int should panic when called with max <= 0: %v", b)
    52  		}
    53  	}()
    54  	rand.Int(rand.Reader, b)
    55  }
    56  
    57  // Test that passing a new big.Int as max causes Int to panic
    58  func TestIntEmptyMaxPanics(t *testing.T) {
    59  	b := new(big.Int)
    60  	testIntPanics(t, b)
    61  }
    62  
    63  // Test that passing a negative value as max causes Int to panic
    64  func TestIntNegativeMaxPanics(t *testing.T) {
    65  	b := new(big.Int).SetInt64(int64(-1))
    66  	testIntPanics(t, b)
    67  }
    68  
    69  func BenchmarkPrime(b *testing.B) {
    70  	r := mathrand.New(mathrand.NewSource(time.Now().UnixNano()))
    71  	for i := 0; i < b.N; i++ {
    72  		rand.Prime(r, 1024)
    73  	}
    74  }