package api import ( "log" "net/http" "os" "reflect" "strings" "testing" "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 opts config.Options setup func(opts *config.Options) error assert func(t *testing.T) error wantErr *HTTPError }{ { name: "user already exists", opts: *opts, setup: func(opts *config.Options) error { // TODO return nil }, 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() // TODO }) } } func TestInstanceInfo(t *testing.T) { opts, err := createTestState() if err != nil { t.Fatalf("failed to create test state: %s", err.Error()) return } teardown, err := db.Setup(*opts) if err != nil { t.Fatalf("could not initialize DB: %s", err.Error()) return } defer teardown() ts := []struct { name string opts config.Options wantData instanceInfo wantErr *HTTPError }{ { name: "basic", opts: *opts, 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: tt.opts, Req: req, } resp, err := api.InstanceInfo() 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) } }) } }