From: Shawn Smith Date: Fri, 31 Jan 2014 00:43:48 +0000 (+1100) Subject: crypto/rand: add tests for Int, Prime X-Git-Tag: go1.3beta1~837 X-Git-Url: http://www.git.cypherpunks.su/?a=commitdiff_plain;h=99d23dfdfd19204d76877a7322c298726aba6d9a;p=gostls13.git crypto/rand: add tests for Int, Prime LGTM=rsc, dave R=golang-codereviews, dave, josharian, rsc CC=golang-codereviews https://golang.org/cl/46490043 --- diff --git a/src/pkg/crypto/rand/util_test.go b/src/pkg/crypto/rand/util_test.go index 33f9820371..1e2a4dd84b 100644 --- a/src/pkg/crypto/rand/util_test.go +++ b/src/pkg/crypto/rand/util_test.go @@ -6,6 +6,7 @@ package rand_test import ( "crypto/rand" + "math/big" "testing" ) @@ -24,3 +25,41 @@ func TestPrimeSmall(t *testing.T) { } } } + +// Test that passing bits < 2 causes Prime to return nil, error +func TestPrimeBitsLt2(t *testing.T) { + if p, err := rand.Prime(rand.Reader, 1); p != nil || err == nil { + t.Errorf("Prime should return nil, error when called with bits < 2") + } +} + +func TestInt(t *testing.T) { + // start at 128 so the case of (max.BitLen() % 8) == 0 is covered + for n := 128; n < 140; n++ { + b := new(big.Int).SetInt64(int64(n)) + if i, err := rand.Int(rand.Reader, b); err != nil { + t.Fatalf("Can't generate random value: %v, %v", i, err) + } + } +} + +func testIntPanics(t *testing.T, b *big.Int) { + defer func() { + if err := recover(); err == nil { + t.Errorf("Int should panic when called with max <= 0: %v", b) + } + }() + rand.Int(rand.Reader, b) +} + +// Test that passing a new big.Int as max causes Int to panic +func TestIntEmptyMaxPanics(t *testing.T) { + b := new(big.Int) + testIntPanics(t, b) +} + +// Test that passing a negative value as max causes Int to panic +func TestIntNegativeMaxPanics(t *testing.T) { + b := new(big.Int).SetInt64(int64(-1)) + testIntPanics(t, b) +}