regexp_test.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  1. package parser
  2. import (
  3. "regexp"
  4. "testing"
  5. )
  6. func TestRegExp(t *testing.T) {
  7. tt(t, func() {
  8. {
  9. // err
  10. test := func(input string, expect interface{}) {
  11. _, err := TransformRegExp(input)
  12. is(err, expect)
  13. }
  14. test("[", "Unterminated character class")
  15. test("(", "Unterminated group")
  16. test("\\(?=)", "Unmatched ')'")
  17. test(")", "Unmatched ')'")
  18. }
  19. {
  20. // err
  21. test := func(input, expect string, expectErr interface{}) {
  22. output, err := TransformRegExp(input)
  23. is(output, expect)
  24. is(err, expectErr)
  25. }
  26. test(")", "", "Unmatched ')'")
  27. test("\\0", "\\0", nil)
  28. }
  29. {
  30. // err
  31. test := func(input string, expect string) {
  32. result, err := TransformRegExp(input)
  33. is(err, nil)
  34. is(result, expect)
  35. _, err = regexp.Compile(result)
  36. is(err, nil)
  37. }
  38. testErr := func(input string, expectErr string) {
  39. _, err := TransformRegExp(input)
  40. is(err, expectErr)
  41. }
  42. test("", "")
  43. test("abc", "abc")
  44. test(`\abc`, `abc`)
  45. test(`\a\b\c`, `a\bc`)
  46. test(`\x`, `x`)
  47. test(`\c`, `c`)
  48. test(`\cA`, `\x01`)
  49. test(`\cz`, `\x1a`)
  50. test(`\ca`, `\x01`)
  51. test(`\cj`, `\x0a`)
  52. test(`\ck`, `\x0b`)
  53. test(`\+`, `\+`)
  54. test(`[\b]`, `[\x08]`)
  55. test(`\u0z01\x\undefined`, `u0z01xundefined`)
  56. test(`\\|'|\r|\n|\t|\u2028|\u2029`, `\\|'|\r|\n|\t|\x{2028}|\x{2029}`)
  57. test("]", "]")
  58. test("}", "}")
  59. test("%", "%")
  60. test("(%)", "(%)")
  61. test("(?:[%\\s])", "(?:[%"+WhitespaceChars+"])")
  62. test("[[]", "[[]")
  63. test("\\101", "\\x41")
  64. test("\\51", "\\x29")
  65. test("\\051", "\\x29")
  66. test("\\175", "\\x7d")
  67. test("\\04", "\\x04")
  68. testErr(`<%([\s\S]+?)%>`, "S in class")
  69. test(`(.)^`, "([^\\r\\n])^")
  70. test(`\$`, `\$`)
  71. test(`[G-b]`, `[G-b]`)
  72. test(`[G-b\0]`, `[G-b\0]`)
  73. }
  74. })
  75. }
  76. func TestTransformRegExp(t *testing.T) {
  77. tt(t, func() {
  78. pattern, err := TransformRegExp(`\s+abc\s+`)
  79. is(err, nil)
  80. is(pattern, `[`+WhitespaceChars+`]+abc[`+WhitespaceChars+`]+`)
  81. is(regexp.MustCompile(pattern).MatchString("\t abc def"), true)
  82. })
  83. }