github.com/Axway/agent-sdk@v1.1.101/pkg/jobs/channeljob_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 channelJobImpl struct { 13 Job 14 name string 15 runTime time.Duration 16 ready bool 17 executions int 18 status error 19 stopChan chan interface{} 20 jobMutex *sync.Mutex 21 readyMutex *sync.Mutex 22 } 23 24 func (j *channelJobImpl) Execute() error { 25 j.incrementExecutions() 26 for { 27 select { 28 case <-j.stopChan: 29 return nil 30 default: 31 time.Sleep(j.runTime) 32 } 33 } 34 } 35 36 func (j *channelJobImpl) Status() error { 37 return j.status 38 } 39 40 func (j *channelJobImpl) Ready() bool { 41 j.readyMutex.Lock() 42 defer j.readyMutex.Unlock() 43 return j.ready 44 } 45 46 func (j *channelJobImpl) setReady(ready bool) { 47 j.readyMutex.Lock() 48 defer j.readyMutex.Unlock() 49 j.ready = ready 50 } 51 52 func (j *channelJobImpl) getExecutions() int { 53 j.jobMutex.Lock() 54 defer j.jobMutex.Unlock() 55 return j.executions 56 } 57 58 func (j *channelJobImpl) incrementExecutions() { 59 j.jobMutex.Lock() 60 defer j.jobMutex.Unlock() 61 j.executions++ 62 } 63 64 func (j *channelJobImpl) clearExecutions() { 65 j.jobMutex.Lock() 66 defer j.jobMutex.Unlock() 67 j.executions = 0 68 } 69 70 func TestChannelJob(t *testing.T) { 71 job := &channelJobImpl{ 72 name: "ChannelJob", 73 runTime: 1 * time.Second, 74 ready: false, 75 stopChan: make(chan interface{}), 76 jobMutex: &sync.Mutex{}, 77 readyMutex: &sync.Mutex{}, 78 } 79 80 jobID, _ := RegisterChannelJob(job, job.stopChan) 81 globalPool.jobs[jobID].(*channelJob).setBackoff(newBackoffTimeout(time.Millisecond, time.Millisecond, 1)) 82 83 statuses := []JobStatus{JobStatusRunning} 84 ctx, cancelFunc := context.WithTimeout(context.Background(), time.Second*10) 85 defer cancelFunc() 86 87 testDone := make(chan interface{}) 88 89 go statusWaiter(ctx, t, statuses, jobID, testDone) 90 91 job.setReady(true) 92 <-testDone 93 94 assert.Nil(t, ctx.Err()) 95 UnregisterJob(jobID) 96 } 97 98 func TestDetachedChannelJob(t *testing.T) { 99 job := &channelJobImpl{ 100 name: "DetachedChannelJob", 101 runTime: 5 * time.Millisecond, 102 ready: false, 103 stopChan: make(chan interface{}), 104 jobMutex: &sync.Mutex{}, 105 readyMutex: &sync.Mutex{}, 106 } 107 108 jobID, _ := RegisterDetachedChannelJob(job, job.stopChan) 109 assert.NotEmpty(t, jobID) 110 j := globalPool.detachedCronJobs[jobID] 111 assert.NotNil(t, j) 112 113 j = globalPool.cronJobs[jobID] 114 assert.Nil(t, j) 115 UnregisterJob(jobID) 116 }