-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver_test.go
79 lines (61 loc) · 1.96 KB
/
server_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
package ginboot
import (
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
)
func TestServer_New(t *testing.T) {
gin.SetMode(gin.TestMode)
server := New()
assert.NotNil(t, server)
assert.NotNil(t, server.engine)
}
func TestServer_SetBasePath(t *testing.T) {
gin.SetMode(gin.TestMode)
server := New()
// Set base path before registering routes
server.SetBasePath("/api/v1")
// Register route after setting base path
server.Group("").GET("/test", func(c *Context) {
c.Status(200)
})
w := httptest.NewRecorder()
req := httptest.NewRequest("GET", "/api/v1/test", nil)
server.engine.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code)
}
func TestServer_CustomCORS(t *testing.T) {
gin.SetMode(gin.TestMode)
server := New()
origins := []string{"http://localhost:3000"}
methods := []string{"GET", "POST"}
headers := []string{"Content-Type"}
maxAge := 24 * time.Hour
server.CustomCORS(origins, methods, headers, maxAge)
server.engine.GET("/test", func(c *gin.Context) {
c.Status(200)
})
w := httptest.NewRecorder()
req := httptest.NewRequest("OPTIONS", "/test", nil)
req.Header.Set("Origin", "http://localhost:3000")
req.Header.Set("Access-Control-Request-Method", "GET")
server.engine.ServeHTTP(w, req)
assert.Equal(t, http.StatusNoContent, w.Code)
assert.Equal(t, "http://localhost:3000", w.Header().Get("Access-Control-Allow-Origin"))
assert.Equal(t, "GET,POST", w.Header().Get("Access-Control-Allow-Methods"))
assert.Equal(t, "Content-Type", w.Header().Get("Access-Control-Allow-Headers"))
assert.Equal(t, "86400", w.Header().Get("Access-Control-Max-Age"))
}
func TestServer_Start(t *testing.T) {
gin.SetMode(gin.TestMode)
server := New()
// Test invalid port
err := server.Start(-1)
assert.Error(t, err)
// Note: We can't easily test successful server start in a unit test
// as it blocks. In a real scenario, you might want to use integration tests
// for this functionality.
}