bbj2/server/cmd/api/api_test.go

144 lines
2.8 KiB
Go

package api
import (
"log"
"net/http"
"os"
"reflect"
"strings"
"testing"
"time"
"git.tilde.town/tildetown/bbj2/server/cmd/config"
"git.tilde.town/tildetown/bbj2/server/cmd/db"
)
func createTestState() (opts *config.Options, err error) {
var dbFile *os.File
if dbFile, err = os.CreateTemp("", "bbj2-test"); err != nil {
return
}
opts = &config.Options{
Logger: log.New(os.Stdout, "bbj2 test", log.Lshortfile),
Config: config.Config{
Admins: []string{"jillValentine", "rebeccaChambers"},
Port: 666,
Host: "hell.cool",
InstanceName: "cool test zone",
AllowAnon: true,
DBPath: dbFile.Name(),
},
}
return
}
func TestUserRegister(t *testing.T) {
opts, err := createTestState()
if err != nil {
t.Fatalf("failed to create test state: %s", err.Error())
return
}
ts := []struct {
name string
setup func(opts *config.Options) error
assert func(t *testing.T) error
wantErr *HTTPError
}{
{
name: "user already exists",
setup: func(opts *config.Options) error {
return db.CreateUser(opts.DB, db.User{
Username: "albertwesker",
Hash: "1234abc",
Created: time.Now(),
})
},
assert: func(t *testing.T) error {
// TODO
return nil
},
wantErr: &HTTPError{Code: 403, Msg: "user already exists"},
},
}
for _, tt := range ts {
t.Run(tt.name, func(t *testing.T) {
teardown, err := db.Setup(opts)
if err != nil {
t.Fatalf("could not initialize DB: %s", err.Error())
return
}
defer teardown()
err = db.EnsureSchema(*opts)
if err != nil {
t.Fatalf("could not initialize DB: %s", err.Error())
return
}
err = tt.setup(opts)
if err != nil {
t.Fatalf("setup failed: %s", err.Error())
return
}
// TODO
err = tt.assert(t)
if err != nil {
t.Fatal(err.Error())
return
}
})
}
}
func TestInstanceInfo(t *testing.T) {
opts, err := createTestState()
if err != nil {
t.Fatalf("failed to create test state: %s", err.Error())
return
}
ts := []struct {
name string
wantData instanceInfo
wantErr *HTTPError
}{
{
name: "basic",
wantData: instanceInfo{
InstanceName: "cool test zone",
AllowAnon: true,
Admins: []string{"jillValentine", "rebeccaChambers"},
},
},
}
for _, tt := range ts {
t.Run(tt.name, func(t *testing.T) {
req, _ := http.NewRequest("GET", "", strings.NewReader(""))
api := &API{
Opts: *opts,
}
ctx := &ReqCtx{Req: req}
resp, err := api.InstanceInfo(ctx)
if tt.wantErr != nil && err != nil {
t.Errorf("got unwanted error: %s", err.Error())
return
}
ii, ok := resp.Data.(instanceInfo)
if !ok {
t.Errorf("could not cast data in %s", tt.name)
}
if !reflect.DeepEqual(ii, tt.wantData) {
t.Errorf("did not get expected data in %s", tt.name)
}
})
}
}