syntax_test.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package test
  2. import (
  3. "testing"
  4. "github.com/stretchr/testify/assert"
  5. "github.com/tal-tech/go-zero/tools/goctl/api/parser/g4/ast"
  6. "github.com/tal-tech/go-zero/tools/goctl/api/parser/g4/gen/api"
  7. )
  8. var syntaxAccept = func(p *api.ApiParserParser, visitor *ast.ApiVisitor) interface{} {
  9. return p.SyntaxLit().Accept(visitor)
  10. }
  11. func TestSyntax(t *testing.T) {
  12. t.Run("matched", func(t *testing.T) {
  13. v, err := parser.Accept(syntaxAccept, `syntax = "v1"`)
  14. assert.Nil(t, err)
  15. syntax := v.(*ast.SyntaxExpr)
  16. assert.True(t, syntax.Equal(&ast.SyntaxExpr{
  17. Syntax: ast.NewTextExpr("syntax"),
  18. Assign: ast.NewTextExpr("="),
  19. Version: ast.NewTextExpr(`"v1"`),
  20. }))
  21. })
  22. t.Run("expecting syntax", func(t *testing.T) {
  23. _, err := parser.Accept(syntaxAccept, `= "v1"`)
  24. assert.Error(t, err)
  25. _, err = parser.Accept(syntaxAccept, `syn = "v1"`)
  26. assert.Error(t, err)
  27. })
  28. t.Run("missing assign", func(t *testing.T) {
  29. _, err := parser.Accept(syntaxAccept, `syntax "v1"`)
  30. assert.Error(t, err)
  31. _, err = parser.Accept(syntaxAccept, `syntax + "v1"`)
  32. assert.Error(t, err)
  33. })
  34. t.Run("mismatched version", func(t *testing.T) {
  35. _, err := parser.Accept(syntaxAccept, `syntax="v0"`)
  36. assert.Error(t, err)
  37. _, err = parser.Accept(syntaxAccept, `syntax = "v1a"`)
  38. assert.Error(t, err)
  39. _, err = parser.Accept(syntaxAccept, `syntax = "vv1"`)
  40. assert.Error(t, err)
  41. _, err = parser.Accept(syntaxAccept, `syntax = "1"`)
  42. assert.Error(t, err)
  43. })
  44. t.Run("with comment", func(t *testing.T) {
  45. v, err := parser.Accept(syntaxAccept, `
  46. // doc
  47. syntax="v1" // line comment`)
  48. assert.Nil(t, err)
  49. syntax := v.(*ast.SyntaxExpr)
  50. assert.True(t, syntax.Equal(&ast.SyntaxExpr{
  51. Syntax: ast.NewTextExpr("syntax"),
  52. Assign: ast.NewTextExpr("="),
  53. Version: ast.NewTextExpr(`"v1"`),
  54. DocExpr: []ast.Expr{
  55. ast.NewTextExpr("// doc"),
  56. },
  57. CommentExpr: ast.NewTextExpr("// line comment"),
  58. }))
  59. })
  60. }