snippet_writer_test.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package generator_test
  2. import (
  3. "bytes"
  4. "strings"
  5. "testing"
  6. "go-common/app/tool/gengo/generator"
  7. "go-common/app/tool/gengo/namer"
  8. "go-common/app/tool/gengo/parser"
  9. )
  10. func construct(t *testing.T, files map[string]string) *generator.Context {
  11. b := parser.New()
  12. for name, src := range files {
  13. if err := b.AddFileForTest("/tmp/"+name, name, []byte(src)); err != nil {
  14. t.Fatal(err)
  15. }
  16. }
  17. c, err := generator.NewContext(b, namer.NameSystems{
  18. "public": namer.NewPublicNamer(0),
  19. "private": namer.NewPrivateNamer(0),
  20. }, "public")
  21. if err != nil {
  22. t.Fatal(err)
  23. }
  24. return c
  25. }
  26. func TestSnippetWriter(t *testing.T) {
  27. var structTest = map[string]string{
  28. "base/foo/proto/foo.go": `
  29. package foo
  30. // Blah is a test.
  31. // A test, I tell you.
  32. type Blah struct {
  33. // A is the first field.
  34. A int64 ` + "`" + `json:"a"` + "`" + `
  35. // B is the second field.
  36. // Multiline comments work.
  37. B string ` + "`" + `json:"b"` + "`" + `
  38. }
  39. `,
  40. }
  41. c := construct(t, structTest)
  42. b := &bytes.Buffer{}
  43. err := generator.NewSnippetWriter(b, c, "$", "$").
  44. Do("$.|public$$.|private$", c.Order[0]).
  45. Error()
  46. if err != nil {
  47. t.Errorf("Unexpected error %v", err)
  48. }
  49. if e, a := "Blahblah", b.String(); e != a {
  50. t.Errorf("Expected %q, got %q", e, a)
  51. }
  52. err = generator.NewSnippetWriter(b, c, "$", "$").
  53. Do("$.|public", c.Order[0]).
  54. Error()
  55. if err == nil {
  56. t.Errorf("expected error on invalid template")
  57. } else {
  58. // Dear reader, I apologize for making the worst change
  59. // detection test in the history of ever.
  60. if e, a := "snippet_writer_test.go", err.Error(); !strings.Contains(a, e) {
  61. t.Errorf("Expected %q but didn't find it in %q", e, a)
  62. }
  63. }
  64. }