-
Notifications
You must be signed in to change notification settings - Fork 27
/
tracer_test.go
101 lines (89 loc) · 2.45 KB
/
tracer_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
//go:build go1.10
// +build go1.10
package proxy_test
import (
"bufio"
"bytes"
"database/sql"
"log"
"regexp"
"testing"
proxy "github.com/shogo82148/go-sql-proxy"
)
func TestTraceProxy(t *testing.T) {
buf := &bytes.Buffer{}
log.SetOutput(buf)
log.SetFlags(log.Lshortfile)
proxy.RegisterTracer()
db, err := sql.Open("fakedb:trace", `{"name":"trace"}`)
if err != nil {
t.Fatalf("Open filed: %v", err)
}
_, err = db.Exec("CREATE TABLE t1 (id INTEGER PRIMARY KEY)")
if err != nil {
t.Fatalf("create table failed: %v", err)
}
// test for transactions
err = func() error {
tx, err := db.Begin()
if err != nil {
return err
}
defer tx.Rollback()
if _, err := tx.Exec("INSERT INTO t1 (id) VALUES(?)", 1); err != nil {
return err
}
rows, err := tx.Query("SELECT id FROM t1 WHERE id = ?", 1)
if err != nil {
return err
}
for rows.Next() {
}
rows.Close()
return tx.Commit()
}()
if err != nil {
t.Fatalf("do failed: %v", err)
}
// test for rollback
err = func() error {
tx, err := db.Begin()
if err != nil {
return err
}
return tx.Rollback()
}()
if err != nil {
t.Fatalf("do failed: %v", err)
}
if err := db.Close(); err != nil {
t.Fatal(err)
}
timeComponent := `\(\d+(?:\.\d+)?[^\)]+\)`
expected := []*regexp.Regexp{
// Fake time component with (\d+\.\d+[^\)]+)
regexp.MustCompile(`tracer_test.go:28: Open 0x[0-9a-f]+ ` + timeComponent),
regexp.MustCompile(`tracer_test.go:28: Exec 0x[0-9a-f]+: CREATE TABLE t1 \(id INTEGER PRIMARY KEY\); args = \[\] ` + timeComponent),
regexp.MustCompile(`tracer_test.go:35: Begin 0x[0-9a-f]+ ` + timeComponent),
regexp.MustCompile(`tracer_test.go:40: Exec 0x[0-9a-f]+: INSERT INTO t1 \(id\) VALUES\(\?\); args = \[1\] ` + timeComponent),
regexp.MustCompile(`tracer_test.go:43: Query 0x[0-9a-f]+: SELECT id FROM t1 WHERE id = \?; args = \[1\] ` + timeComponent),
regexp.MustCompile(`tracer_test.go:50: Commit 0x[0-9a-f]+ ` + timeComponent),
regexp.MustCompile(`tracer_test.go:58: Begin 0x[0-9a-f]+ ` + timeComponent),
regexp.MustCompile(`tracer_test.go:62: Rollback 0x[0-9a-f]+ ` + timeComponent),
regexp.MustCompile(`.*:\d+: Close 0x[0-9a-f]+ ` + timeComponent),
}
scanner := bufio.NewScanner(buf)
i := 0
for scanner.Scan() {
line := scanner.Text()
t.Log(line)
if i >= len(expected) {
t.Errorf("Got more lines than expected (%s)", line)
break
}
if !expected[i].MatchString(line) {
t.Errorf("\ngot: %s\nwant: %s", line, expected[i])
}
i++
}
}