This repository has been archived by the owner on Feb 7, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpostgres_test.go
101 lines (85 loc) · 2.09 KB
/
postgres_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
package metric
import (
"testing"
"time"
"github.com/go-pg/pg/v10"
. "github.com/smartystreets/goconvey/convey"
)
func TestSaveToDB(t *testing.T) {
Convey("test save data to db", t, func() {
Convey("should success save data", func() {
pg := NewPostgre("metric", "postgres", "postgres")
defer pg.Close()
pg.DropSchema()
pg.CreateSchema()
logs := []Log{
{
Request: "fake request 1",
TimeLocal: time.Now(),
HTTPReferer: "no referer",
},
{
Request: "fake request 2",
TimeLocal: time.Now(),
HTTPReferer: "no referer",
},
}
err := pg.Insert(logs)
if err != nil {
t.Fatalf("save data to db failure %v", err)
}
So(err, ShouldBeNil)
})
})
}
func TestPostgresRepo(t *testing.T) {
Convey("test postgres repository", t, func() {
fakePG := PostgresRepo{
db: pg.Connect(&pg.Options{
User: "postgres",
Password: "postgres",
Database: "metric",
}),
}
defer fakePG.db.Close()
Convey("should panic when postgre db backend is nil", func() {
panicPG := PostgresRepo{}
So(func() {
panicPG.Insert([]Log{
{Request: "fake request"},
})
}, ShouldPanicWith, dbError)
})
Convey("should success insert data into database", func() {
logs := []Log{
{Request: "test request 1"},
{Request: "test request 2"},
{Request: "test request 3"},
}
if err := fakePG.DropSchema(); err != nil {
t.Fatalf("drop table failure %v", err)
}
if err := fakePG.CreateSchema(); err != nil {
t.Fatalf("create table failure, %v", err)
}
err := fakePG.Insert(logs)
// select the data from database
count, err := fakePG.db.Model((*Log)(nil)).Count()
var inserted []Log
err = fakePG.db.Model(&inserted).Select()
So(err, ShouldBeNil)
So(count, ShouldEqual, 3)
for _, l := range inserted {
So(l, ShouldBeIn, logs)
}
})
})
}
func TestNewPostgre(t *testing.T) {
Convey("test NewPostgre function", t, func() {
Convey("should return a object", func() {
postgre := NewPostgre("metric", "postgre", "postgres")
So(postgre, ShouldNotBeNil)
})
})
}