Home | History | Annotate | Download | only in rand
      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 	"testing"
     11 )
     12 
     13 // https://golang.org/issue/6849.
     14 func TestPrimeSmall(t *testing.T) {
     15 	for n := 2; n < 10; n++ {
     16 		p, err := rand.Prime(rand.Reader, n)
     17 		if err != nil {
     18 			t.Fatalf("Can't generate %d-bit prime: %v", n, err)
     19 		}
     20 		if p.BitLen() != n {
     21 			t.Fatalf("%v is not %d-bit", p, n)
     22 		}
     23 		if !p.ProbablyPrime(32) {
     24 			t.Fatalf("%v is not prime", p)
     25 		}
     26 	}
     27 }
     28 
     29 // Test that passing bits < 2 causes Prime to return nil, error
     30 func TestPrimeBitsLt2(t *testing.T) {
     31 	if p, err := rand.Prime(rand.Reader, 1); p != nil || err == nil {
     32 		t.Errorf("Prime should return nil, error when called with bits < 2")
     33 	}
     34 }
     35 
     36 func TestInt(t *testing.T) {
     37 	// start at 128 so the case of (max.BitLen() % 8) == 0 is covered
     38 	for n := 128; n < 140; n++ {
     39 		b := new(big.Int).SetInt64(int64(n))
     40 		if i, err := rand.Int(rand.Reader, b); err != nil {
     41 			t.Fatalf("Can't generate random value: %v, %v", i, err)
     42 		}
     43 	}
     44 }
     45 
     46 func testIntPanics(t *testing.T, b *big.Int) {
     47 	defer func() {
     48 		if err := recover(); err == nil {
     49 			t.Errorf("Int should panic when called with max <= 0: %v", b)
     50 		}
     51 	}()
     52 	rand.Int(rand.Reader, b)
     53 }
     54 
     55 // Test that passing a new big.Int as max causes Int to panic
     56 func TestIntEmptyMaxPanics(t *testing.T) {
     57 	b := new(big.Int)
     58 	testIntPanics(t, b)
     59 }
     60 
     61 // Test that passing a negative value as max causes Int to panic
     62 func TestIntNegativeMaxPanics(t *testing.T) {
     63 	b := new(big.Int).SetInt64(int64(-1))
     64 	testIntPanics(t, b)
     65 }
     66