photoprism/internal/api/api_test.go

94 lines
2.6 KiB
Go
Raw Normal View History

package api
import (
2021-08-11 10:47:52 +02:00
"bytes"
"encoding/json"
"github.com/photoprism/photoprism/internal/form"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
"github.com/gin-gonic/gin"
"github.com/photoprism/photoprism/internal/config"
"github.com/photoprism/photoprism/internal/service"
"github.com/sirupsen/logrus"
)
2020-12-18 13:05:48 +01:00
// NewApiTest returns new API test helper.
func NewApiTest() (app *gin.Engine, router *gin.RouterGroup, conf *config.Config) {
gin.SetMode(gin.TestMode)
app = gin.New()
router = app.Group("/api/v1")
return app, router, service.Config()
}
2021-08-11 10:47:52 +02:00
// NewAdminApiTest returns new API test helper with authenticated admin session.
2020-12-18 13:05:48 +01:00
func NewAdminApiTest() (app *gin.Engine, router *gin.RouterGroup, conf *config.Config, sessId string) {
2021-08-11 10:47:52 +02:00
return NewAuthApiTest("admin", "photoprism")
}
2021-08-11 10:47:52 +02:00
// NewAuthApiTest returns new API test helper with authenticated admin session.
func NewAuthApiTest(username string, password string) (app *gin.Engine, router *gin.RouterGroup, conf *config.Config, sessId string) {
2020-12-18 13:05:48 +01:00
app = gin.New()
router = app.Group("/api/v1")
CreateSession(router)
2021-08-11 10:47:52 +02:00
f := form.Login{
UserName: username,
Password: password,
}
loginStr, err := json.Marshal(f)
if err != nil {
log.Fatal(err)
}
reader := bytes.NewReader(loginStr)
2020-12-18 13:05:48 +01:00
req, _ := http.NewRequest("POST", "/api/v1/session", reader)
w := httptest.NewRecorder()
app.ServeHTTP(w, req)
sessId = w.Header().Get("X-Session-ID")
gin.SetMode(gin.TestMode)
return app, router, service.Config(), sessId
}
// Performs API request with empty request body.
2018-11-18 19:18:19 +01:00
// See https://medium.com/@craigchilds94/testing-gin-json-responses-1f258ce3b0b1
func PerformRequest(r http.Handler, method, path string) *httptest.ResponseRecorder {
req, _ := http.NewRequest(method, path, nil)
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
return w
2018-11-17 12:29:01 +01:00
}
2020-12-18 13:05:48 +01:00
// Performs authenticated API request with empty request body.
func AuthenticatedRequest(r http.Handler, method, path, sess string) *httptest.ResponseRecorder {
req, _ := http.NewRequest(method, path, nil)
req.Header.Add("X-Session-ID", sess)
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
return w
}
// Performs API request including request body as string.
func PerformRequestWithBody(r http.Handler, method, path, body string) *httptest.ResponseRecorder {
reader := strings.NewReader(body)
req, _ := http.NewRequest(method, path, reader)
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
return w
}
func TestMain(m *testing.M) {
log = logrus.StandardLogger()
log.SetLevel(logrus.DebugLevel)
c := config.TestConfig()
service.SetConfig(c)
code := m.Run()
_ = c.CloseDb()
os.Exit(code)
}