csv_test.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. // Copyright 2021 gorse Project Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package base
  15. import (
  16. "bufio"
  17. "github.com/stretchr/testify/assert"
  18. "strings"
  19. "testing"
  20. )
  21. func TestValidateId(t *testing.T) {
  22. assert.NotNil(t, ValidateId(""))
  23. assert.NotNil(t, ValidateId("/"))
  24. assert.Nil(t, ValidateId("abc"))
  25. }
  26. func TestValidateLabel(t *testing.T) {
  27. assert.NotNil(t, ValidateLabel(""))
  28. assert.NotNil(t, ValidateLabel("/"))
  29. assert.NotNil(t, ValidateLabel("|"))
  30. assert.Nil(t, ValidateLabel("abc"))
  31. }
  32. func TestEscape(t *testing.T) {
  33. assert.Equal(t, "123", Escape("123"))
  34. assert.Equal(t, "\"\"\"123\"\"\"", Escape("\"123\""))
  35. assert.Equal(t, "\"1,2,3\"", Escape("1,2,3"))
  36. assert.Equal(t, "\"\"\",\"\"\"", Escape("\",\""))
  37. assert.Equal(t, "\"1\r\n2\r\n3\"", Escape("1\r\n2\r\n3"))
  38. }
  39. func splitLines(t *testing.T, text string) [][]string {
  40. sc := bufio.NewScanner(strings.NewReader(text))
  41. lines := make([][]string, 0)
  42. err := ReadLines(sc, ",", func(i int, i2 []string) bool {
  43. lines = append(lines, i2)
  44. return i2[0] != "STOP"
  45. })
  46. assert.NoError(t, err)
  47. return lines
  48. }
  49. func TestReadLines(t *testing.T) {
  50. assert.Equal(t, [][]string{{"1", "2", "3"}, {"4", "5", "6"}},
  51. splitLines(t, "1,2,3\r\n4,5,6\r\n"))
  52. assert.Equal(t, [][]string{{"1,2", "3,4", "5,6"}, {"2,3", "4,6", "6,9"}},
  53. splitLines(t, "\"1,2\",\"3,4\",\"5,6\"\r\n\"2,3\",\"4,6\",\"6,9\""))
  54. assert.Equal(t, [][]string{{"\"1,2\",\"3,4\",\"5,6\""}, {"\"2,3\",\"4,6\",\"6,9\""}},
  55. splitLines(t, "\"\"\"1,2\"\",\"\"3,4\"\",\"\"5,6\"\"\"\r\n\"\"\"2,3\"\",\"\"4,6\"\",\"\"6,9\"\"\""))
  56. assert.Equal(t, [][]string{{"1\r\n2", "3\r\n4", "5\r\n6"}, {"2\r\n3", "4\r\n6", "6\r\n9"}},
  57. splitLines(t, "\"1\r\n2\",\"3\r\n4\",\"5\r\n6\"\r\n\"2\r\n3\",\"4\r\n6\",\"6\r\n9\""))
  58. assert.Equal(t, [][]string{{"1", "2", "3"}, {"4", "5", "6"}, {"STOP"}},
  59. splitLines(t, "1,2,3\r\n4,5,6\r\nSTOP\r\n7,8,9"))
  60. }