package test import ( "bytes" "encoding/json" "net/http" "net/http/httptest" "testing" "github.com/astaxie/session" _ "github.com/astaxie/session/providers/memory" "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/postgres" "github.com/stretchr/testify/assert" "goji.io" libconfig "dev.sum7.eu/sum7/warehost/config" libapi "dev.sum7.eu/sum7/warehost/lib/api" log "dev.sum7.eu/sum7/warehost/lib/log" ) //Init to initialisieren a API func Init(t *testing.T) (assertion *assert.Assertions, config *libconfig.Config, sessions *session.Manager, dbconnection *gorm.DB, router *goji.Mux) { assertion = assert.New(t) config = libconfig.ReadConfigFile("../cmd/warehost/config.yml.example") log.NewLogger(config.Log.Path) // Session mgmt sessions, err := session.NewManager("memory", "session", 3600) go sessions.GC() assertion.NoError(err) // Database dbconnection, err = gorm.Open("postgres", config.Database) assertion.NoError(err) dbconnection.Callback().Create().Remove("gorm:update_time_stamp") dbconnection.Callback().Update().Remove("gorm:update_time_stamp") dbconnection.SingularTable(true) dbconnection.LogMode(config.DatabaseDebug) router = goji.NewMux() return } // Request a easy manager to test REST-API 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 libapi.JSONResult, res *http.Response) { jsonObj, _ := json.Marshal(body) req, _ := http.NewRequest(method, url, bytes.NewReader(jsonObj)) for _, c := range r.cookies { req.AddCookie(c) } w := httptest.NewRecorder() r.router.ServeHTTP(w, req) res = w.Result() r.cookies = res.Cookies() json.NewDecoder(w.Body).Decode(&jsonResult) return } // CleanSession to clean the current session func (r *Request) CleanSession() { r.cookies = nil }