case_test.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "os"
  6. "path/filepath"
  7. "strings"
  8. "testing"
  9. )
  10. type Testcase struct {
  11. Name string
  12. Path string
  13. ConfigName string
  14. Stderr []byte
  15. Exec *Exec
  16. }
  17. type Exec struct {
  18. Command string `json:"command"`
  19. Contexts []string `json:"contexts"`
  20. Process string `json:"process"`
  21. Env map[string]string `json:"env"`
  22. }
  23. func parseStderr(t *testing.T, dir, testctx string) []byte {
  24. t.Helper()
  25. paths := []string{
  26. filepath.Join(dir, "stderr", fmt.Sprintf("%s.txt", testctx)),
  27. filepath.Join(dir, "stderr.txt"),
  28. }
  29. for _, path := range paths {
  30. if _, err := os.Stat(path); !os.IsNotExist(err) {
  31. blob, err := os.ReadFile(path)
  32. if err != nil {
  33. t.Fatal(err)
  34. }
  35. return blob
  36. }
  37. }
  38. return nil
  39. }
  40. func parseExec(t *testing.T, dir string) *Exec {
  41. t.Helper()
  42. path := filepath.Join(dir, "exec.json")
  43. if _, err := os.Stat(path); os.IsNotExist(err) {
  44. return nil
  45. }
  46. var e Exec
  47. blob, err := os.ReadFile(path)
  48. if err != nil {
  49. t.Fatal(err)
  50. }
  51. if err := json.Unmarshal(blob, &e); err != nil {
  52. t.Fatal(err)
  53. }
  54. if e.Command == "" {
  55. e.Command = "generate"
  56. }
  57. return &e
  58. }
  59. func FindTests(t *testing.T, root, testctx string) []*Testcase {
  60. var tcs []*Testcase
  61. err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
  62. if err != nil {
  63. return err
  64. }
  65. if info.Name() == "sqlc.json" || info.Name() == "sqlc.yaml" || info.Name() == "sqlc.yml" {
  66. dir := filepath.Dir(path)
  67. tcs = append(tcs, &Testcase{
  68. Path: dir,
  69. Name: strings.TrimPrefix(dir, root+string(filepath.Separator)),
  70. ConfigName: info.Name(),
  71. Stderr: parseStderr(t, dir, testctx),
  72. Exec: parseExec(t, dir),
  73. })
  74. return filepath.SkipDir
  75. }
  76. return nil
  77. })
  78. if err != nil {
  79. t.Fatal(err)
  80. }
  81. return tcs
  82. }