Cloudreve/models/user_test.go

90 lines
2 KiB
Go
Raw Normal View History

2019-11-07 02:56:05 -05:00
package model
import (
2019-11-11 06:13:17 -05:00
"encoding/json"
2019-11-07 02:56:05 -05:00
"github.com/DATA-DOG/go-sqlmock"
"github.com/jinzhu/gorm"
"github.com/pkg/errors"
"github.com/stretchr/testify/assert"
"testing"
)
2019-11-11 06:13:17 -05:00
func TestGetUserByID(t *testing.T) {
2019-11-07 02:56:05 -05:00
asserts := assert.New(t)
//找到用户时
2019-11-12 03:18:58 -05:00
rows := sqlmock.NewRows([]string{"id", "deleted_at", "email", "options"}).
AddRow(1, nil, "admin@cloudreve.org", "{}")
2019-11-07 02:56:05 -05:00
mock.ExpectQuery("^SELECT (.+)").WillReturnRows(rows)
2019-11-11 06:13:17 -05:00
user, err := GetUserByID(1)
2019-11-07 02:56:05 -05:00
asserts.NoError(err)
asserts.Equal(User{
Model: gorm.Model{
ID: 1,
DeletedAt: nil,
},
2019-11-12 03:23:24 -05:00
Email: "admin@cloudreve.org",
Options: "{}",
2019-11-07 02:56:05 -05:00
}, user)
//未找到用户时
mock.ExpectQuery("^SELECT (.+)").WillReturnError(errors.New("not found"))
2019-11-11 06:13:17 -05:00
user, err = GetUserByID(1)
2019-11-07 02:56:05 -05:00
asserts.Error(err)
asserts.Equal(User{}, user)
}
func TestUser_SetPassword(t *testing.T) {
asserts := assert.New(t)
user := User{}
err := user.SetPassword("Cause Sega does what nintendon't")
asserts.NoError(err)
asserts.NotEmpty(user.Password)
}
func TestUser_CheckPassword(t *testing.T) {
asserts := assert.New(t)
user := User{}
err := user.SetPassword("Cause Sega does what nintendon't")
asserts.NoError(err)
//密码正确
res, err := user.CheckPassword("Cause Sega does what nintendon't")
asserts.NoError(err)
asserts.True(res)
//密码错误
res, err = user.CheckPassword("Cause Sega does what Nintendon't")
asserts.NoError(err)
asserts.False(res)
//密码字段为空
user = User{}
res, err = user.CheckPassword("Cause Sega does what nintendon't")
asserts.Error(err)
asserts.False(res)
}
func TestNewUser(t *testing.T) {
asserts := assert.New(t)
newUser := NewUser()
asserts.IsType(User{}, newUser)
asserts.NotEmpty(newUser.Avatar)
asserts.NotEmpty(newUser.Options)
}
2019-11-11 06:13:17 -05:00
func TestUser_AfterFind(t *testing.T) {
asserts := assert.New(t)
newUser := NewUser()
err := newUser.AfterFind()
2019-11-12 03:18:58 -05:00
expected := UserOption{}
2019-11-11 06:13:17 -05:00
err = json.Unmarshal([]byte(newUser.Options), &expected)
asserts.NoError(err)
asserts.Equal(expected, newUser.OptionsSerialized)
}