github.com/Axway/agent-sdk@v1.1.101/pkg/jobs/scheduledjob_test.go (about) 1 package jobs 2 3 import ( 4 "context" 5 "sync" 6 "testing" 7 "time" 8 9 "github.com/stretchr/testify/assert" 10 ) 11 12 type scheduledJobImpl struct { 13 Job 14 name string 15 runTime time.Duration 16 ready bool 17 executions int 18 jobMutex *sync.Mutex 19 } 20 21 func (j *scheduledJobImpl) Execute() error { 22 j.jobMutex.Lock() 23 j.executions++ 24 j.jobMutex.Unlock() 25 time.Sleep(j.runTime) 26 return nil 27 } 28 29 func (j *scheduledJobImpl) Status() error { 30 return nil 31 } 32 33 func (j *scheduledJobImpl) Ready() bool { 34 j.jobMutex.Lock() 35 defer j.jobMutex.Unlock() 36 return j.ready 37 } 38 39 func (j *scheduledJobImpl) setReady(ready bool) { 40 j.jobMutex.Lock() 41 defer j.jobMutex.Unlock() 42 j.ready = ready 43 } 44 45 func (j *scheduledJobImpl) getExecutions() int { 46 j.jobMutex.Lock() 47 defer j.jobMutex.Unlock() 48 return j.executions 49 } 50 51 func (j *scheduledJobImpl) clearExecutions() { 52 j.jobMutex.Lock() 53 defer j.jobMutex.Unlock() 54 j.executions = 0 55 } 56 57 func TestScheduledJob(t *testing.T) { 58 job := &scheduledJobImpl{ 59 name: "ScheduledJob", 60 runTime: 5 * time.Millisecond, 61 ready: false, 62 jobMutex: &sync.Mutex{}, 63 } 64 65 // scheduled job with bad schedule 66 _, err := RegisterScheduledJob(job, "@time") 67 assert.NotNil(t, err, "expected an error with a bad schedule") 68 69 // create a scheduled job that runs every second 70 jobID, err := RegisterScheduledJob(job, "* * * * * * *") 71 assert.Nil(t, err) 72 73 statuses := []JobStatus{JobStatusRunning} 74 ctx, cancelFunc := context.WithTimeout(context.Background(), time.Second*10) 75 defer cancelFunc() 76 77 testDone := make(chan interface{}) 78 79 go statusWaiter(ctx, t, statuses, jobID, testDone) 80 81 job.setReady(true) 82 <-testDone 83 assert.Nil(t, ctx.Err()) 84 UnregisterJob(jobID) 85 }