rdpar_test.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. // This package contains a reusable recursive descent parser
  2. // Copyright Beoran beoran@gmail.com 2021
  3. // Licenced under the MIT licence.
  4. package rdpar
  5. import "testing"
  6. // import "os"
  7. // import "bufio"
  8. import "strings"
  9. import "strconv"
  10. func FatalIfErr(t *testing.T, v Value) {
  11. if v != nil {
  12. if err, isErr := v.(error); isErr {
  13. t.Fatalf("Error: %s", err)
  14. }
  15. }
  16. }
  17. func TestParseWord(t *testing.T) {
  18. in := strings.NewReader(`foo `)
  19. p := &Parser{}
  20. p.RuneScanner = in
  21. res := p.ParseWord("\r\n ")
  22. FatalIfErr(t, res)
  23. want := string("foo")
  24. if res != want {
  25. t.Errorf("error: expected: %s, got %s.", want, res)
  26. } else {
  27. t.Logf("ok: %s, %s", want, res)
  28. }
  29. }
  30. func TestParseInt(t *testing.T) {
  31. in := strings.NewReader(`123 `)
  32. p := &Parser{}
  33. p.RuneScanner = in
  34. res := p.ParseNum("\r\n ")
  35. FatalIfErr(t, res)
  36. want := int64(123)
  37. if res != want {
  38. t.Errorf("error: expected: %d, got %d.", want, res)
  39. } else {
  40. t.Logf("ok: %d, %d", want, res)
  41. }
  42. }
  43. func TestParseFloat(t *testing.T) {
  44. in := strings.NewReader(`123.456 `)
  45. p := &Parser{}
  46. p.RuneScanner = in
  47. res := p.ParseNum("\r\n ")
  48. FatalIfErr(t, res)
  49. want := float64(123.456)
  50. if res != want {
  51. t.Errorf("error: expected: %f, got %f.", want, res)
  52. } else {
  53. t.Logf("ok: %f, %f", want, res)
  54. }
  55. }
  56. func TestParseString(t *testing.T) {
  57. instr := `"Hello\nWorld\\\""`
  58. in := strings.NewReader(instr)
  59. p := &Parser{}
  60. p.RuneScanner = in
  61. res := p.ParseString('"', '"')
  62. FatalIfErr(t, res)
  63. want, err := strconv.Unquote(instr)
  64. FatalIfErr(t, err)
  65. if res != want {
  66. t.Errorf("error: expected: %s, got %v.", want, res)
  67. } else {
  68. t.Logf("ok: %s, %s", want, res)
  69. }
  70. }
  71. func TestParsRawString(t *testing.T) {
  72. instr := `[Hello&]World&&]`
  73. in := strings.NewReader(instr)
  74. p := &Parser{}
  75. p.RuneScanner = in
  76. res := p.ParseRawString('[', ']', '&')
  77. FatalIfErr(t, res)
  78. want := `Hello]World&`
  79. if res != want {
  80. t.Errorf("error: expected: %s, got %v.", want, res)
  81. } else {
  82. t.Logf("ok: %s, %s", want, res)
  83. }
  84. }
  85. /*
  86. func TestTabpa(t *testing.T) {
  87. fin, err := os.Open("testdata/test1.b1cfg")
  88. FatalIfErr(t, err)
  89. defer fin.Close()
  90. res, err := ParseB1cfg(bufio.NewReader(fin))
  91. FatalIfErr(t, err)
  92. t.Logf("res: %v", res)
  93. }*/