genofire/hs_monolith
genofire
/
hs_monolith
Archived
1
0
Fork 0
This repository has been archived on 2020-09-27. You can view files and clone it, but cannot push or open issues or pull requests.
hs_monolith/test/http.go

68 lines
1.4 KiB
Go
Raw Normal View History

2017-03-25 16:09:17 +01:00
package test
// Request a easy manager to test REST-API
import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
2017-03-30 19:05:33 +02:00
"github.com/genofire/hs_master-kss-monolith/lib/database"
2017-03-25 16:09:17 +01:00
"github.com/stretchr/testify/assert"
goji "goji.io"
)
//Init to initialisieren a API
func Init(t *testing.T) (assertion *assert.Assertions, router *goji.Mux) {
assertion = assert.New(t)
2017-03-30 19:05:33 +02:00
database.Open(database.Config{
Type: "sqlite3",
Logging: true,
2017-03-30 19:05:33 +02:00
Connection: ":memory:",
})
2017-03-25 16:09:17 +01:00
router = goji.NewMux()
return
}
2017-03-30 19:05:33 +02:00
func Close() {
database.Close()
}
2017-03-25 16:09:17 +01:00
type Request struct {
req *http.Request
cookies []*http.Cookie
router *goji.Mux
}
// NewSession to get a new easy manager
func NewSession(router *goji.Mux) *Request {
return &Request{router: router}
}
// JSONRequest send request to router
func (r *Request) JSONRequest(method string, url string, body interface{}) (jsonResult interface{}, res *http.Response) {
jsonObj, _ := json.Marshal(body)
req, _ := http.NewRequest(method, url, bytes.NewReader(jsonObj))
req.Header.Set("Content-Type", "application/json")
for _, c := range r.cookies {
req.AddCookie(c)
}
w := httptest.NewRecorder()
r.router.ServeHTTP(w, req)
res = w.Result()
cookies := res.Cookies()
if len(cookies) > 0 {
r.cookies = cookies
}
json.NewDecoder(w.Body).Decode(&jsonResult)
return
}
// Clean to clean the current session
func (r *Request) Clean() {
r.cookies = nil
}