github.com/Axway/agent-sdk@v1.1.101/pkg/jobs/basejob_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 singleJobImpl struct {
    13  	Job
    14  	name      string
    15  	runTime   time.Duration
    16  	ready     bool
    17  	readyLock *sync.Mutex
    18  }
    19  
    20  func (j *singleJobImpl) Execute() error {
    21  	time.Sleep(j.runTime)
    22  	return nil
    23  }
    24  
    25  func (j *singleJobImpl) Status() error {
    26  	return nil
    27  }
    28  
    29  func (j *singleJobImpl) Ready() bool {
    30  	j.readyLock.Lock()
    31  	defer j.readyLock.Unlock()
    32  	return j.ready
    33  }
    34  
    35  func (j *singleJobImpl) setReady(ready bool) {
    36  	j.readyLock.Lock()
    37  	defer j.readyLock.Unlock()
    38  	j.ready = ready
    39  }
    40  
    41  func statusWaiter(ctx context.Context, t *testing.T, statuses []JobStatus, jobID string, doneChan chan interface{}) {
    42  	for _, status := range statuses {
    43  		for {
    44  			select {
    45  			case <-ctx.Done():
    46  				assert.Fail(t, "did not get all statuses")
    47  				doneChan <- nil
    48  				return
    49  			default:
    50  			}
    51  			curStat := GetJobStatus(jobID)
    52  			if curStat == jobStatusToString[status] {
    53  				break
    54  			}
    55  		}
    56  	}
    57  
    58  	doneChan <- nil
    59  }
    60  
    61  func TestSingleRunJob(t *testing.T) {
    62  	job := &singleJobImpl{
    63  		name:      "SingleJob",
    64  		runTime:   1 * time.Second,
    65  		ready:     false,
    66  		readyLock: &sync.Mutex{},
    67  	}
    68  
    69  	jobID, _ := RegisterSingleRunJob(job)
    70  	globalPool.jobs[jobID].(*baseJob).setBackoff(newBackoffTimeout(time.Millisecond, time.Millisecond, 1))
    71  
    72  	statuses := []JobStatus{JobStatusRunning, JobStatusFinished}
    73  	ctx, cancelFunc := context.WithTimeout(context.Background(), time.Second*10)
    74  	defer cancelFunc()
    75  
    76  	testDone := make(chan interface{})
    77  
    78  	go statusWaiter(ctx, t, statuses, jobID, testDone)
    79  
    80  	job.setReady(true)
    81  	<-testDone
    82  
    83  	assert.Nil(t, ctx.Err())
    84  	UnregisterJob(jobID)
    85  }