Skip to content

Commit

Permalink
#142 validation of params is added (#144)
Browse files Browse the repository at this point in the history
* #142 validation of params is added

* #142 test refactoring

* wrap or return the error

Co-authored-by: John Roesler <[email protected]>
  • Loading branch information
mikhailbolshakov and JohnRoesler authored Mar 25, 2021
1 parent a55ceb8 commit d70cabe
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 0 deletions.
1 change: 1 addition & 0 deletions gocron.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ var (
ErrAtTimeNotSupported = errors.New("the At() method is not supported for this time unit")
ErrWeekdayNotSupported = errors.New("weekday is not supported for time unit")
ErrTagsUnique = func(tag string) error { return fmt.Errorf("a non-unique tag was set on the job: %s", tag) }
ErrWrongParams = errors.New("wrong list of params")
)

func wrapOrError(toWrap error, err error) error {
Expand Down
7 changes: 7 additions & 0 deletions scheduler.go
Original file line number Diff line number Diff line change
Expand Up @@ -529,6 +529,13 @@ func (s *Scheduler) Do(jobFun interface{}, params ...interface{}) (*Job, error)
return nil, ErrNotAFunction
}

f := reflect.ValueOf(jobFun)
if len(params) != f.Type().NumIn() {
s.RemoveByReference(job)
job.error = wrapOrError(job.error, ErrWrongParams)
return nil, job.error
}

fname := getFunctionName(jobFun)
job.functions[fname] = jobFun
job.params[fname] = params
Expand Down
22 changes: 22 additions & 0 deletions scheduler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1058,3 +1058,25 @@ func TestScheduler_TagsUnique(t *testing.T) {
assert.EqualError(t, err, ErrTagsUnique(bar).Error())

}

func TestScheduler_DoParameterValidation(t *testing.T) {
testCases := []struct {
description string
parameters []interface{}
}{
{"less than expected", []interface{}{"p1"}},
{"more than expected", []interface{}{"p1", "p2", "p3"}},
}

for _, tc := range testCases {
t.Run(tc.description, func(t *testing.T) {
s := NewScheduler(time.UTC)
f := func(s1, s2 string) {
fmt.Println("ok")
}

_, err := s.Every(1).Days().StartAt(time.Now().UTC().Add(time.Second*10)).Do(f, tc.parameters...)
assert.EqualError(t, err, ErrWrongParams.Error())
})
}
}

0 comments on commit d70cabe

Please sign in to comment.