position_test.go 822 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. package parse
  2. import (
  3. "bytes"
  4. "fmt"
  5. "io"
  6. "testing"
  7. "github.com/tdewolff/test"
  8. )
  9. func TestPosition(t *testing.T) {
  10. var newlineTests = []struct {
  11. offset int
  12. buf string
  13. line int
  14. col int
  15. err error
  16. }{
  17. {0, "x", 1, 1, nil},
  18. {1, "xx", 1, 2, nil},
  19. {2, "x\nx", 2, 1, nil},
  20. {2, "\n\nx", 3, 1, nil},
  21. {3, "\nxxx", 2, 3, nil},
  22. {2, "\r\nx", 2, 1, nil},
  23. // edge cases
  24. {0, "", 1, 1, io.EOF},
  25. {0, "\n", 1, 1, nil},
  26. {1, "\r\n", 1, 2, nil},
  27. {-1, "x", 1, 2, io.EOF}, // continue till the end
  28. }
  29. for _, tt := range newlineTests {
  30. t.Run(fmt.Sprint(tt.buf, " ", tt.offset), func(t *testing.T) {
  31. r := bytes.NewBufferString(tt.buf)
  32. line, col, _, err := Position(r, tt.offset)
  33. test.T(t, err, tt.err)
  34. test.T(t, line, tt.line, "line")
  35. test.T(t, col, tt.col, "column")
  36. })
  37. }
  38. }