Skip to content

Commit

Permalink
fixes + db changes (#204)
Browse files Browse the repository at this point in the history
* fixes + db changes

* make duration more lenient
  • Loading branch information
tsmethurst committed Sep 10, 2021
1 parent 446dbb7 commit e681aac
Show file tree
Hide file tree
Showing 16 changed files with 401 additions and 78 deletions.
56 changes: 55 additions & 1 deletion internal/api/client/account/account_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
package account_test

import (
"bytes"
"fmt"
"net/http"
"net/http/httptest"

"github.com/gin-gonic/gin"
"github.com/sirupsen/logrus"
"github.com/stretchr/testify/suite"
"github.com/superseriousbusiness/gotosocial/internal/api/client/account"
Expand All @@ -9,11 +15,12 @@ import (
"github.com/superseriousbusiness/gotosocial/internal/db"
"github.com/superseriousbusiness/gotosocial/internal/federation"
"github.com/superseriousbusiness/gotosocial/internal/gtsmodel"
"github.com/superseriousbusiness/gotosocial/internal/oauth"
"github.com/superseriousbusiness/gotosocial/internal/processing"
"github.com/superseriousbusiness/gotosocial/internal/typeutils"
"github.com/superseriousbusiness/gotosocial/testrig"
)

// nolint
type AccountStandardTestSuite struct {
// standard suite interfaces
suite.Suite
Expand All @@ -37,3 +44,50 @@ type AccountStandardTestSuite struct {
// module being tested
accountModule *account.Module
}

func (suite *AccountStandardTestSuite) SetupSuite() {
suite.testTokens = testrig.NewTestTokens()
suite.testClients = testrig.NewTestClients()
suite.testApplications = testrig.NewTestApplications()
suite.testUsers = testrig.NewTestUsers()
suite.testAccounts = testrig.NewTestAccounts()
suite.testAttachments = testrig.NewTestAttachments()
suite.testStatuses = testrig.NewTestStatuses()
}

func (suite *AccountStandardTestSuite) SetupTest() {
suite.config = testrig.NewTestConfig()
suite.db = testrig.NewTestDB()
suite.storage = testrig.NewTestStorage()
suite.log = testrig.NewTestLog()
suite.federator = testrig.NewTestFederator(suite.db, testrig.NewTestTransportController(testrig.NewMockHTTPClient(nil), suite.db), suite.storage)
suite.processor = testrig.NewTestProcessor(suite.db, suite.storage, suite.federator)
suite.accountModule = account.New(suite.config, suite.processor, suite.log).(*account.Module)
testrig.StandardDBSetup(suite.db, nil)
testrig.StandardStorageSetup(suite.storage, "../../../../testrig/media")
}

func (suite *AccountStandardTestSuite) TearDownTest() {
testrig.StandardDBTeardown(suite.db)
testrig.StandardStorageTeardown(suite.storage)
}

func (suite *AccountStandardTestSuite) newContext(recorder *httptest.ResponseRecorder, requestMethod string, requestBody []byte, requestPath string, bodyContentType string) *gin.Context {
ctx, _ := gin.CreateTestContext(recorder)

ctx.Set(oauth.SessionAuthorizedAccount, suite.testAccounts["local_account_1"])
ctx.Set(oauth.SessionAuthorizedToken, oauth.DBTokenToToken(suite.testTokens["local_account_1"]))
ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplications["application_1"])
ctx.Set(oauth.SessionAuthorizedUser, suite.testUsers["local_account_1"])

baseURI := fmt.Sprintf("%s://%s", suite.config.Protocol, suite.config.Host)
requestURI := fmt.Sprintf("%s/%s", baseURI, requestPath)

ctx.Request = httptest.NewRequest(http.MethodPatch, requestURI, bytes.NewReader(requestBody)) // the endpoint we're hitting

if bodyContentType != "" {
ctx.Request.Header.Set("Content-Type", bodyContentType)
}

return ctx
}
3 changes: 2 additions & 1 deletion internal/api/client/account/accountupdate.go
Original file line number Diff line number Diff line change
Expand Up @@ -107,14 +107,15 @@ func (m *Module) AccountUpdateCredentialsPATCHHandler(c *gin.Context) {
}
l.Tracef("retrieved account %+v", authed.Account.ID)

l.Debugf("parsing request form %s", c.Request.Form)
form := &model.UpdateCredentialsRequest{}
if err := c.ShouldBind(&form); err != nil || form == nil {
l.Debugf("could not parse form from request: %s", err)
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}

l.Debugf("parsed request form %+v", form)

// if everything on the form is nil, then nothing has been set and we shouldn't continue
if form.Discoverable == nil && form.Bot == nil && form.DisplayName == nil && form.Note == nil && form.Avatar == nil && form.Header == nil && form.Locked == nil && form.Source == nil && form.FieldsAttributes == nil {
l.Debugf("could not parse form from request")
Expand Down
87 changes: 37 additions & 50 deletions internal/api/client/account/accountupdate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,88 +19,75 @@
package account_test

import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"

"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/suite"
"github.com/superseriousbusiness/gotosocial/internal/api/client/account"
"github.com/superseriousbusiness/gotosocial/internal/oauth"
apimodel "github.com/superseriousbusiness/gotosocial/internal/api/model"
"github.com/superseriousbusiness/gotosocial/testrig"
)

type AccountUpdateTestSuite struct {
AccountStandardTestSuite
}

func (suite *AccountUpdateTestSuite) SetupSuite() {
suite.testTokens = testrig.NewTestTokens()
suite.testClients = testrig.NewTestClients()
suite.testApplications = testrig.NewTestApplications()
suite.testUsers = testrig.NewTestUsers()
suite.testAccounts = testrig.NewTestAccounts()
suite.testAttachments = testrig.NewTestAttachments()
suite.testStatuses = testrig.NewTestStatuses()
}

func (suite *AccountUpdateTestSuite) SetupTest() {
suite.config = testrig.NewTestConfig()
suite.db = testrig.NewTestDB()
suite.storage = testrig.NewTestStorage()
suite.log = testrig.NewTestLog()
suite.federator = testrig.NewTestFederator(suite.db, testrig.NewTestTransportController(testrig.NewMockHTTPClient(nil), suite.db), suite.storage)
suite.processor = testrig.NewTestProcessor(suite.db, suite.storage, suite.federator)
suite.accountModule = account.New(suite.config, suite.processor, suite.log).(*account.Module)
testrig.StandardDBSetup(suite.db, nil)
testrig.StandardStorageSetup(suite.storage, "../../../../testrig/media")
}

func (suite *AccountUpdateTestSuite) TearDownTest() {
testrig.StandardDBTeardown(suite.db)
testrig.StandardStorageTeardown(suite.storage)
}

func (suite *AccountUpdateTestSuite) TestAccountUpdateCredentialsPATCHHandler() {

requestBody, w, err := testrig.CreateMultipartFormData("header", "../../../../testrig/media/test-jpeg.jpg", map[string]string{
"display_name": "updated zork display name!!!",
"locked": "true",
})
func (suite *AccountUpdateTestSuite) TestAccountUpdateCredentialsPATCHHandlerSimple() {
// set up the request
// we're updating the header image, the display name, and the locked status of zork
// we're removing the note/bio
requestBody, w, err := testrig.CreateMultipartFormData(
"header", "../../../../testrig/media/test-jpeg.jpg",
map[string]string{
"display_name": "updated zork display name!!!",
"note": "",
"locked": "true",
})
if err != nil {
panic(err)
}

// setup
recorder := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(recorder)
ctx.Set(oauth.SessionAuthorizedAccount, suite.testAccounts["local_account_1"])
ctx.Set(oauth.SessionAuthorizedToken, oauth.DBTokenToToken(suite.testTokens["local_account_1"]))
ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplications["application_1"])
ctx.Set(oauth.SessionAuthorizedUser, suite.testUsers["local_account_1"])
ctx.Request = httptest.NewRequest(http.MethodPatch, fmt.Sprintf("http://localhost:8080/%s", account.UpdateCredentialsPath), bytes.NewReader(requestBody.Bytes())) // the endpoint we're hitting
ctx.Request.Header.Set("Content-Type", w.FormDataContentType())
suite.accountModule.AccountUpdateCredentialsPATCHHandler(ctx)
ctx := suite.newContext(recorder, http.MethodPatch, requestBody.Bytes(), account.UpdateCredentialsPath, w.FormDataContentType())

// check response
// call the handler
suite.accountModule.AccountUpdateCredentialsPATCHHandler(ctx)

// 1. we should have OK because our request was valid
suite.EqualValues(http.StatusOK, recorder.Code)
suite.Equal(http.StatusOK, recorder.Code)

// 2. we should have no error message in the result body
result := recorder.Result()
defer result.Body.Close()

// check the response
b, err := ioutil.ReadAll(result.Body)
assert.NoError(suite.T(), err)

fmt.Println(string(b))

// TODO write more assertions allee
// unmarshal the returned account
apimodelAccount := &apimodel.Account{}
err = json.Unmarshal(b, apimodelAccount)
suite.NoError(err)

// check the returned api model account
// fields should be updated
suite.Equal("updated zork display name!!!", apimodelAccount.DisplayName)
suite.True(apimodelAccount.Locked)
suite.Empty(apimodelAccount.Note)

// header values...
// should be set
suite.NotEmpty(apimodelAccount.Header)
suite.NotEmpty(apimodelAccount.HeaderStatic)

// should be different from the values set before
suite.NotEqual("http://localhost:8080/fileserver/01F8MH1H7YV1Z7D2C8K2730QBF/header/original/01PFPMWK2FF0D9WMHEJHR07C3Q.jpeg", apimodelAccount.Header)
suite.NotEqual("http://localhost:8080/fileserver/01F8MH1H7YV1Z7D2C8K2730QBF/header/small/01PFPMWK2FF0D9WMHEJHR07C3Q.jpeg", apimodelAccount.HeaderStatic)
}

func TestAccountUpdateTestSuite(t *testing.T) {
Expand Down
74 changes: 74 additions & 0 deletions internal/api/client/account/accountverify_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,77 @@
*/

package account_test

import (
"encoding/json"
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
"time"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/suite"
"github.com/superseriousbusiness/gotosocial/internal/api/client/account"
apimodel "github.com/superseriousbusiness/gotosocial/internal/api/model"
"github.com/superseriousbusiness/gotosocial/internal/gtsmodel"
)

type AccountVerifyTestSuite struct {
AccountStandardTestSuite
}

func (suite *AccountVerifyTestSuite) TestAccountVerifyGet() {
testAccount := suite.testAccounts["local_account_1"]

// set up the request
recorder := httptest.NewRecorder()
ctx := suite.newContext(recorder, http.MethodPatch, nil, account.UpdateCredentialsPath, "")

// call the handler
suite.accountModule.AccountVerifyGETHandler(ctx)

// 1. we should have OK because our request was valid
suite.Equal(http.StatusOK, recorder.Code)

// 2. we should have no error message in the result body
result := recorder.Result()
defer result.Body.Close()

// check the response
b, err := ioutil.ReadAll(result.Body)
assert.NoError(suite.T(), err)

// unmarshal the returned account
apimodelAccount := &apimodel.Account{}
err = json.Unmarshal(b, apimodelAccount)
suite.NoError(err)

createdAt, err := time.Parse(time.RFC3339, apimodelAccount.CreatedAt)
suite.NoError(err)
lastStatusAt, err := time.Parse(time.RFC3339, apimodelAccount.LastStatusAt)
suite.NoError(err)

suite.Equal(testAccount.ID, apimodelAccount.ID)
suite.Equal(testAccount.Username, apimodelAccount.Username)
suite.Equal(testAccount.Username, apimodelAccount.Acct)
suite.Equal(testAccount.DisplayName, apimodelAccount.DisplayName)
suite.Equal(testAccount.Locked, apimodelAccount.Locked)
suite.Equal(testAccount.Bot, apimodelAccount.Bot)
suite.WithinDuration(testAccount.CreatedAt, createdAt, 30*time.Second) // we lose a bit of accuracy serializing so fuzz this a bit
suite.Equal(testAccount.URL, apimodelAccount.URL)
suite.Equal("http://localhost:8080/fileserver/01F8MH1H7YV1Z7D2C8K2730QBF/avatar/original/01F8MH58A357CV5K7R7TJMSH6S.jpeg", apimodelAccount.Avatar)
suite.Equal("http://localhost:8080/fileserver/01F8MH1H7YV1Z7D2C8K2730QBF/avatar/small/01F8MH58A357CV5K7R7TJMSH6S.jpeg", apimodelAccount.AvatarStatic)
suite.Equal("http://localhost:8080/fileserver/01F8MH1H7YV1Z7D2C8K2730QBF/header/original/01PFPMWK2FF0D9WMHEJHR07C3Q.jpeg", apimodelAccount.Header)
suite.Equal("http://localhost:8080/fileserver/01F8MH1H7YV1Z7D2C8K2730QBF/header/small/01PFPMWK2FF0D9WMHEJHR07C3Q.jpeg", apimodelAccount.HeaderStatic)
suite.Zero(apimodelAccount.FollowersCount)
suite.Equal(2, apimodelAccount.FollowingCount)
suite.Equal(5, apimodelAccount.StatusesCount)
suite.WithinDuration(time.Now(), lastStatusAt, 5*time.Minute)
suite.EqualValues(gtsmodel.VisibilityPublic, apimodelAccount.Source.Privacy)
suite.Equal(testAccount.Language, apimodelAccount.Source.Language)
}

func TestAccountVerifyTestSuite(t *testing.T) {
suite.Run(t, new(AccountVerifyTestSuite))
}
10 changes: 5 additions & 5 deletions internal/cliactions/admin/account/account.go
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ var Confirm cliactions.GTSAction = func(ctx context.Context, c *config.Config, l
u.Approved = true
u.Email = u.UnconfirmedEmail
u.ConfirmedAt = time.Now()
if err := dbConn.UpdateByID(ctx, u.ID, u); err != nil {
if err := dbConn.UpdateByPrimaryKey(ctx, u); err != nil {
return err
}

Expand Down Expand Up @@ -133,7 +133,7 @@ var Promote cliactions.GTSAction = func(ctx context.Context, c *config.Config, l
return err
}
u.Admin = true
if err := dbConn.UpdateByID(ctx, u.ID, u); err != nil {
if err := dbConn.UpdateByPrimaryKey(ctx, u); err != nil {
return err
}

Expand Down Expand Up @@ -165,7 +165,7 @@ var Demote cliactions.GTSAction = func(ctx context.Context, c *config.Config, lo
return err
}
u.Admin = false
if err := dbConn.UpdateByID(ctx, u.ID, u); err != nil {
if err := dbConn.UpdateByPrimaryKey(ctx, u); err != nil {
return err
}

Expand Down Expand Up @@ -197,7 +197,7 @@ var Disable cliactions.GTSAction = func(ctx context.Context, c *config.Config, l
return err
}
u.Disabled = true
if err := dbConn.UpdateByID(ctx, u.ID, u); err != nil {
if err := dbConn.UpdateByPrimaryKey(ctx, u); err != nil {
return err
}

Expand Down Expand Up @@ -250,7 +250,7 @@ var Password cliactions.GTSAction = func(ctx context.Context, c *config.Config,

u.EncryptedPassword = string(pw)

if err := dbConn.UpdateByID(ctx, u.ID, u); err != nil {
if err := dbConn.UpdateByPrimaryKey(ctx, u); err != nil {
return err
}

Expand Down
9 changes: 5 additions & 4 deletions internal/db/basic.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,12 +62,13 @@ type Basic interface {
// The given interface i will be set to the result of the query, whatever it is. Use a pointer or a slice.
Put(ctx context.Context, i interface{}) Error

// UpdateByID updates i with id id.
// UpdateByPrimaryKey updates all values of i based on its primary key.
// The given interface i will be set to the result of the query, whatever it is. Use a pointer or a slice.
UpdateByID(ctx context.Context, id string, i interface{}) Error
UpdateByPrimaryKey(ctx context.Context, i interface{}) Error

// UpdateOneByID updates interface i with database the given database id. It will update one field of key key and value value.
UpdateOneByID(ctx context.Context, id string, key string, value interface{}, i interface{}) Error
// UpdateOneByPrimaryKey sets one column of interface, with the given key, to the given value.
// It uses the primary key of interface i to decide which row to update. This is usually the `id`.
UpdateOneByPrimaryKey(ctx context.Context, key string, value interface{}, i interface{}) Error

// UpdateWhere updates column key of interface i with the given value, where the given parameters apply.
UpdateWhere(ctx context.Context, where []Where, key string, value interface{}, i interface{}) Error
Expand Down
4 changes: 2 additions & 2 deletions internal/db/bundb/basic.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ func (b *basicDB) DeleteWhere(ctx context.Context, where []db.Where, i interface
return b.conn.ProcessError(err)
}

func (b *basicDB) UpdateByID(ctx context.Context, id string, i interface{}) db.Error {
func (b *basicDB) UpdateByPrimaryKey(ctx context.Context, i interface{}) db.Error {
q := b.conn.
NewUpdate().
Model(i).
Expand All @@ -105,7 +105,7 @@ func (b *basicDB) UpdateByID(ctx context.Context, id string, i interface{}) db.E
return b.conn.ProcessError(err)
}

func (b *basicDB) UpdateOneByID(ctx context.Context, id string, key string, value interface{}, i interface{}) db.Error {
func (b *basicDB) UpdateOneByPrimaryKey(ctx context.Context, key string, value interface{}, i interface{}) db.Error {
q := b.conn.NewUpdate().
Model(i).
Set("? = ?", bun.Safe(key), value).
Expand Down
Loading

0 comments on commit e681aac

Please sign in to comment.