-
Notifications
You must be signed in to change notification settings - Fork 24
/
logger_test.go
116 lines (96 loc) · 2.55 KB
/
logger_test.go
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
package gormzap
import (
"fmt"
"os"
"testing"
"time"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
_ "github.com/jinzhu/gorm/dialects/postgres"
"go.uber.org/zap"
"go.uber.org/zap/zaptest/observer"
"github.com/wantedly/gorm-zap/testhelper"
)
var pool *testhelper.DockerPool
func TestMain(m *testing.M) {
pool = testhelper.MustCreatePool()
os.Exit(m.Run())
}
func Test_Logger_Postgres(t *testing.T) {
fac, logs := observer.New(zap.DebugLevel)
zapLogger := zap.New(fac)
defer func() {
err := zapLogger.Sync()
if err != nil {
panic(err)
}
}()
conn := pool.MustCreateDB(testhelper.DialectPostgres)
defer conn.MustClose()
now := time.Now()
gorm.NowFunc = func() time.Time { return now }
db, err := gorm.Open(conn.Dialect, conn.URL)
if err != nil {
panic(err)
}
type Post struct {
Title, Body string
CreatedAt time.Time
}
db.AutoMigrate(&Post{})
cases := []struct {
run func() error
sql string
values []string
}{
{
run: func() error { return db.Create(&Post{Title: "awesome"}).Error },
sql: fmt.Sprintf(
"INSERT INTO %q (%q,%q,%q) VALUES ($1,$2,$3) RETURNING %q.*",
"posts", "title", "body", "created_at",
"posts",
),
values: []string{"awesome", "", now.String()},
},
{
run: func() error { return db.Model(&Post{}).Find(&[]*Post{}).Error },
sql: "SELECT * FROM \"posts\" ",
values: []string{},
},
{
run: func() error {
return db.Where(&Post{Title: "awesome", Body: "This is awesome post !"}).First(&Post{}).Error
},
sql: fmt.Sprintf(
"SELECT * FROM %q WHERE (%q = $1) AND (%q = $2) LIMIT 1",
"posts", "title", "body",
),
values: []string{"awesome", "This is awesome post !"},
},
}
db.SetLogger(New(zapLogger))
db.LogMode(true)
for _, c := range cases {
err := c.run()
if err != nil && err != gorm.ErrRecordNotFound {
t.Fatalf("Unexpected error: %v", err)
}
entries := logs.TakeAll()
if got, want := len(entries), 1; got != want {
t.Errorf("Logger logged %d items, want %d items", got, want)
}
fieldByName := entries[0].ContextMap()
if got, want := fieldByName["sql"].(string), c.sql; got != want {
t.Errorf("Logged sql was %q, want %q", got, want)
}
if got, want := len(fieldByName["values"].([]interface{})), len(c.values); got != want {
t.Errorf("Logged values has %d items, want %d items", got, want)
}
for i, want := range c.values {
got := fieldByName["values"].([]interface{})[i].(string)
if got != want {
t.Errorf("Logged values at %d was %v, want %v", i, got, want)
}
}
}
}