package test import ( "bytes" "encoding/json" "net/http" "net/http/httptest" "os" "testing" "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" libsession "dev.sum7.eu/sum7/warehost/lib/session" ) //Init to initialisieren a API func Init(t *testing.T) (assertion *assert.Assertions, dbconnection *gorm.DB, router *goji.Mux) { assertion = assert.New(t) libconfig.ReadConfigFile(os.Getenv("GOPATH") + "/src/dev.sum7.eu/sum7/warehost/cmd/warehost/config.yml.example") log.NewLogger(libconfig.Data.Log.Path) // Session mgmt libsession.Init() go libsession.Stop() // Database dbconnection, err := gorm.Open("postgres", libconfig.Data.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(libconfig.Data.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)) 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 }