-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathapi_test.go
92 lines (73 loc) · 2.15 KB
/
api_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
package api
import (
"bytes"
"encoding/json"
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
"github.com/riotpot/pkg/api"
"github.com/riotpot/pkg/utils"
)
func SetupRouter() *gin.Engine {
// Create a router
router := gin.Default()
group := router.Group("/api/")
// Add the proxy routes
api.ProxiesRouter.AddToGroup(group)
api.ServicesRouter.AddToGroup(group)
return router
}
func TestApiProxy(t *testing.T) {
expected := &api.CreateProxy{
Port: 8080,
Network: utils.TCP.String(),
}
router := SetupRouter()
w := httptest.NewRecorder()
// POST request to create a new proxy
body, _ := json.Marshal(expected)
req, _ := http.NewRequest("POST", "/api/proxies/", bytes.NewBuffer(body))
router.ServeHTTP(w, req)
response, _ := ioutil.ReadAll(w.Body)
// Assert the body of the created proxy is equal to the response
outputPost := &api.CreateProxy{}
json.Unmarshal(response, outputPost)
assert.Equal(t, expected, outputPost)
// GET all the proxies
req, _ = http.NewRequest("GET", "/api/proxies/", nil)
router.ServeHTTP(w, req)
response, _ = ioutil.ReadAll(w.Body)
// Assert we got 1 proxy in total
outputGet := &[]api.CreateProxy{}
json.Unmarshal(response, outputGet)
assert.Equal(t, 1, len(*outputGet))
}
func TestApiService(t *testing.T) {
expected := &api.CreateService{
Name: "Test Service",
Host: "localhost",
Port: 8080,
Network: utils.TCP.String(),
}
router := SetupRouter()
w := httptest.NewRecorder()
// POST to create a new service
body, _ := json.Marshal(expected)
req, _ := http.NewRequest("POST", "/api/services/", bytes.NewBuffer(body))
router.ServeHTTP(w, req)
response, _ := ioutil.ReadAll(w.Body)
// Assert the body of the created service is equal to the response
outputPost := &api.CreateService{}
json.Unmarshal(response, outputPost)
assert.Equal(t, expected, outputPost)
// Request all services
req, _ = http.NewRequest("GET", "/api/services/", nil)
router.ServeHTTP(w, req)
response, _ = ioutil.ReadAll(w.Body)
outputGet := &[]api.CreateService{}
json.Unmarshal(response, outputGet)
assert.Equal(t, 1, len(*outputGet))
}