add test for getUser & add readme

This commit is contained in:
Cubicroot 2021-06-19 16:59:30 +02:00
parent 46dd19b07d
commit e6f24c4458
6 changed files with 114 additions and 21 deletions

View file

@ -157,3 +157,33 @@ git clone https://github.com/pushbits/server.git
``` ```
[![Stargazers over time](https://starchart.cc/pushbits/server.svg)](https://starchart.cc/pushbits/server) [![Stargazers over time](https://starchart.cc/pushbits/server.svg)](https://starchart.cc/pushbits/server)
### Testing
Testing is essential for deliviering a good and reliable software. PushBits uses golangs integrated test features. Unfortunately writing tests is quite time consuming and therefore not every feature and every line of code is automatically tested. Feel free to help us improve our tests.
Some tests depend on confidential configuration data. Therefore provide a `config.yml` in PushBits main folder.
To run tests for a single (sub)module you can simply execute the following command in the modules folder.
```bash
go test
```
To get the testing coverage for a module use the `-cover` flag.
```bash
go test -cover
```
To execute a single test use the `-run` flag.
```bash
go test -run "TestApi_getUser"
```
Running tests for all PushBits module is done by the `execute_tests.sh` script provided.
```bash
bash execute_tests.sh
```

1
execute_tests.sh Normal file
View file

@ -0,0 +1 @@
find . -name '*.go' -printf '%h\n' | sort -u | xargs -n1 -P1 go test -cover

View file

@ -10,6 +10,7 @@ import (
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/pushbits/server/internal/configuration" "github.com/pushbits/server/internal/configuration"
"github.com/pushbits/server/internal/database"
"github.com/pushbits/server/internal/model" "github.com/pushbits/server/internal/model"
"github.com/pushbits/server/tests" "github.com/pushbits/server/tests"
"github.com/pushbits/server/tests/mockups" "github.com/pushbits/server/tests/mockups"
@ -18,6 +19,7 @@ import (
var TestApplicationHandler *ApplicationHandler var TestApplicationHandler *ApplicationHandler
var TestUsers []*model.User var TestUsers []*model.User
var TestDatabase *database.Database
// Collect all created applications to check & delete them later // Collect all created applications to check & delete them later
var SuccessAplications map[uint][]model.Application var SuccessAplications map[uint][]model.Application
@ -35,7 +37,15 @@ func TestMain(m *testing.M) {
config.Database.Dialect = "sqlite3" config.Database.Dialect = "sqlite3"
// Set up test environment // Set up test environment
appHandler, err := getApplicationHandler(&config.Matrix) db, err := mockups.GetEmptyDatabase(config.Crypto)
if err != nil {
cleanUp()
log.Println("Can not set up database: ", err)
os.Exit(1)
}
TestDatabase = db
appHandler, err := getApplicationHandler(config)
if err != nil { if err != nil {
cleanUp() cleanUp()
log.Println("Can not set up application handler: ", err) log.Println("Can not set up application handler: ", err)
@ -46,6 +56,7 @@ func TestMain(m *testing.M) {
TestUsers = mockups.GetUsers(config) TestUsers = mockups.GetUsers(config)
SuccessAplications = make(map[uint][]model.Application) SuccessAplications = make(map[uint][]model.Application)
// Run
m.Run() m.Run()
cleanUp() cleanUp()
} }
@ -300,18 +311,13 @@ func TestApi_DeleteApplication(t *testing.T) {
} }
// GetApplicationHandler creates and returns an application handler // GetApplicationHandler creates and returns an application handler
func getApplicationHandler(c *configuration.Matrix) (*ApplicationHandler, error) { func getApplicationHandler(c *configuration.Configuration) (*ApplicationHandler, error) {
db, err := mockups.GetEmptyDatabase() dispatcher, err := mockups.GetMatrixDispatcher(c.Matrix.Homeserver, c.Matrix.Username, c.Matrix.Password, c.Crypto)
if err != nil {
return nil, err
}
dispatcher, err := mockups.GetMatrixDispatcher(c.Homeserver, c.Username, c.Password)
if err != nil { if err != nil {
return nil, err return nil, err
} }
return &ApplicationHandler{ return &ApplicationHandler{
DB: db, DB: TestDatabase,
DP: dispatcher, DP: dispatcher,
}, nil }, nil
} }
@ -321,9 +327,9 @@ func validateAllApplications(user *model.User, apps []model.Application) bool {
if _, ok := SuccessAplications[user.ID]; !ok { if _, ok := SuccessAplications[user.ID]; !ok {
if len(apps) == 0 { if len(apps) == 0 {
return true return true
} else {
return false
} }
return false
} }
for _, successApp := range SuccessAplications[user.ID] { for _, successApp := range SuccessAplications[user.ID] {

View file

@ -53,13 +53,10 @@ func TestApi_getApplication(t *testing.T) {
assert := assert.New(t) assert := assert.New(t)
gin.SetMode(gin.TestMode) gin.SetMode(gin.TestMode)
// Generate a mock database
db, err := mockups.GetEmptyDatabase()
assert.NoErrorf(err, "Could not get database: ", err)
applications := mockups.GetAllApplications() applications := mockups.GetAllApplications()
mockups.AddApplicationsToDb(db, applications) mockups.AddApplicationsToDb(TestDatabase, applications)
// No testing of invalid ids as that is tested in TestApi_getID already
testCases := make(map[uint]tests.Request) testCases := make(map[uint]tests.Request)
testCases[500] = tests.Request{Name: "-", Method: "GET", Endpoint: "/", Data: "", ShouldStatus: 404} testCases[500] = tests.Request{Name: "-", Method: "GET", Endpoint: "/", Data: "", ShouldStatus: 404}
testCases[1] = tests.Request{Name: "-", Method: "GET", Endpoint: "/", Data: "", ShouldStatus: 200} testCases[1] = tests.Request{Name: "-", Method: "GET", Endpoint: "/", Data: "", ShouldStatus: 200}
@ -72,7 +69,7 @@ func TestApi_getApplication(t *testing.T) {
} }
c.Set("id", id) c.Set("id", id)
app, err := getApplication(c, db) app, err := getApplication(c, TestDatabase)
if req.ShouldStatus >= 200 && req.ShouldStatus < 300 { if req.ShouldStatus >= 200 && req.ShouldStatus < 300 {
assert.Equalf(app.ID, id, "getApplication id was set to %d but resulting app id is %d", id, app.ID) assert.Equalf(app.ID, id, "getApplication id was set to %d but resulting app id is %d", id, app.ID)
@ -85,3 +82,36 @@ func TestApi_getApplication(t *testing.T) {
} }
} }
func TestApi_getUser(t *testing.T) {
assert := assert.New(t)
gin.SetMode(gin.TestMode)
_, err := mockups.AddUsersToDb(TestDatabase, TestUsers)
assert.NoErrorf(err, "Adding users to database failed: %v", err)
// No testing of invalid ids as that is tested in TestApi_getID already
testCases := make(map[uint]tests.Request)
testCases[500] = tests.Request{Name: "-", Method: "GET", Endpoint: "/", Data: "", ShouldStatus: 404}
testCases[1] = tests.Request{Name: "-", Method: "GET", Endpoint: "/", Data: "", ShouldStatus: 200}
testCases[2] = tests.Request{Name: "-", Method: "GET", Endpoint: "/", Data: "", ShouldStatus: 200}
for id, req := range testCases {
w, c, err := req.GetRequest()
if err != nil {
t.Fatalf(err.Error())
}
c.Set("id", id)
user, err := getUser(c, TestDatabase)
if req.ShouldStatus >= 200 && req.ShouldStatus < 300 {
assert.Equalf(user.ID, id, "getUser id was set to %d but resulting app id is %d", id, user.ID)
assert.NoErrorf(err, "getUser with id %v (%t) returned an error altough it should not: %v", id, id, err)
} else {
assert.Errorf(err, "getUser with id %v (%t) returned no error altough it should", id, id)
}
assert.Equalf(w.Code, req.ShouldStatus, "getUser id was set to %v (%T) and should result in status code %d but code is %d", id, id, req.ShouldStatus, w.Code)
}
}

View file

@ -8,8 +8,8 @@ import (
) )
// GetEmptyDatabase returns an empty sqlite database object // GetEmptyDatabase returns an empty sqlite database object
func GetEmptyDatabase() (*database.Database, error) { func GetEmptyDatabase(confCrypto configuration.CryptoConfig) (*database.Database, error) {
cm := credentials.CreateManager(false, configuration.CryptoConfig{}) cm := credentials.CreateManager(false, confCrypto)
return database.Create(cm, "sqlite3", "pushbits-test.db") return database.Create(cm, "sqlite3", "pushbits-test.db")
} }
@ -24,3 +24,29 @@ func AddApplicationsToDb(db *database.Database, apps []*model.Application) error
return nil return nil
} }
// AddUsersToDb adds the users to the database and sets their username as a password, returns list of added users
func AddUsersToDb(db *database.Database, users []*model.User) ([]*model.User, error) {
addedUsers := make([]*model.User, 0)
for _, user := range users {
extUser := model.ExternalUser{
ID: user.ID,
Name: user.Name,
IsAdmin: user.IsAdmin,
MatrixID: user.MatrixID,
}
credentials := model.UserCredentials{
Password: user.Name,
}
createUser := model.CreateUser{ExternalUser: extUser, UserCredentials: credentials}
newUser, err := db.CreateUser(createUser)
addedUsers = append(addedUsers, newUser)
if err != nil {
return nil, err
}
}
return addedUsers, nil
}

View file

@ -6,8 +6,8 @@ import (
) )
// GetMatrixDispatcher creates and returns a matrix dispatcher // GetMatrixDispatcher creates and returns a matrix dispatcher
func GetMatrixDispatcher(homeserver, username, password string) (*dispatcher.Dispatcher, error) { func GetMatrixDispatcher(homeserver, username, password string, confCrypto configuration.CryptoConfig) (*dispatcher.Dispatcher, error) {
db, err := GetEmptyDatabase() db, err := GetEmptyDatabase(confCrypto)
if err != nil { if err != nil {
return nil, err return nil, err