github.com/avahowell/sia@v0.5.1-beta.0.20160524050156-83dcc3d37c94/crypto/rand_test.go (about) 1 package crypto 2 3 import ( 4 "testing" 5 ) 6 7 // panics returns true if the function fn panicked. 8 func panics(fn func()) (panicked bool) { 9 defer func() { 10 panicked = (recover() != nil) 11 }() 12 fn() 13 return 14 } 15 16 // TestRandIntnPanics tests that RandIntn panics if n <= 0. 17 func TestRandIntnPanics(t *testing.T) { 18 // Test n = 0. 19 if !panics(func() { RandIntn(0) }) { 20 t.Error("expected panic for n <= 0") 21 } 22 23 // Test n < 0. 24 if !panics(func() { RandIntn(-1) }) { 25 t.Error("expected panic for n <= 0") 26 } 27 } 28 29 // TestPerm tests the Perm function. 30 func TestPerm(t *testing.T) { 31 chars := "abcde" // string to be permuted 32 createPerm := func() string { 33 perm, err := Perm(len(chars)) 34 if err != nil { 35 t.Fatal(err) 36 } 37 s := make([]byte, len(chars)) 38 for i, j := range perm { 39 s[i] = chars[j] 40 } 41 return string(s) 42 } 43 44 // create (factorial(len(chars)) * 100) permutations 45 permCount := make(map[string]int) 46 for i := 0; i < 12000; i++ { 47 permCount[createPerm()]++ 48 } 49 50 // we should have seen each permutation approx. 100 times 51 for p, n := range permCount { 52 if n < 50 || n > 150 { 53 t.Errorf("saw permutation %v times: %v", n, p) 54 } 55 } 56 }