oef/handlers/handlers_test.go

180 lines
3.5 KiB
Go

package handlers
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"time"
"git.andreafazzi.eu/andrea/oef/config"
"git.andreafazzi.eu/andrea/oef/orm"
"git.andreafazzi.eu/andrea/oef/renderer"
jwt "github.com/dgrijalva/jwt-go"
"github.com/jinzhu/gorm"
"github.com/remogatto/prettytest"
)
var (
token string
handlers *Handlers
)
// Start of setup
type testSuite struct {
prettytest.Suite
}
func authenticate(request *http.Request, tokenString string, signingKey string) (*http.Request, error) {
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
return []byte(signingKey), nil
})
if err != nil {
return nil, err
}
ctx := request.Context()
ctx = context.WithValue(ctx, "user", token)
return request.WithContext(ctx), nil
}
func requestToken(handlers *Handlers) string {
req, err := http.NewRequest("GET", "/get_token", nil)
if err != nil {
panic(err)
}
req.SetBasicAuth("admin", "admin")
rr := httptest.NewRecorder()
handlers.GetToken([]byte(config.Config.Keys.JWTSigningKey)).ServeHTTP(rr, req)
var data struct {
Token string
}
if err := json.Unmarshal(rr.Body.Bytes(), &data); err != nil {
panic(err)
}
return data.Token
}
func TestRunner(t *testing.T) {
prettytest.Run(
t,
new(testSuite),
)
}
func (t *testSuite) BeforeAll() {
var (
db *gorm.DB
err error
)
models := []interface{}{
&orm.Question{},
&orm.Answer{},
&orm.Contest{},
&orm.Participant{},
&orm.School{},
&orm.Response{},
&orm.User{},
&orm.Category{},
&orm.Region{},
}
// Initialize the ORM
connected := false
for !connected {
time.Sleep(5 * time.Second)
db, err = orm.New("oef:oef@/oef_test?charset=utf8&parseTime=True&loc=Local")
if err != nil {
continue
}
connected = true
}
orm.Use(db)
orm.AutoMigrate()
// Map the handlers
if err := orm.MapHandlers(models); err != nil {
panic(err)
}
// Initialize the renderers
htmlRenderer, err := renderer.NewHTMLRenderer("./testdata/templates/")
if err != nil {
panic(err)
}
renderer.Render = make(map[string]func(http.ResponseWriter, *http.Request, interface{}, ...url.Values))
renderer.Render["html"] = func(w http.ResponseWriter, r *http.Request, data interface{}, options ...url.Values) {
htmlRenderer.Render(w, r, data, options...)
}
// Load the configuration
err = config.ReadFile("testdata/config.yaml", config.Config)
if err != nil {
panic(err)
}
config.Config.LogLevel = config.LOG_LEVEL_OFF
handlers = NewHandlers(config.Config, models)
token = requestToken(handlers)
if err := orm.MapHandlers(models); err != nil {
panic(err)
}
}
func (t *testSuite) TestReadAllContests() {
req, err := http.NewRequest("GET", "/contests?format=html&tpl_layout=base&tpl_content=contests", nil)
if err != nil {
panic(err)
}
pattern := PathPattern{
"/%s",
"/%s?format=html&tpl_layout=base&tpl_content=%s",
[]string{"GET"}, PermissionReadAll,
}
rr := httptest.NewRecorder()
req, err = authenticate(req, token, config.Config.Keys.JWTSigningKey)
// tkn, err := jwt.Parse(token, func(token *jwt.Token) (interface{}, error) {
// return []byte("secret"), nil
// })
// if err != nil {
// panic(err)
// }
// ctx := req.Context()
// ctx = context.WithValue(ctx, "user", tkn)
// req = req.WithContext(ctx)
t.Nil(err)
if err != nil {
handlers.modelHandler("contests", pattern).ServeHTTP(rr, req)
t.Equal(http.StatusOK, rr.Code)
if !t.Failed() {
t.True(strings.Contains(rr.Body.String(), "JUNIOR Contest"))
}
}
}