Cloudreve/pkg/task/job_test.go

107 lines
2.6 KiB
Go
Raw Normal View History

2020-02-06 16:01:06 +08:00
package task
import (
"errors"
2021-11-20 17:14:45 +08:00
testMock "github.com/stretchr/testify/mock"
"testing"
2020-02-06 16:01:06 +08:00
"github.com/DATA-DOG/go-sqlmock"
model "github.com/cloudreve/Cloudreve/v3/models"
2020-02-06 16:01:06 +08:00
"github.com/stretchr/testify/assert"
)
func TestRecord(t *testing.T) {
asserts := assert.New(t)
job := &TransferTask{
User: &model.User{Policy: model.Policy{Type: "unknown"}},
}
mock.ExpectBegin()
mock.ExpectExec("INSERT(.+)").WillReturnResult(sqlmock.NewResult(1, 1))
mock.ExpectCommit()
_, err := Record(job)
asserts.NoError(err)
}
2021-11-20 17:14:45 +08:00
type taskPoolMock struct {
testMock.Mock
}
func (t taskPoolMock) Add(num int) {
t.Called(num)
}
func (t taskPoolMock) Submit(job Job) {
t.Called(job)
}
2020-02-06 16:01:06 +08:00
func TestResume(t *testing.T) {
asserts := assert.New(t)
2021-11-20 17:14:45 +08:00
mockPool := taskPoolMock{}
2020-02-06 16:01:06 +08:00
// 没有任务
{
2021-11-20 17:14:45 +08:00
mock.ExpectQuery("SELECT(.+)").WithArgs(Queued, Processing).WillReturnRows(sqlmock.NewRows([]string{"type"}))
Resume(mockPool)
asserts.NoError(mock.ExpectationsWereMet())
}
// 有任务, 类型未知
{
mock.ExpectQuery("SELECT(.+)").WithArgs(Queued, Processing).WillReturnRows(sqlmock.NewRows([]string{"type"}).AddRow(233))
Resume(mockPool)
asserts.NoError(mock.ExpectationsWereMet())
}
// 有任务
{
mockPool.On("Submit", testMock.Anything)
mock.ExpectQuery("SELECT(.+)").WithArgs(Queued, Processing).WillReturnRows(sqlmock.NewRows([]string{"type", "props"}).AddRow(CompressTaskType, "{}"))
mock.ExpectQuery("SELECT(.+)users").WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(1))
mock.ExpectQuery("SELECT(.+)policies").WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(1))
Resume(mockPool)
2020-02-06 16:01:06 +08:00
asserts.NoError(mock.ExpectationsWereMet())
2021-11-20 17:14:45 +08:00
mockPool.AssertExpectations(t)
2020-02-06 16:01:06 +08:00
}
}
func TestGetJobFromModel(t *testing.T) {
asserts := assert.New(t)
// CompressTaskType
{
task := &model.Task{
Status: 0,
Type: CompressTaskType,
}
mock.ExpectQuery("SELECT(.+)users(.+)").WillReturnError(errors.New("error"))
job, err := GetJobFromModel(task)
asserts.NoError(mock.ExpectationsWereMet())
asserts.Nil(job)
asserts.Error(err)
}
// DecompressTaskType
{
task := &model.Task{
Status: 0,
Type: DecompressTaskType,
}
mock.ExpectQuery("SELECT(.+)users(.+)").WillReturnError(errors.New("error"))
job, err := GetJobFromModel(task)
asserts.NoError(mock.ExpectationsWereMet())
asserts.Nil(job)
asserts.Error(err)
}
// TransferTaskType
{
task := &model.Task{
Status: 0,
Type: TransferTaskType,
}
mock.ExpectQuery("SELECT(.+)users(.+)").WillReturnError(errors.New("error"))
job, err := GetJobFromModel(task)
asserts.NoError(mock.ExpectationsWereMet())
asserts.Nil(job)
asserts.Error(err)
}
}