|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "os" |
| 6 | + "path/filepath" |
| 7 | + "strings" |
| 8 | + "testing" |
| 9 | + |
| 10 | + "github.com/google/go-cmp/cmp" |
| 11 | + |
| 12 | + "github.com/sqlc-dev/sqlc/internal/cmd" |
| 13 | +) |
| 14 | + |
| 15 | +// TestParseCommand runs `sqlc parse --dialect <dialect> query.sql` for every |
| 16 | +// case under testdata/parse and compares stdout against the stdout.json |
| 17 | +// golden. The dialect is the case directory's name up to the first "_" |
| 18 | +// (e.g. googlesql_select uses --dialect googlesql). |
| 19 | +// |
| 20 | +// To regenerate the goldens after an intentional AST change, run: |
| 21 | +// |
| 22 | +// SQLC_PARSE_UPDATE=1 go test ./internal/endtoend -run TestParseCommand |
| 23 | +func TestParseCommand(t *testing.T) { |
| 24 | + t.Parallel() |
| 25 | + |
| 26 | + dirs, err := filepath.Glob(filepath.Join("testdata", "parse", "*")) |
| 27 | + if err != nil { |
| 28 | + t.Fatal(err) |
| 29 | + } |
| 30 | + if len(dirs) == 0 { |
| 31 | + t.Fatal("no testdata/parse cases found") |
| 32 | + } |
| 33 | + |
| 34 | + for _, dir := range dirs { |
| 35 | + tc := filepath.Base(dir) |
| 36 | + dialect, _, ok := strings.Cut(tc, "_") |
| 37 | + if !ok { |
| 38 | + t.Fatalf("case %q: directory name must be <dialect>_<name>", tc) |
| 39 | + } |
| 40 | + t.Run(tc, func(t *testing.T) { |
| 41 | + // Subtests run sequentially: the parse command is a shared |
| 42 | + // package-level cobra.Command, so concurrent cmd.Do calls would |
| 43 | + // race on its flag and output state. |
| 44 | + query := filepath.Join(dir, "query.sql") |
| 45 | + golden := filepath.Join(dir, "stdout.json") |
| 46 | + |
| 47 | + var stdout, stderr bytes.Buffer |
| 48 | + code := cmd.Do([]string{"parse", "--dialect", dialect, query}, strings.NewReader(""), &stdout, &stderr) |
| 49 | + if code != 0 { |
| 50 | + t.Fatalf("sqlc parse exited %d: %s", code, stderr.String()) |
| 51 | + } |
| 52 | + |
| 53 | + if os.Getenv("SQLC_PARSE_UPDATE") != "" { |
| 54 | + if err := os.WriteFile(golden, stdout.Bytes(), 0644); err != nil { |
| 55 | + t.Fatal(err) |
| 56 | + } |
| 57 | + return |
| 58 | + } |
| 59 | + |
| 60 | + want, err := os.ReadFile(golden) |
| 61 | + if err != nil { |
| 62 | + t.Fatalf("reading golden (set SQLC_PARSE_UPDATE=1 to create it): %v", err) |
| 63 | + } |
| 64 | + if diff := cmp.Diff(string(want), stdout.String(), lineEndings()); diff != "" { |
| 65 | + t.Errorf("stdout mismatch (-want +got):\n%s", diff) |
| 66 | + } |
| 67 | + }) |
| 68 | + } |
| 69 | +} |
0 commit comments