diff --git a/pkg/scheduler/scheduler.go b/pkg/scheduler/scheduler.go index b5c6632..4f66848 100644 --- a/pkg/scheduler/scheduler.go +++ b/pkg/scheduler/scheduler.go @@ -199,22 +199,26 @@ func (scheduler *Scheduler) ScheduleTask(name string, startTime *time.Time, dura } // StopTask encapsulates task stopping sequence. -func (scheduler *Scheduler) StopTask(task *Task) { +func (scheduler *Scheduler) StopTask(task *Task) error { if task.stopSignal != nil { close(task.stopSignal) task.stopSignal = nil } - scheduler.removeTask(task) + return scheduler.removeTask(task) } // removeTask removes Task from the tasks list of the Scheduler. -func (scheduler *Scheduler) removeTask(scheduledTask *Task) { +func (scheduler *Scheduler) removeTask(scheduledTask *Task) error { taskIndex := scheduler.FindTaskIndex(scheduledTask) + if taskIndex == -1 { + return fmt.Errorf("task with id: %s cannot be stopped, because it was not found", scheduledTask.ID) + } if len(scheduler.Tasks) <= 1 { scheduler.Tasks = make([]*Task, 0) } else { scheduler.Tasks = append(scheduler.Tasks[:taskIndex], scheduler.Tasks[taskIndex+1:]...) } + return nil } // callFunction calls a function dynamically using reflection. diff --git a/pkg/scheduler/scheduler_test.go b/pkg/scheduler/scheduler_test.go index a3c10ba..1fbfb3b 100644 --- a/pkg/scheduler/scheduler_test.go +++ b/pkg/scheduler/scheduler_test.go @@ -297,7 +297,7 @@ func TestScheduler_StopTask(t *testing.T) { time.Sleep(duration) - newScheduler.StopTask(newTask) + err := newScheduler.StopTask(newTask) foundTask := false @@ -307,11 +307,29 @@ func TestScheduler_StopTask(t *testing.T) { } } - if foundTask { + if foundTask && err != nil { t.Fatalf("Task \"%s\" with id \"%s\" has not been stopped.", newTask.Name, newTask.ID) } } +// TestScheduler_StopTask_NotExist tests that Scheduler.StopTask method correctly +// handles situation where provided task doesn't exist. +func TestScheduler_StopTask_NotExist(t *testing.T) { + taskName := "Test Task" + intervalSeconds := 5 + interval := time.Duration(intervalSeconds) * time.Second + + newScheduler := CreateEmptyScheduler() + newTask := NewSimpleTask(taskName, interval) + + err := newScheduler.StopTask(newTask) + expected := fmt.Sprintf("task with id: %s cannot be stopped, because it was not found", newTask.ID) + + if err.Error() != expected { + t.Fatalf("Error has not been thrown for missing task with id %s.", newTask.ID) + } +} + // TestTask_GetFromContext tests that Task.GetFromContext method returns correct // value from the Task.context based on the provided key. func TestTask_GetFromContext(t *testing.T) {