forked from go-gorm/playground
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain_test.go
61 lines (52 loc) · 1.35 KB
/
main_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
package main
import (
"log"
"net/http"
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
"gorm.io/gorm"
)
// GORM_REPO: https://github.com/go-gorm/gorm.git
// GORM_BRANCH: master
// TEST_DRIVERS: sqlite, mysql, postgres, sqlserver
func errHandler1(db *gorm.DB) gin.HandlerFunc {
return func(c *gin.Context) {
m := User{Name: "thing"}
errHandler2(db, m)(c)
}
}
func errHandler2(db *gorm.DB, model interface{}) gin.HandlerFunc {
return func(c *gin.Context) {
if err := db.Create(&model).Error; err != nil {
log.Fatalln("db.Create error:", err)
c.JSON(http.StatusInternalServerError, nil)
return
}
c.JSON(http.StatusOK, nil)
}
}
func noErrHandler(db *gorm.DB) gin.HandlerFunc {
return func(c *gin.Context) {
model := User{Name: "thing"}
if err := db.Create(&model).Error; err != nil {
log.Fatalln("db.Create error:", err)
c.JSON(http.StatusInternalServerError, nil)
return
}
c.JSON(http.StatusOK, nil)
}
}
func TestGORM(t *testing.T) {
r := gin.Default()
r.GET("/1", noErrHandler(DB))
r.GET("/2", errHandler1(DB))
w := httptest.NewRecorder()
req := httptest.NewRequest("GET", "/1", nil)
r.ServeHTTP(w, req)
log.Println("Req 1 status:", w.Result().StatusCode)
w2 := httptest.NewRecorder()
req2 := httptest.NewRequest("GET", "/2", nil)
r.ServeHTTP(w2, req2)
log.Println("Req 2 status:", w.Result().StatusCode)
}