random_test.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. // Copyright (C) 2014 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at http://mozilla.org/MPL/2.0/.
  6. package util
  7. import (
  8. "runtime"
  9. "sync"
  10. "testing"
  11. )
  12. var predictableRandomTest sync.Once
  13. func TestPredictableRandom(t *testing.T) {
  14. if runtime.GOARCH != "amd64" {
  15. t.Skip("Test only for 64 bit platforms; but if it works there, it should work on 32 bit")
  16. }
  17. predictableRandomTest.Do(func() {
  18. // predictable random sequence is predictable
  19. e := int64(3440579354231278675)
  20. if v := int64(PredictableRandom.Int()); v != e {
  21. t.Errorf("Unexpected random value %d != %d", v, e)
  22. }
  23. })
  24. }
  25. func TestSeedFromBytes(t *testing.T) {
  26. // should always return the same seed for the same bytes
  27. tcs := []struct {
  28. bs []byte
  29. v int64
  30. }{
  31. {[]byte("hello world"), -3639725434188061933},
  32. {[]byte("hello worlx"), -2539100776074091088},
  33. }
  34. for _, tc := range tcs {
  35. if v := SeedFromBytes(tc.bs); v != tc.v {
  36. t.Errorf("Unexpected seed value %d != %d", v, tc.v)
  37. }
  38. }
  39. }
  40. func TestRandomString(t *testing.T) {
  41. for _, l := range []int{0, 1, 2, 3, 4, 8, 42} {
  42. s := RandomString(l)
  43. if len(s) != l {
  44. t.Errorf("Incorrect length %d != %d", len(s), l)
  45. }
  46. }
  47. strings := make([]string, 1000)
  48. for i := range strings {
  49. strings[i] = RandomString(8)
  50. for j := range strings {
  51. if i == j {
  52. continue
  53. }
  54. if strings[i] == strings[j] {
  55. t.Errorf("Repeated random string %q", strings[i])
  56. }
  57. }
  58. }
  59. }
  60. func TestRandomInt64(t *testing.T) {
  61. ints := make([]int64, 1000)
  62. for i := range ints {
  63. ints[i] = RandomInt64()
  64. for j := range ints {
  65. if i == j {
  66. continue
  67. }
  68. if ints[i] == ints[j] {
  69. t.Errorf("Repeated random int64 %d", ints[i])
  70. }
  71. }
  72. }
  73. }