ref/test/testutil: test for use of an unitialized global random number generator.
Change-Id: I62e5c0e76401cf6d6d61e25f8687ce1581c4110c
diff --git a/test/testutil/rand.go b/test/testutil/rand.go
index ca9f038..dd65af1 100644
--- a/test/testutil/rand.go
+++ b/test/testutil/rand.go
@@ -23,6 +23,8 @@
once sync.Once
)
+const randPanicMsg = "It looks like the singleton random number generator has not been initialized, please call InitRandGenerator."
+
// Random is a concurrent-access friendly source of randomness.
type Random struct {
mu sync.Mutex
@@ -125,23 +127,35 @@
// RandomInt returns a non-negative pseudo-random int using the public variable Rand.
func RandomInt() int {
+ if Rand == nil {
+ panic(randPanicMsg)
+ }
return Rand.RandomInt()
}
// RandomIntn returns a non-negative pseudo-random int in the range [0, n) using
// the public variable Rand.
func RandomIntn(n int) int {
+ if Rand == nil {
+ panic(randPanicMsg)
+ }
return Rand.RandomIntn(n)
}
// RandomInt63 returns a non-negative 63-bit pseudo-random integer as an int64
// using the public variable Rand.
func RandomInt63() int64 {
+ if Rand == nil {
+ panic(randPanicMsg)
+ }
return Rand.RandomInt63()
}
// RandomBytes generates the given number of random bytes using
// the public variable Rand.
func RandomBytes(size int) []byte {
+ if Rand == nil {
+ panic(randPanicMsg)
+ }
return Rand.RandomBytes(size)
}
diff --git a/test/testutil/util_test.go b/test/testutil/util_test.go
index 91b9aff..b2ed9f5 100644
--- a/test/testutil/util_test.go
+++ b/test/testutil/util_test.go
@@ -20,6 +20,25 @@
}
}
+func panicHelper(ch chan string) {
+ defer func() {
+ if r := recover(); r != nil {
+ ch <- r.(string)
+ }
+ }()
+ testutil.RandomInt()
+}
+
+func TestPanic(t *testing.T) {
+ testutil.Rand = nil
+ ch := make(chan string)
+ go panicHelper(ch)
+ str := <-ch
+ if got, want := str, "It looks like the singleton random number generator has not been initialized, please call InitRandGenerator."; got != want {
+ t.Fatalf("got %v, want %v", got, want)
+ }
+}
+
//go:generate v23 test generate .
func V23TestRandSeed(i *v23tests.T) {