Initial commit

This commit is contained in:
2023-05-14 19:44:16 +02:00
commit 15bc406494
29 changed files with 4346 additions and 0 deletions
+34
View File
@@ -0,0 +1,34 @@
package listautenti
import (
"github.com/gofiber/fiber/v2"
"git.phc.dm.unipi.it/phc/website/libs/sl"
"git.phc.dm.unipi.it/phc/website/server/database"
"git.phc.dm.unipi.it/phc/website/server/routes"
)
func Configure(l *sl.ServiceLocator) error {
db, err := sl.Use(l, database.Slot)
if err != nil {
return err
}
r, err := sl.Use(l, routes.Root)
if err != nil {
return err
}
r.Get("/api/lista-utenti", func(c *fiber.Ctx) error {
users, err := db.ReadUsers()
if err != nil {
return err
}
// TODO: Pre-process data to strip server only fields...
return c.JSON(users)
})
return nil
}
+104
View File
@@ -0,0 +1,104 @@
package listautenti_test
import (
"context"
"fmt"
"io"
"net"
"net/http"
"testing"
"gotest.tools/assert"
"github.com/gofiber/fiber/v2"
"github.com/valyala/fasthttp"
"github.com/valyala/fasthttp/fasthttputil"
"git.phc.dm.unipi.it/phc/website/libs/db"
"git.phc.dm.unipi.it/phc/website/libs/sl"
"git.phc.dm.unipi.it/phc/website/libs/util"
"git.phc.dm.unipi.it/phc/website/server/config"
"git.phc.dm.unipi.it/phc/website/server/database"
"git.phc.dm.unipi.it/phc/website/server/listautenti"
"git.phc.dm.unipi.it/phc/website/server/model"
"git.phc.dm.unipi.it/phc/website/server/routes"
)
func TestApiListaUtenti(t *testing.T) {
r := fiber.New()
memDB := &database.Memory{
Users: []model.User{
{
Id: "e39ad8d5-a087-4cb2-8fd7-5a6ca3f6a534",
Username: "claire-doe",
FullName: db.NewOption("Claire Doe"),
Email: db.NewOption("claire.doe@example.org"),
},
{
Id: "9b7109cd-95a1-41e9-a9f6-001a32c20ca1",
Username: "john-smith",
FullName: db.NewOption("John Smith"),
Email: db.NewOption("john.smith@example.org"),
},
},
}
l := sl.New()
sl.InjectValue(l, config.Slot, config.TestingProductionConfig)
sl.InjectValue[database.Database](l, database.Slot, memDB)
sl.InjectValue(l, routes.Root, fiber.Router(r))
listautenti.Configure(l)
// Try doing the request
req, err := http.NewRequest("GET", "http://localhost:4000/api/lista-utenti", nil)
if err != nil {
t.Error(err)
}
ln := fasthttputil.NewInmemoryListener()
defer ln.Close()
go func() {
err := fasthttp.Serve(ln, r.Handler())
if err != nil {
panic(fmt.Errorf("failed to serve: %v", err))
}
}()
client := http.Client{
Transport: &http.Transport{
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
return ln.Dial()
},
},
}
res, err := client.Do(req)
if err != nil {
t.Error(err)
}
body, err := io.ReadAll(res.Body)
if err != nil {
t.Error(err)
}
assert.Equal(t, string(body), util.CompactIndentedLines(`
[
{
"Id":"claire",
"FullName":"Claire Doe",
"Nickname":"claire-doe",
"Email":"claire.doe@example.org"
},
{
"Id":"john",
"FullName":"John Smith",
"Nickname":"john-smith",
"Email":"john.smith@example.org"
}
]
`))
}