github.com/ChicK00o/awgo@v0.29.4/background_test.go (about)

     1  // Copyright (c) 2018 Dean Jackson <deanishe@deanishe.net>
     2  // MIT Licence - http://opensource.org/licenses/MIT
     3  
     4  package aw
     5  
     6  import (
     7  	"fmt"
     8  	"io/ioutil"
     9  	"os/exec"
    10  	"strings"
    11  	"testing"
    12  
    13  	"github.com/stretchr/testify/assert"
    14  	"github.com/stretchr/testify/require"
    15  
    16  	"github.com/ChicK00o/awgo/util"
    17  )
    18  
    19  // Background jobs.
    20  func TestWorkflow_RunInBackground(t *testing.T) {
    21  	t.Parallel()
    22  
    23  	withTestWf(func(wf *Workflow) {
    24  		jobName := "sleep"
    25  
    26  		cmd := exec.Command("sleep", "5")
    27  		// Sanity check
    28  		require.False(t, wf.IsRunning(jobName), "job already running")
    29  
    30  		// Start job
    31  		require.Nil(t, wf.RunInBackground(jobName, cmd), "start job failed")
    32  
    33  		// Job running?
    34  		assert.True(t, wf.IsRunning(jobName), "job is not running")
    35  
    36  		pid, err := wf.getPid(jobName)
    37  		assert.Nil(t, err, "get PID failed")
    38  
    39  		p := wf.pidFile(jobName)
    40  		assert.True(t, util.PathExists(p), "PID file does not exist")
    41  
    42  		// Duplicate job fails?
    43  		cmd = exec.Command("sleep", "5")
    44  		err = wf.RunInBackground("sleep", cmd)
    45  		require.NotNil(t, err, "start duplicate job did not fail")
    46  		_, ok := err.(ErrJobExists)
    47  		require.True(t, ok, "RunInBackground did not return ErrJobExists")
    48  		assert.True(t, IsJobExists(err), "IsJobExist failed to identify ErrJobExists")
    49  		assert.NotEqual(t, -1, strings.Index(err.Error(), fmt.Sprintf("%d", pid)), "PID not found in error")
    50  
    51  		// Job killed OK?
    52  		require.Nil(t, wf.Kill(jobName), "kill job failed")
    53  
    54  		// Killing dead job fails?
    55  		require.NotNil(t, wf.Kill(jobName), "kill dead job succeeded")
    56  
    57  		// Job has exited and tidied up?
    58  		assert.False(t, wf.IsRunning(jobName), "job still running")
    59  		assert.False(t, util.PathExists(p), "PID file not deleted")
    60  
    61  		// Invalid PID returns error?
    62  		err = ioutil.WriteFile(p, []byte("bad PID"), 0600)
    63  		require.Nil(t, err, "write PID file failed")
    64  
    65  		assert.NotNil(t, wf.Kill(jobName), "invalid PID did not cause error")
    66  	})
    67  }
    68  
    69  // invalid command fails
    70  func TestWorkflow_RunInBackground_badJob(t *testing.T) {
    71  	t.Parallel()
    72  
    73  	withTestWf(func(wf *Workflow) {
    74  		cmd := exec.Command("/does/not/exist")
    75  		assert.NotNil(t, wf.RunInBackground("badJob", cmd), `run "/does/not/exist" succeeded`)
    76  	})
    77  }