mirror of
https://github.com/superseriousbusiness/gotosocial.git
synced 2025-11-03 09:52:24 -06:00
proper mocking tests
This commit is contained in:
parent
cd0a1829d4
commit
f9932adcac
1 changed files with 153 additions and 139 deletions
|
|
@ -20,6 +20,9 @@ package account
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"io/ioutil"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/http/httptest"
|
"net/http/httptest"
|
||||||
"net/url"
|
"net/url"
|
||||||
|
|
@ -27,62 +30,49 @@ import (
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"github.com/sirupsen/logrus"
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
"github.com/stretchr/testify/mock"
|
||||||
|
"github.com/stretchr/testify/suite"
|
||||||
"github.com/superseriousbusiness/gotosocial/internal/config"
|
"github.com/superseriousbusiness/gotosocial/internal/config"
|
||||||
"github.com/superseriousbusiness/gotosocial/internal/db"
|
"github.com/superseriousbusiness/gotosocial/internal/db"
|
||||||
"github.com/superseriousbusiness/gotosocial/internal/db/model"
|
"github.com/superseriousbusiness/gotosocial/internal/db/model"
|
||||||
"github.com/superseriousbusiness/gotosocial/internal/oauth"
|
"github.com/superseriousbusiness/gotosocial/internal/oauth"
|
||||||
|
"github.com/superseriousbusiness/gotosocial/pkg/mastotypes"
|
||||||
"github.com/superseriousbusiness/oauth2/v4"
|
"github.com/superseriousbusiness/oauth2/v4"
|
||||||
|
"github.com/superseriousbusiness/oauth2/v4/models"
|
||||||
oauthmodels "github.com/superseriousbusiness/oauth2/v4/models"
|
oauthmodels "github.com/superseriousbusiness/oauth2/v4/models"
|
||||||
"github.com/sirupsen/logrus"
|
"golang.org/x/crypto/bcrypt"
|
||||||
"github.com/stretchr/testify/suite"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type AccountTestSuite struct {
|
type AccountTestSuite struct {
|
||||||
suite.Suite
|
suite.Suite
|
||||||
log *logrus.Logger
|
config *config.Config
|
||||||
testAccountLocal *model.Account
|
log *logrus.Logger
|
||||||
testAccountRemote *model.Account
|
testAccountLocal *model.Account
|
||||||
testUser *model.User
|
testAccountRemote *model.Account
|
||||||
testApplication *model.Application
|
testUser *model.User
|
||||||
testToken oauth2.TokenInfo
|
testApplication *model.Application
|
||||||
db db.DB
|
testToken oauth2.TokenInfo
|
||||||
accountModule *accountModule
|
mockOauthServer *oauth.MockServer
|
||||||
|
db db.DB
|
||||||
|
accountModule *accountModule
|
||||||
|
newUserFormHappyPath url.Values
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
TEST INFRASTRUCTURE
|
||||||
|
*/
|
||||||
|
|
||||||
// SetupSuite sets some variables on the suite that we can use as consts (more or less) throughout
|
// SetupSuite sets some variables on the suite that we can use as consts (more or less) throughout
|
||||||
func (suite *AccountTestSuite) SetupSuite() {
|
func (suite *AccountTestSuite) SetupSuite() {
|
||||||
|
// some of our subsequent entities need a log so create this here
|
||||||
log := logrus.New()
|
log := logrus.New()
|
||||||
log.SetLevel(logrus.TraceLevel)
|
log.SetLevel(logrus.TraceLevel)
|
||||||
suite.log = log
|
suite.log = log
|
||||||
|
|
||||||
c := config.Empty()
|
// can use this test application throughout
|
||||||
c.DBConfig = &config.DBConfig{
|
|
||||||
Type: "postgres",
|
|
||||||
Address: "localhost",
|
|
||||||
Port: 5432,
|
|
||||||
User: "postgres",
|
|
||||||
Password: "postgres",
|
|
||||||
Database: "postgres",
|
|
||||||
ApplicationName: "gotosocial",
|
|
||||||
}
|
|
||||||
c.AccountsConfig = &config.AccountsConfig{
|
|
||||||
OpenRegistration: true,
|
|
||||||
RequireApproval: true,
|
|
||||||
ReasonRequired: true,
|
|
||||||
}
|
|
||||||
|
|
||||||
database, err := db.New(context.Background(), c, log)
|
|
||||||
if err != nil {
|
|
||||||
suite.FailNow(err.Error())
|
|
||||||
}
|
|
||||||
suite.db = database
|
|
||||||
|
|
||||||
suite.accountModule = &accountModule{
|
|
||||||
config: c,
|
|
||||||
db: database,
|
|
||||||
log: log,
|
|
||||||
}
|
|
||||||
|
|
||||||
suite.testApplication = &model.Application{
|
suite.testApplication = &model.Application{
|
||||||
ID: "weeweeeeeeeeeeeeee",
|
ID: "weeweeeeeeeeeeeeee",
|
||||||
Name: "a test application",
|
Name: "a test application",
|
||||||
|
|
@ -94,6 +84,7 @@ func (suite *AccountTestSuite) SetupSuite() {
|
||||||
VapidKey: "aaaaaa-aaaaaaaa-aaaaaaaaaaa",
|
VapidKey: "aaaaaa-aaaaaaaa-aaaaaaaaaaa",
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// can use this test token throughout
|
||||||
suite.testToken = &oauthmodels.Token{
|
suite.testToken = &oauthmodels.Token{
|
||||||
ClientID: "a-known-client-id",
|
ClientID: "a-known-client-id",
|
||||||
RedirectURI: "http://localhost:8080",
|
RedirectURI: "http://localhost:8080",
|
||||||
|
|
@ -103,97 +94,48 @@ func (suite *AccountTestSuite) SetupSuite() {
|
||||||
CodeExpiresIn: time.Duration(10 * time.Minute),
|
CodeExpiresIn: time.Duration(10 * time.Minute),
|
||||||
}
|
}
|
||||||
|
|
||||||
// encryptedPassword, err := bcrypt.GenerateFromPassword([]byte("password"), bcrypt.DefaultCost)
|
// Direct config to local postgres instance
|
||||||
// if err != nil {
|
c := config.Empty()
|
||||||
// logrus.Panicf("error encrypting user pass: %s", err)
|
c.DBConfig = &config.DBConfig{
|
||||||
// }
|
Type: "postgres",
|
||||||
|
Address: "localhost",
|
||||||
|
Port: 5432,
|
||||||
|
User: "postgres",
|
||||||
|
Password: "postgres",
|
||||||
|
Database: "postgres",
|
||||||
|
ApplicationName: "gotosocial",
|
||||||
|
}
|
||||||
|
// Default accountsconfig
|
||||||
|
c.AccountsConfig = &config.AccountsConfig{
|
||||||
|
OpenRegistration: true,
|
||||||
|
RequireApproval: true,
|
||||||
|
ReasonRequired: true,
|
||||||
|
}
|
||||||
|
suite.config = c
|
||||||
|
|
||||||
// localAvatar, err := url.Parse("https://localhost:8080/media/aaaaaaaaa.png")
|
// use an actual database for this, because it's just easier than mocking one out
|
||||||
// if err != nil {
|
database, err := db.New(context.Background(), c, log)
|
||||||
// logrus.Panicf("error parsing localavatar url: %s", err)
|
if err != nil {
|
||||||
// }
|
suite.FailNow(err.Error())
|
||||||
// localHeader, err := url.Parse("https://localhost:8080/media/ffffffffff.png")
|
}
|
||||||
// if err != nil {
|
suite.db = database
|
||||||
// logrus.Panicf("error parsing localheader url: %s", err)
|
|
||||||
// }
|
|
||||||
|
|
||||||
// acctID := uuid.NewString()
|
// we need to mock the oauth server because account creation needs it to create a new token
|
||||||
// suite.testAccountLocal = &model.Account{
|
suite.mockOauthServer = &oauth.MockServer{}
|
||||||
// ID: acctID,
|
suite.mockOauthServer.On("GenerateUserAccessToken", suite.testToken, suite.testApplication.ClientSecret, mock.AnythingOfType("string")).Run(func(args mock.Arguments) {
|
||||||
// Username: "local_account_of_some_kind",
|
l := suite.log.WithField("func", "GenerateUserAccessToken")
|
||||||
// AvatarRemoteURL: localAvatar,
|
token := args.Get(0).(oauth2.TokenInfo)
|
||||||
// HeaderRemoteURL: localHeader,
|
l.Infof("received token %+v", token)
|
||||||
// DisplayName: "michael caine",
|
clientSecret := args.Get(1).(string)
|
||||||
// Fields: []model.Field{
|
l.Infof("received clientSecret %+v", clientSecret)
|
||||||
// {
|
userID := args.Get(2).(string)
|
||||||
// Name: "come and ave a go",
|
l.Infof("received userID %+v", userID)
|
||||||
// Value: "if you think you're hard enough",
|
}).Return(&models.Token{
|
||||||
// },
|
Code: "we're authorized now!",
|
||||||
// {
|
}, nil)
|
||||||
// Name: "website",
|
|
||||||
// Value: "https://imdb.com",
|
|
||||||
// VerifiedAt: time.Now(),
|
|
||||||
// },
|
|
||||||
// },
|
|
||||||
// Note: "My name is Michael Caine and i'm a local user.",
|
|
||||||
// Discoverable: true,
|
|
||||||
// }
|
|
||||||
|
|
||||||
// avatarURL, err := url.Parse("http://example.org/accounts/avatars/000/207/122/original/089-1098-09.png")
|
// and finally here's the thing we're actually testing!
|
||||||
// if err != nil {
|
suite.accountModule = New(suite.config, suite.db, suite.mockOauthServer, suite.log).(*accountModule)
|
||||||
// logrus.Panicf("error parsing avatarURL: %s", err)
|
|
||||||
// }
|
|
||||||
|
|
||||||
// headerURL, err := url.Parse("http://example.org/accounts/headers/000/207/122/original/111111111111.png")
|
|
||||||
// if err != nil {
|
|
||||||
// logrus.Panicf("error parsing avatarURL: %s", err)
|
|
||||||
// }
|
|
||||||
// suite.testAccountRemote = &model.Account{
|
|
||||||
// ID: uuid.NewString(),
|
|
||||||
// Username: "neato_bombeato",
|
|
||||||
// Domain: "example.org",
|
|
||||||
|
|
||||||
// AvatarFileName: "avatar.png",
|
|
||||||
// AvatarContentType: "image/png",
|
|
||||||
// AvatarFileSize: 1024,
|
|
||||||
// AvatarUpdatedAt: time.Now(),
|
|
||||||
// AvatarRemoteURL: avatarURL,
|
|
||||||
|
|
||||||
// HeaderFileName: "avatar.png",
|
|
||||||
// HeaderContentType: "image/png",
|
|
||||||
// HeaderFileSize: 1024,
|
|
||||||
// HeaderUpdatedAt: time.Now(),
|
|
||||||
// HeaderRemoteURL: headerURL,
|
|
||||||
|
|
||||||
// DisplayName: "one cool dude 420",
|
|
||||||
// Fields: []model.Field{
|
|
||||||
// {
|
|
||||||
// Name: "pronouns",
|
|
||||||
// Value: "he/they",
|
|
||||||
// },
|
|
||||||
// {
|
|
||||||
// Name: "website",
|
|
||||||
// Value: "https://imcool.edu",
|
|
||||||
// VerifiedAt: time.Now(),
|
|
||||||
// },
|
|
||||||
// },
|
|
||||||
// Note: "<p>I'm cool as heck!</p>",
|
|
||||||
// Discoverable: true,
|
|
||||||
// URI: "https://example.org/users/neato_bombeato",
|
|
||||||
// URL: "https://example.org/@neato_bombeato",
|
|
||||||
// LastWebfingeredAt: time.Now(),
|
|
||||||
// InboxURL: "https://example.org/users/neato_bombeato/inbox",
|
|
||||||
// OutboxURL: "https://example.org/users/neato_bombeato/outbox",
|
|
||||||
// SharedInboxURL: "https://example.org/inbox",
|
|
||||||
// FollowersURL: "https://example.org/users/neato_bombeato/followers",
|
|
||||||
// FeaturedCollectionURL: "https://example.org/users/neato_bombeato/collections/featured",
|
|
||||||
// }
|
|
||||||
// suite.testUser = &model.User{
|
|
||||||
// ID: uuid.NewString(),
|
|
||||||
// EncryptedPassword: string(encryptedPassword),
|
|
||||||
// Email: "user@example.org",
|
|
||||||
// AccountID: acctID,
|
|
||||||
// }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (suite *AccountTestSuite) TearDownSuite() {
|
func (suite *AccountTestSuite) TearDownSuite() {
|
||||||
|
|
@ -218,6 +160,16 @@ func (suite *AccountTestSuite) SetupTest() {
|
||||||
logrus.Panicf("db connection error: %s", err)
|
logrus.Panicf("db connection error: %s", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// form to submit for happy path account create requests -- this will be changed inside tests so it's better to set it before each test
|
||||||
|
suite.newUserFormHappyPath = url.Values{
|
||||||
|
"reason": []string{"a very good reason that's at least 40 characters i swear"},
|
||||||
|
"username": []string{"test_user"},
|
||||||
|
"email": []string{"user@example.org"},
|
||||||
|
"password": []string{"very-strong-password"},
|
||||||
|
"agreement": []string{"true"},
|
||||||
|
"locale": []string{"en"},
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TearDownTest drops tables to make sure there's no data in the db
|
// TearDownTest drops tables to make sure there's no data in the db
|
||||||
|
|
@ -237,24 +189,86 @@ func (suite *AccountTestSuite) TearDownTest() {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (suite *AccountTestSuite) TestAccountCreatePOSTHandler() {
|
/*
|
||||||
// TODO: figure out how to test this properly
|
ACTUAL TESTS
|
||||||
|
*/
|
||||||
|
|
||||||
|
// TestAccountCreatePOSTHandlerSuccessful checks the happy path for an account creation request: all the fields provided are valid,
|
||||||
|
// and at the end of it a new user and account should be added into the database.
|
||||||
|
//
|
||||||
|
// This is the handler served at /api/v1/accounts as POST
|
||||||
|
func (suite *AccountTestSuite) TestAccountCreatePOSTHandlerSuccessful() {
|
||||||
|
|
||||||
|
// setup
|
||||||
recorder := httptest.NewRecorder()
|
recorder := httptest.NewRecorder()
|
||||||
recorder.Header().Set("X-Forwarded-For", "127.0.0.1")
|
|
||||||
recorder.Header().Set("Content-Type", "application/json")
|
|
||||||
ctx, _ := gin.CreateTestContext(recorder)
|
ctx, _ := gin.CreateTestContext(recorder)
|
||||||
ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplication)
|
ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplication)
|
||||||
ctx.Set(oauth.SessionAuthorizedToken, suite.testToken)
|
ctx.Set(oauth.SessionAuthorizedToken, suite.testToken)
|
||||||
ctx.Request = httptest.NewRequest(http.MethodPost, "http://localhost:8080/api/v1/accounts", nil)
|
ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080/%s", basePath), nil) // the endpoint we're hitting
|
||||||
ctx.Request.Form = url.Values{
|
ctx.Request.Form = suite.newUserFormHappyPath
|
||||||
"reason": []string{"a very good reason that's at least 40 characters i swear"},
|
|
||||||
"username": []string{"test_user"},
|
|
||||||
"email": []string{"user@example.org"},
|
|
||||||
"password": []string{"very-strong-password"},
|
|
||||||
"agreement": []string{"true"},
|
|
||||||
"locale": []string{"en"},
|
|
||||||
}
|
|
||||||
suite.accountModule.accountCreatePOSTHandler(ctx)
|
suite.accountModule.accountCreatePOSTHandler(ctx)
|
||||||
|
|
||||||
|
// check response
|
||||||
|
|
||||||
|
// 1. we should have OK from our call to the function
|
||||||
|
suite.EqualValues(http.StatusOK, recorder.Code)
|
||||||
|
|
||||||
|
// 2. we should have a token in the result body
|
||||||
|
result := recorder.Result()
|
||||||
|
defer result.Body.Close()
|
||||||
|
b, err := ioutil.ReadAll(result.Body)
|
||||||
|
assert.NoError(suite.T(), err)
|
||||||
|
t := &mastotypes.Token{}
|
||||||
|
err = json.Unmarshal(b, t)
|
||||||
|
assert.NoError(suite.T(), err)
|
||||||
|
assert.Equal(suite.T(), "we're authorized now!", t.AccessToken)
|
||||||
|
|
||||||
|
// check new account
|
||||||
|
|
||||||
|
// 1. we should be able to get the new account from the db
|
||||||
|
acct := &model.Account{}
|
||||||
|
err = suite.db.GetWhere("username", "test_user", acct)
|
||||||
|
assert.NoError(suite.T(), err)
|
||||||
|
assert.NotNil(suite.T(), acct)
|
||||||
|
// 2. reason should be set
|
||||||
|
assert.Equal(suite.T(), suite.newUserFormHappyPath.Get("reason"), acct.Reason)
|
||||||
|
// 3. display name should be equal to username by default
|
||||||
|
assert.Equal(suite.T(), suite.newUserFormHappyPath.Get("username"), acct.DisplayName)
|
||||||
|
// 4. domain should be nil because this is a local account
|
||||||
|
assert.Nil(suite.T(), nil, acct.Domain)
|
||||||
|
// 5. id should be set and parseable as a uuid
|
||||||
|
assert.NotNil(suite.T(), acct.ID)
|
||||||
|
_, err = uuid.Parse(acct.ID)
|
||||||
|
assert.Nil(suite.T(), err)
|
||||||
|
// 6. private and public key should be set
|
||||||
|
assert.NotNil(suite.T(), acct.PrivateKey)
|
||||||
|
assert.NotNil(suite.T(), acct.PublicKey)
|
||||||
|
|
||||||
|
// check new user
|
||||||
|
|
||||||
|
// 1. we should be able to get the new user from the db
|
||||||
|
usr := &model.User{}
|
||||||
|
err = suite.db.GetWhere("unconfirmed_email", suite.newUserFormHappyPath.Get("email"), usr)
|
||||||
|
assert.Nil(suite.T(), err)
|
||||||
|
assert.NotNil(suite.T(), usr)
|
||||||
|
|
||||||
|
// 2. user should have account id set to account we got above
|
||||||
|
assert.Equal(suite.T(), acct.ID, usr.AccountID)
|
||||||
|
|
||||||
|
// 3. id should be set and parseable as a uuid
|
||||||
|
assert.NotNil(suite.T(), usr.ID)
|
||||||
|
_, err = uuid.Parse(usr.ID)
|
||||||
|
assert.Nil(suite.T(), err)
|
||||||
|
|
||||||
|
// 4. locale should be equal to what we requested
|
||||||
|
assert.Equal(suite.T(), suite.newUserFormHappyPath.Get("locale"), usr.Locale)
|
||||||
|
|
||||||
|
// 5. created by application id should be equal to the app id
|
||||||
|
assert.Equal(suite.T(), suite.testApplication.ID, usr.CreatedByApplicationID)
|
||||||
|
|
||||||
|
// 6. password should be matcheable to what we set above
|
||||||
|
err = bcrypt.CompareHashAndPassword([]byte(usr.EncryptedPassword), []byte(suite.newUserFormHappyPath.Get("password")))
|
||||||
|
assert.Nil(suite.T(), err)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestAccountTestSuite(t *testing.T) {
|
func TestAccountTestSuite(t *testing.T) {
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue