github.com/Axway/agent-sdk@v1.1.101/pkg/jobs/retryjob_test.go (about)

     1  package jobs
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"sync"
     7  	"testing"
     8  	"time"
     9  
    10  	"github.com/stretchr/testify/assert"
    11  )
    12  
    13  type retryJobImpl struct {
    14  	Job
    15  	name     string
    16  	runTime  time.Duration
    17  	fails    int
    18  	ready    bool
    19  	jobMutex *sync.Mutex
    20  }
    21  
    22  func (j *retryJobImpl) Execute() error {
    23  	for j.fails > 0 {
    24  		j.fails--
    25  		time.Sleep(j.runTime)
    26  		return fmt.Errorf("retry job failed")
    27  	}
    28  
    29  	return nil
    30  }
    31  
    32  func (j *retryJobImpl) Status() error {
    33  	return nil
    34  }
    35  
    36  func (j *retryJobImpl) Ready() bool {
    37  	j.jobMutex.Lock()
    38  	defer j.jobMutex.Unlock()
    39  	return j.ready
    40  }
    41  
    42  func (j *retryJobImpl) setReady(ready bool) {
    43  	j.jobMutex.Lock()
    44  	defer j.jobMutex.Unlock()
    45  	j.ready = ready
    46  }
    47  func TestRetryJob(t *testing.T) {
    48  	job := &retryJobImpl{
    49  		name:     "RetryJob",
    50  		runTime:  500 * time.Millisecond,
    51  		fails:    2,
    52  		ready:    false,
    53  		jobMutex: &sync.Mutex{},
    54  	}
    55  
    56  	jobID, _ := RegisterRetryJob(job, 3)
    57  	globalPool.jobs[jobID].(*retryJob).setBackoff(newBackoffTimeout(time.Millisecond, time.Millisecond, 1))
    58  
    59  	statuses := []JobStatus{JobStatusRunning, JobStatusRetrying, JobStatusFinished}
    60  	ctx, cancelFunc := context.WithTimeout(context.Background(), time.Second*10)
    61  	defer cancelFunc()
    62  
    63  	testDone := make(chan interface{})
    64  
    65  	go statusWaiter(ctx, t, statuses, jobID, testDone)
    66  
    67  	job.setReady(true)
    68  	<-testDone
    69  
    70  	assert.Nil(t, ctx.Err())
    71  	UnregisterJob(jobID)
    72  }