-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathe2e_postgres_nodb_test.go
More file actions
84 lines (72 loc) · 2.58 KB
/
e2e_postgres_nodb_test.go
File metadata and controls
84 lines (72 loc) · 2.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
// Package main provides end-to-end tests for the gormdb2struct tool.
package main
import (
"os"
"path/filepath"
"runtime"
"strings"
"testing"
"gorm.io/gen"
)
// TestPostgresDbInitTemplateNoDB validates the Postgres DbInit code generation
// without connecting to any Postgres server by fabricating a generator with
// fake model names and invoking generatePostgresDbInit directly.
func TestPostgresDbInitTemplateNoDB(t *testing.T) {
if testing.Short() {
t.Skip("skipping postgres template test in short mode")
}
// Create an OutPath under the project root so that package name resolution is simple.
outPath := filepath.Join(projectRootPG(t), "generated_pg_nodb")
if err := os.MkdirAll(outPath, 0o755); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = os.RemoveAll(outPath) })
// Create a minimal gen.Generator and populate its Data map with fake model names.
g := gen.NewGenerator(gen.Config{
OutPath: outPath,
ModelPkgPath: filepath.Join(outPath, "models"),
})
// NewGenerator already initializes g.Data (map[string]*genInfo). We only need keys; values can be nil.
g.Data["Foo"] = nil
g.Data["Bar"] = nil
// Prepare a minimal Postgres config with IncludeAutoMigrate enabled.
cfg := ConversionConfig{
IncludeAutoMigrate: true,
DbHost: "db.example.local",
DbPort: 5432,
DbName: "unit_test_db",
DbUser: "test_user",
DbPassword: "secret",
DbSSLMode: false,
}
// Generate the db.go initializer using the template function.
generatePostgresDbInit(cfg, g)
// Verify the output file was created.
outFile := filepath.Join(outPath, "db.go")
b, err := os.ReadFile(outFile)
if err != nil {
t.Fatalf("reading generated db.go: %v", err)
}
content := string(b)
pkgBase := filepath.Base(outPath)
// Assertions on generated content.
mustContain(t, content, "Code generated by gormdb2struct; DO NOT EDIT.")
mustContain(t, content, "package "+pkgBase)
mustContain(t, content, "\""+pkgBase+"/models\"")
// Ensure AutoMigrate contains our fake models
mustContain(t, content, "&models.Foo{}")
mustContain(t, content, "&models.Bar{}")
// Ensure DSN is constructed via utilities when optional DSN is not provided
mustContain(t, content, "DbDSN(")
}
func mustContain(t *testing.T, s, sub string) {
t.Helper()
if !strings.Contains(s, sub) {
t.Fatalf("expected generated content to contain %q, but it did not", sub)
}
}
// projectRootPG returns the repo root directory (same strategy as the SQLite test)
func projectRootPG(_ *testing.T) string {
_, file, _, _ := runtime.Caller(0)
return filepath.Dir(file)
}