package api import ( "encoding/json" "io" "log" "net/http" "net/url" "strings" "testing" "git.freecumextremist.com/grumbulon/pomme/internal" "git.freecumextremist.com/grumbulon/pomme/internal/db" "github.com/stretchr/testify/assert" ) type response struct { Username string `json:"username"` Message string `json:"message"` Status int `json:"status"` } type accountTest struct { username string password string } func TestInit(t *testing.T) { tester := accountTest{ username: autoUname(), password: "merde", } tester.TestMakeAccount(t) tester.TestLogin(t) tester.TestLogout(t) tester.CleanUpDb() } func (a *accountTest) TestMakeAccount(t *testing.T) { var target response client := http.Client{} form := url.Values{} form.Add("username", a.username) form.Add("password", "test") if req, err := http.NewRequest(http.MethodPost, "http://localhost:3010/api/create", strings.NewReader(form.Encode())); err == nil { req.Header.Add("Content-Type", "application/x-www-form-urlencoded") resp, err := client.Do(req) if err != nil { assert.NotNil(t, err) } respBody, _ := io.ReadAll(resp.Body) err = json.Unmarshal(respBody, &target) if err != nil { assert.NotNil(t, err) } log.Println(target) assert.Equal(t, http.StatusCreated, target.Status) } } func (a *accountTest) TestLogin(t *testing.T) { var target response client := http.Client{} form := url.Values{} form.Add("username", a.username) form.Add("password", "test") if req, err := http.NewRequest(http.MethodPost, "http://localhost:3010/api/login", strings.NewReader(form.Encode())); err == nil { req.Header.Add("Content-Type", "application/x-www-form-urlencoded") resp, err := client.Do(req) if err != nil { assert.NotNil(t, err) } respBody, _ := io.ReadAll(resp.Body) err = json.Unmarshal(respBody, &target) if err != nil { assert.NotNil(t, err) } log.Println(target) assert.Equal(t, http.StatusOK, target.Status) } } func (a *accountTest) TestLogout(t *testing.T) { var target response client := http.Client{} form := url.Values{} form.Add("username", a.username) if req, err := http.NewRequest(http.MethodPost, "http://localhost:3010/api/logout", strings.NewReader(form.Encode())); err == nil { req.Header.Add("Content-Type", "application/x-www-form-urlencoded") resp, err := client.Do(req) if err != nil { assert.NotNil(t, err) } respBody, _ := io.ReadAll(resp.Body) err = json.Unmarshal(respBody, &target) if err != nil { assert.NotNil(t, err) } log.Println(target) assert.Equal(t, http.StatusOK, target.Status) } } // currently does not work. func (a *accountTest) CleanUpDb() { var user internal.User db := db.InitDb() db.Where("username = ?", a.username).First(&user) if user.Username != "" { db.Delete(&user, user.ID) } }