random_test.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package random
  2. import (
  3. "encoding/base64"
  4. "testing"
  5. )
  6. func TestSeq_LengthAndAlphabet(t *testing.T) {
  7. for _, n := range []int{0, 1, 8, 64, 256} {
  8. s := Seq(n)
  9. if len(s) != n {
  10. t.Fatalf("Seq(%d) returned length %d", n, len(s))
  11. }
  12. for i, r := range s {
  13. isDigit := r >= '0' && r <= '9'
  14. isLower := r >= 'a' && r <= 'z'
  15. isUpper := r >= 'A' && r <= 'Z'
  16. if !(isDigit || isLower || isUpper) {
  17. t.Fatalf("Seq(%d) byte %d = %q is not alphanumeric", n, i, r)
  18. }
  19. }
  20. }
  21. }
  22. func TestSeq_NotConstant(t *testing.T) {
  23. a := Seq(32)
  24. b := Seq(32)
  25. if a == b {
  26. t.Fatalf("two consecutive Seq(32) calls produced identical output: %q", a)
  27. }
  28. }
  29. func TestNum_InRange(t *testing.T) {
  30. for _, upper := range []int{1, 2, 10, 1000} {
  31. for range 200 {
  32. v := Num(upper)
  33. if v < 0 || v >= upper {
  34. t.Fatalf("Num(%d) returned %d, out of [0, %d)", upper, v, upper)
  35. }
  36. }
  37. }
  38. }
  39. func TestBase64Bytes_DecodesToRequestedSize(t *testing.T) {
  40. for _, n := range []int{1, 16, 32, 64} {
  41. out := Base64Bytes(n)
  42. decoded, err := base64.StdEncoding.DecodeString(out)
  43. if err != nil {
  44. t.Fatalf("Base64Bytes(%d) produced invalid base64 %q: %v", n, out, err)
  45. }
  46. if len(decoded) != n {
  47. t.Fatalf("Base64Bytes(%d) decoded to %d bytes", n, len(decoded))
  48. }
  49. }
  50. }
  51. func TestBase64Bytes_Random(t *testing.T) {
  52. a := Base64Bytes(32)
  53. b := Base64Bytes(32)
  54. if a == b {
  55. t.Fatalf("two consecutive Base64Bytes(32) calls produced identical output: %q", a)
  56. }
  57. }