92 lines
2 KiB
Go
92 lines
2 KiB
Go
package main
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"testing"
|
|
)
|
|
|
|
func testApp(t *testing.T) *App {
|
|
t.Helper()
|
|
db, err := initDB(":memory:")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
t.Cleanup(func() { db.Close() })
|
|
db.Exec(`CREATE TABLE IF NOT EXISTS config (key TEXT PRIMARY KEY, value TEXT NOT NULL)`)
|
|
return &App{
|
|
db: db,
|
|
secret: "test-secret",
|
|
tokenExpiry: 24,
|
|
broker: newBroker(),
|
|
}
|
|
}
|
|
|
|
func testAdminUser(t *testing.T, app *App) *User {
|
|
t.Helper()
|
|
hash, _ := hashPassword("admin123")
|
|
u, err := app.createUser("oberon@athens.example", "Oberon", hash, []string{"admin"}, []int{})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return u
|
|
}
|
|
|
|
func testUserWithRoles(t *testing.T, app *App, name string, roles []string, deptIDs []int) *User {
|
|
t.Helper()
|
|
email := strings.ToLower(name) + "@athens.example"
|
|
hash, _ := hashPassword(name + "123")
|
|
u, err := app.createUser(email, name, hash, roles, deptIDs)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return u
|
|
}
|
|
|
|
func testToken(t *testing.T, app *App, user *User) string {
|
|
t.Helper()
|
|
token, err := app.signToken(user)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return token
|
|
}
|
|
|
|
func testMux(app *App) *http.ServeMux {
|
|
mux := http.NewServeMux()
|
|
app.registerRoutes(mux)
|
|
return mux
|
|
}
|
|
|
|
func testRequest(method, path string, body any) *http.Request {
|
|
var buf bytes.Buffer
|
|
if body != nil {
|
|
json.NewEncoder(&buf).Encode(body)
|
|
}
|
|
req := httptest.NewRequest(method, path, &buf)
|
|
req.Header.Set("Content-Type", "application/json")
|
|
return req
|
|
}
|
|
|
|
func testAuthRequest(method, path string, body any, token string) *http.Request {
|
|
req := testRequest(method, path, body)
|
|
req.Header.Set("Authorization", "Bearer "+token)
|
|
return req
|
|
}
|
|
|
|
func itoa(i int) string {
|
|
return fmt.Sprintf("%d", i)
|
|
}
|
|
|
|
func parseJSON(t *testing.T, w *httptest.ResponseRecorder) map[string]any {
|
|
t.Helper()
|
|
var result map[string]any
|
|
if err := json.Unmarshal(w.Body.Bytes(), &result); err != nil {
|
|
t.Fatalf("parse JSON: %v\nbody: %s", err, w.Body.String())
|
|
}
|
|
return result
|
|
}
|