]> Cypherpunks repositories - gostls13.git/commitdiff
crypto/rand: add tests for Int, Prime
authorShawn Smith <shawn.p.smith@gmail.com>
Fri, 31 Jan 2014 00:43:48 +0000 (11:43 +1100)
committerDave Cheney <dave@cheney.net>
Fri, 31 Jan 2014 00:43:48 +0000 (11:43 +1100)
LGTM=rsc, dave
R=golang-codereviews, dave, josharian, rsc
CC=golang-codereviews
https://golang.org/cl/46490043

src/pkg/crypto/rand/util_test.go

index 33f9820371a7166522a67a25cbc5f2238d304dfd..1e2a4dd84b715da3478e242f69e48e80552bb425 100644 (file)
@@ -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)
+}