vet_test.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. //go:build examples
  2. package main
  3. import (
  4. "bytes"
  5. "context"
  6. "fmt"
  7. "os"
  8. "path/filepath"
  9. "strings"
  10. "testing"
  11. "github.com/sqlc-dev/sqlc/internal/cmd"
  12. "github.com/sqlc-dev/sqlc/internal/sqltest"
  13. "github.com/sqlc-dev/sqlc/internal/sqltest/local"
  14. )
  15. func findSchema(t *testing.T, path string) (string, bool) {
  16. schemaFile := filepath.Join(path, "schema.sql")
  17. if _, err := os.Stat(schemaFile); !os.IsNotExist(err) {
  18. return schemaFile, true
  19. }
  20. schemaDir := filepath.Join(path, "schema")
  21. if _, err := os.Stat(schemaDir); !os.IsNotExist(err) {
  22. return schemaDir, true
  23. }
  24. return "", false
  25. }
  26. func TestExamplesVet(t *testing.T) {
  27. t.Parallel()
  28. ctx := context.Background()
  29. examples, err := filepath.Abs(filepath.Join("..", "..", "examples"))
  30. if err != nil {
  31. t.Fatal(err)
  32. }
  33. files, err := os.ReadDir(examples)
  34. if err != nil {
  35. t.Fatal(err)
  36. }
  37. for _, replay := range files {
  38. if !replay.IsDir() {
  39. continue
  40. }
  41. tc := replay.Name()
  42. t.Run(tc, func(t *testing.T) {
  43. t.Parallel()
  44. path := filepath.Join(examples, tc)
  45. if tc != "kotlin" && tc != "python" {
  46. if s, found := findSchema(t, filepath.Join(path, "sqlite")); found {
  47. dsn := fmt.Sprintf("file:%s?mode=memory&cache=shared", tc)
  48. db, cleanup := sqltest.CreateSQLiteDatabase(t, dsn, []string{s})
  49. defer db.Close()
  50. defer cleanup()
  51. }
  52. if s, found := findSchema(t, filepath.Join(path, "mysql")); found {
  53. uri := local.MySQL(t, []string{s})
  54. os.Setenv(fmt.Sprintf("VET_TEST_EXAMPLES_MYSQL_%s", strings.ToUpper(tc)), uri)
  55. }
  56. if s, found := findSchema(t, filepath.Join(path, "postgresql")); found {
  57. uri := local.PostgreSQL(t, []string{s})
  58. os.Setenv(fmt.Sprintf("VET_TEST_EXAMPLES_POSTGRES_%s", strings.ToUpper(tc)), uri)
  59. }
  60. }
  61. var stderr bytes.Buffer
  62. opts := &cmd.Options{
  63. Stderr: &stderr,
  64. Env: cmd.Env{},
  65. }
  66. err := cmd.Vet(ctx, path, "", opts)
  67. if err != nil {
  68. t.Fatalf("sqlc vet failed: %s %s", err, stderr.String())
  69. }
  70. })
  71. }
  72. }