You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

89 lines
2.3 KiB

  1. package strings
  2. import (
  3. "testing"
  4. "github.com/stretchr/testify/require"
  5. )
  6. func TestSplitAndTrimEmpty(t *testing.T) {
  7. testCases := []struct {
  8. s string
  9. sep string
  10. cutset string
  11. expected []string
  12. }{
  13. {"a,b,c", ",", " ", []string{"a", "b", "c"}},
  14. {" a , b , c ", ",", " ", []string{"a", "b", "c"}},
  15. {" a, b, c ", ",", " ", []string{"a", "b", "c"}},
  16. {" a, ", ",", " ", []string{"a"}},
  17. {" ", ",", " ", []string{}},
  18. }
  19. for _, tc := range testCases {
  20. require.Equal(t, tc.expected, SplitAndTrimEmpty(tc.s, tc.sep, tc.cutset), "%s", tc.s)
  21. }
  22. }
  23. func assertCorrectTrim(t *testing.T, input, expected string) {
  24. t.Helper()
  25. output, err := ASCIITrim(input)
  26. require.NoError(t, err)
  27. require.Equal(t, expected, output)
  28. }
  29. func TestASCIITrim(t *testing.T) {
  30. t.Run("Validation", func(t *testing.T) {
  31. t.Run("NonASCII", func(t *testing.T) {
  32. notASCIIText := []string{
  33. "\xC2", "\xC2\xA2", "\xFF", "\x80", "\xF0", "\n", "\t",
  34. }
  35. for _, v := range notASCIIText {
  36. _, err := ASCIITrim(v)
  37. require.Error(t, err, "%q is not ascii-text", v)
  38. }
  39. })
  40. t.Run("EmptyString", func(t *testing.T) {
  41. out, err := ASCIITrim("")
  42. require.NoError(t, err)
  43. require.Zero(t, out)
  44. })
  45. t.Run("ASCIIText", func(t *testing.T) {
  46. asciiText := []string{
  47. " ", ".", "x", "$", "_", "abcdefg;", "-", "0x00", "0", "123",
  48. }
  49. for _, v := range asciiText {
  50. _, err := ASCIITrim(v)
  51. require.NoError(t, err, "%q is ascii-text", v)
  52. }
  53. })
  54. _, err := ASCIITrim("\xC2\xA2")
  55. require.Error(t, err)
  56. })
  57. t.Run("Trimming", func(t *testing.T) {
  58. assertCorrectTrim(t, " ", "")
  59. assertCorrectTrim(t, " a", "a")
  60. assertCorrectTrim(t, "a ", "a")
  61. assertCorrectTrim(t, " a ", "a")
  62. })
  63. }
  64. func TestStringSliceEqual(t *testing.T) {
  65. tests := []struct {
  66. a []string
  67. b []string
  68. want bool
  69. }{
  70. {[]string{"hello", "world"}, []string{"hello", "world"}, true},
  71. {[]string{"test"}, []string{"test"}, true},
  72. {[]string{"test1"}, []string{"test2"}, false},
  73. {[]string{"hello", "world."}, []string{"hello", "world!"}, false},
  74. {[]string{"only 1 word"}, []string{"two", "words!"}, false},
  75. {[]string{"two", "words!"}, []string{"only 1 word"}, false},
  76. }
  77. for i, tt := range tests {
  78. require.Equal(t, tt.want, StringSliceEqual(tt.a, tt.b),
  79. "StringSliceEqual failed on test %d", i)
  80. }
  81. }