github.com/bkosm/gompose/v2@v2.3.1/readyonstdout_test.go (about)

     1  package gompose
     2  
     3  import (
     4  	"fmt"
     5  	"os/exec"
     6  	"testing"
     7  	"time"
     8  )
     9  
    10  func TestReadyOnStdout(t *testing.T) {
    11  	t.Parallel()
    12  
    13  	t.Run("marks ready when a specified phrase occurs in N lines", func(t *testing.T) {
    14  		t.Parallel()
    15  
    16  		cmd := exec.Command("echo", "1\n2\n3\n2\n")
    17  		rc := ReadyOnStdout(cmd, "2", Times(2))
    18  
    19  		select {
    20  		case err := <-rc:
    21  			assertNoError(t, err)
    22  		case <-time.After(time.Second):
    23  			t.Fatal("was not ready in time")
    24  		}
    25  	})
    26  
    27  	t.Run("returns immediate success if times is 0", func(t *testing.T) {
    28  		t.Parallel()
    29  
    30  		cmd := exec.Command("pwd")
    31  		rc := ReadyOnStdout(cmd, "dk", Times(0))
    32  
    33  		select {
    34  		case err := <-rc:
    35  			assertNoError(t, err)
    36  		case <-time.After(15 * time.Millisecond):
    37  			t.Fatal("was not ready in time")
    38  		}
    39  	})
    40  
    41  	t.Run("fails immediately with command issues", func(t *testing.T) {
    42  		t.Parallel()
    43  
    44  		cmd := exec.Command("this-shouldnt-work")
    45  		rc := ReadyOnStdout(cmd, "")
    46  
    47  		select {
    48  		case err := <-rc:
    49  			assertError(t, err)
    50  		case <-time.After(time.Second):
    51  			t.Fatal("was not ready in time")
    52  		}
    53  	})
    54  
    55  	t.Run("times out after provided duration and returns an error", func(t *testing.T) {
    56  		t.Parallel()
    57  
    58  		cmd := exec.Command("pwd")
    59  		rc := ReadyOnStdout(cmd, "nope", Timeout(time.Millisecond))
    60  
    61  		select {
    62  		case err := <-rc:
    63  			assertError(t, err, ErrWaitTimedOut)
    64  		case <-time.After(3 * time.Millisecond):
    65  			t.Fatal("did not time out in time")
    66  		}
    67  	})
    68  
    69  	t.Run("poll interval can be adjusted", func(t *testing.T) {
    70  		t.Parallel()
    71  
    72  		c := `
    73  		if [[ ! -e ./pit1 ]]
    74  		then
    75  			touch ./pit1
    76  		else
    77  			rm ./pit1 && echo "ok"
    78  		fi
    79  		`
    80  		cmd := exec.Command("bash", "-c", c)
    81  		rc := ReadyOnStdout(cmd, "ok", PollInterval(time.Millisecond))
    82  
    83  		select {
    84  		case err := <-rc:
    85  			assertNoError(t, err)
    86  		case <-time.After(80 * time.Millisecond): // default is 100ms
    87  			t.Fatal("did not complete in time")
    88  		}
    89  	})
    90  }
    91  
    92  func ExampleReadyOnStdout() {
    93  	cmd := exec.Command("echo", `
    94  		wow this
    95  		is actually
    96  		quite versatile
    97  		wow
    98  	`)
    99  	ch := ReadyOnStdout(cmd, "wow", Times(2))
   100  
   101  	<-ch
   102  	fmt.Println("that indeed happened")
   103  	// Output:
   104  	// that indeed happened
   105  }