stringutils_test.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package stringutils
  2. import "testing"
  3. func TestRandomString(t *testing.T) {
  4. str := GenerateRandomString()
  5. if len(str) != 64 {
  6. t.Fatalf("Id returned is incorrect: %s", str)
  7. }
  8. }
  9. func TestRandomStringUniqueness(t *testing.T) {
  10. repeats := 25
  11. set := make(map[string]struct{}, repeats)
  12. for i := 0; i < repeats; i = i + 1 {
  13. str := GenerateRandomString()
  14. if len(str) != 64 {
  15. t.Fatalf("Id returned is incorrect: %s", str)
  16. }
  17. if _, ok := set[str]; ok {
  18. t.Fatalf("Random number is repeated")
  19. }
  20. set[str] = struct{}{}
  21. }
  22. }
  23. func testLengthHelper(generator func(int) string, t *testing.T) {
  24. expectedLength := 20
  25. s := generator(expectedLength)
  26. if len(s) != expectedLength {
  27. t.Fatalf("Length of %s was %d but expected length %d", s, len(s), expectedLength)
  28. }
  29. }
  30. func testUniquenessHelper(generator func(int) string, t *testing.T) {
  31. repeats := 25
  32. set := make(map[string]struct{}, repeats)
  33. for i := 0; i < repeats; i = i + 1 {
  34. str := generator(64)
  35. if len(str) != 64 {
  36. t.Fatalf("Id returned is incorrect: %s", str)
  37. }
  38. if _, ok := set[str]; ok {
  39. t.Fatalf("Random number is repeated")
  40. }
  41. set[str] = struct{}{}
  42. }
  43. }
  44. func isASCII(s string) bool {
  45. for _, c := range s {
  46. if c > 127 {
  47. return false
  48. }
  49. }
  50. return true
  51. }
  52. func TestGenerateRandomAlphaOnlyStringLength(t *testing.T) {
  53. testLengthHelper(GenerateRandomAlphaOnlyString, t)
  54. }
  55. func TestGenerateRandomAlphaOnlyStringUniqueness(t *testing.T) {
  56. testUniquenessHelper(GenerateRandomAlphaOnlyString, t)
  57. }
  58. func TestGenerateRandomAsciiStringLength(t *testing.T) {
  59. testLengthHelper(GenerateRandomAsciiString, t)
  60. }
  61. func TestGenerateRandomAsciiStringUniqueness(t *testing.T) {
  62. testUniquenessHelper(GenerateRandomAsciiString, t)
  63. }
  64. func TestGenerateRandomAsciiStringIsAscii(t *testing.T) {
  65. str := GenerateRandomAsciiString(64)
  66. if !isASCII(str) {
  67. t.Fatalf("%s contained non-ascii characters", str)
  68. }
  69. }